Delete System.Data.SqlClient package (#2275)
authorJan Kotas <jkotas@microsoft.com>
Wed, 5 Feb 2020 18:51:03 +0000 (10:51 -0800)
committerGitHub <noreply@github.com>
Wed, 5 Feb 2020 18:51:03 +0000 (10:51 -0800)
* Delete System.Data.SqlClient package

* Delete unnecessary SqlClient references

* Unify System.Data.SqlClient package reference

* Add System.Data facade test

* Add System.Data.SqlClient references
- Add System.Data.SqlClient package references for tests that need it
- Use System.Data.SqlClient reference assembly to build the System.Data shim
- Disable ILLinker for the shims since it does not work well with incremental builds and it is not necessary anyway

* Disable tests on Mono

Fixes https://github.com/dotnet/corefx/issues/40846

582 files changed:
.config/CredScanSuppressions.json
eng/Versions.props
src/coreclr/tests/scripts/run-corefx-tests.bat
src/libraries/Native/pkg/Directory.Build.props [deleted file]
src/libraries/Native/pkg/Directory.Build.targets [deleted file]
src/libraries/Native/pkg/_.pdb [deleted file]
src/libraries/Native/pkg/runtime.native.System.Data.SqlClient.sni/runtime.native.System.Data.SqlClient.sni.pkgproj [deleted file]
src/libraries/System.Data.Common/tests/System.Data.Common.Tests.csproj
src/libraries/System.Data.Common/tests/System/Data/FacadeTest.cs [new file with mode: 0644]
src/libraries/System.Data.OleDb/src/DbConnectionStringCommon.cs
src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj
src/libraries/System.Data.SqlClient/Directory.Build.props [deleted file]
src/libraries/System.Data.SqlClient/System.Data.SqlClient.sln [deleted file]
src/libraries/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj [deleted file]
src/libraries/System.Data.SqlClient/ref/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.Forwards.cs [deleted file]
src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.Manual.cs [deleted file]
src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.NetCoreApp.cs [deleted file]
src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.cs [deleted file]
src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.csproj [deleted file]
src/libraries/System.Data.SqlClient/src/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/src/GenerateThisAssemblyCs.targets [deleted file]
src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Common.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/MatchingRefApiCompatBaseline.netstandard2.0.txt [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ExtendedClrTypeCode.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedGetters.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedGettersV3.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedSetters.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedSettersV3.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/MemoryRecordBuffer.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/MetadataUtilsSmi.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiEventSink.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiEventSink_Default.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiGettersStream.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiMetaData.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiMetaDataProperty.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiRecordBuffer.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiSettersStream.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiTypedGetterSetter.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiXetterAccessMap.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiXetterTypeCode.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlDataRecord.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlFacetAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlRecordBuffer.cs [deleted file]
src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ValueUtilsSmi.cs [deleted file]
src/libraries/System.Data.SqlClient/src/PinvokeAnalyzerExceptionList.analyzerdata.windows [deleted file]
src/libraries/System.Data.SqlClient/src/Resources/Strings.resx [deleted file]
src/libraries/System.Data.SqlClient/src/Resources/System.Data.SqlClient.SqlMetaData.xml [deleted file]
src/libraries/System.Data.SqlClient/src/System.Data.SqlClient.TypeForwards.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System.Data.SqlClient.csproj [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Common/ActivityCorrelator.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.NetCoreApp.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Common/SR.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/DataException.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/OperationAbortedException.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.NetCoreApp.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolProviderInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/IBinarySerialize.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/InvalidUdtException.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlFunctionAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlMetaData.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlMethodAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlNorm.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlNotificationRequest.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlSer.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlUserDefinedAggregateAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlUserDefinedTypeAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/ApplicationIntent.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Common.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/OnChangedEventHandler.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PacketHandle.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PacketHandle.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/ParameterPeekAheadValue.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PoolBlockingPeriod.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/RowsCopiedEventArgs.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/RowsCopiedEventHandler.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNICommon.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIError.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIHandle.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNILoadHandle.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsConnection.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsHandle.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsQueuedPacket.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIPacket.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIProxy.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SSRP.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SslOverTdsStream.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SspiClientContextStatus.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SessionHandle.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SessionHandle.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SortOrder.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBuffer.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopy.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyColumnMapping.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyColumnMappingCollection.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyOptions.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCachedBuffer.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientDiagnosticListenerExtensions.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientFactory.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientMetaDataCollectionNames.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommandBuilder.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommandSet.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolKey.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolProviderInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.NetCoreApp.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.NetCoreApp.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionTimeoutErrorInternal.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCredential.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataAdapter.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDbColumn.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.NetCoreApp.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.NetStandard.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependency.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyListener.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyUtils.AppDomain.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyUtils.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlEnums.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlError.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlErrorCollection.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlException.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlFileStream.Unsupported.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlFileStream.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInfoMessageEvent.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInfoMessageEventHandler.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalTransaction.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlMetadataFactory.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationEventArgs.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationSource.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationType.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterCollection.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterCollectionHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlReferenceCollection.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatedEvent.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatedEventHandler.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatingEvent.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatingEventHandler.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlSequentialStream.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlSequentialTextReader.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlStatistics.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlStream.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlTransaction.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlUdtInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParameterSetter.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.NetCoreApp.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.NetStandard.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.RegisterEncoding.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserHelperClasses.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserSafeHandles.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserSessionPool.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObject.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectFactory.Managed.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectManaged.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectNative.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStaticMethods.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsRecordBufferSetter.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsValueSetter.cs [deleted file]
src/libraries/System.Data.SqlClient/src/System/Data/SqlTypes/SqlTypeWorkarounds.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/AADAccessTokenTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/AssemblyInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/BaseProviderAsyncTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockCommand.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockConnection.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockDataReader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/CloneTests.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/DiagnosticTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/FakeDiagnosticListenerObserver.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlBulkCopyColumnMappingCollectionTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlClientFactoryTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.RetrieveStatistics.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlCredentialTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlDataRecordTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlErrorCollectionTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlFacetAttributeTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlMetaDataTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlParameterTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/FunctionalTests/TestTdsServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDAsyncTest/DDAsyncTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/DDDataTypesTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/data.xml [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDMARSTest/DDMARSTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataSourceBuilder.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/ProxyServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/SystemDataResourceManager.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.bsl [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ConcurrentLoadContext.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ReaderTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/README.md [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/RunTests.cmd [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecAsyncTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecReaderAsyncTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/XmlReaderAsyncTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/CommandCancelTest/CommandCancelTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/AsyncDebugScope.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/ConnectionPoolWrapper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/InternalConnectionWrapper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataExtensions.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/CommandHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/ConnectionHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/ConnectionPoolHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/DataReaderHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserStateObjectHelper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/ConnectionPoolTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/PoolBlockPeriodTest.netcoreapp.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/AADAccessTokenTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataBaseSchemaTest/ConnectionSchemaTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DateTimeTest/DateTimeTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/IntegratedAuthenticationTest/IntegratedAuthenticationTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/LocalDBTest/LocalDBTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MARSSessionPoolingTest/MARSSessionPoolingTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/DateTimeVariantTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/OutputParameter.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlAdapterUpdateBatch.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlParameterTest_DebugMode.bsl [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlParameterTest_ReleaseMode.bsl [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlVariantParam.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteParam.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/StePermutationSet.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteTypeBoundaries.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/StreamInputParam.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/RandomStressTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/Randomizer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/RandomizerPool.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomColumnOptions.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTable.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTableColumn.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypeInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypeInfoCollection.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypesForSqlServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomizer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SplitPacketTest/SplitPacketTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/AdjustPrecScaleForBulkCopy.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/AzureDistributedTransaction.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug84548.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug85007.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug903514.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug98182.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CheckConstraints.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/ColumnCollation.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReader1.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderCancelAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseOnEventAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyMultipleReaders.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromDatatable.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromDatatableAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromReader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromRowArray.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromRowArrayAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyVariants.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWidenNullInexactNumerics.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent1.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEventAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/ErrorOnRowsMarkedAsDeleted.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/FireTrigger.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Helpers.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumn.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetTable.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SpecialCharacterNames.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction1.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction2.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction3.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction4.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/TransactionTestAsync.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlCredentialTest/SqlCredentialTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlFileStreamTest/SqlFileStreamTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlNamedPipesTest/SqlNamedPipesTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlNotificationTest/SqlNotificationTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlSchemaInfoTest/SqlSchemaInfoTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.snk [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Address.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Address.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Circle.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Circle.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Point1.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Line.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Point.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Shapes.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Utf8String.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Utf8String.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtBulkCopyTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTestHelpers.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Utf8SupportTest/Utf8SupportTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/WeakRefTest/WeakRefTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/WeakRefTestYukonSpecific/WeakRefTestYukonSpecific.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/XUnitAssemblyAttributes.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/ManualTests/createUdtTestDb_corefx.sql [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/IMonitorLoader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/IMonitorLoader.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/MonitorMetrics.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/FilteredDefaultTraceListener.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/HostsFileManager.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/MultiSubnetFailoverSetup.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/NetUtils.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/SqlClientStressFactory.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/SqlClientTestGroup.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/System.Data.SqlClient.Stress.Tests.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/AsyncUtils.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataSource.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressConnection.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressFactory.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressReader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressSettings.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataTestGroup.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/Extensions.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/StressConfigReader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/StressTest.config [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/System.Data.StressFramework.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/TrackedRandom.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Constants.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/DeadlockDetection.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/DeadlockDetectionTaskScheduler.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/FakeConsole.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalExceptionHandlerAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalTestCleanupAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalTestSetupAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/ITestAttributeFilter.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Logger.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MemApi.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MemApi.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MonitorLoadUtils.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MultithreadedTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/PerfCounters.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Program.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/RecordedExceptions.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/SqlScript.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/StressEngine.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/StressTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/System.Data.StressRunner.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Test.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestBase.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestCleanupAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestFinder.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestMetrics.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestSetupAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestVariationAttribute.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/ThreadPoolTest.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/VersionUtil.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/FederatedAuthenticationTicketService.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/IFederatedAuthenticationTicket.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/Rps.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/RpsTicket.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSClient.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSClientContext.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSServerSession.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/PlaceholderStream.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIContext.Unix.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIContext.Windows.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIResponse.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBuffer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferDesc.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferDescType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecConstants.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecContextRequirements.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecDataRepresentation.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecPgkCredentials.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecPkgInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecResult.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityHandle.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityInteger.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityWrapper.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDS.EndPoint.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSClientEndPoint.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSClientParser.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSEndPointInfo.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSEndPointTransportType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSParser.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerEndPoint.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerEndPointConnection.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerParser.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/ApplicationIntentFilterType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/AuthenticatingTDSServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/AuthenticatingTDSServerArguments.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/DateFormatString.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSScenarioType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSServerArguments.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/GenericTDSServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/GenericTDSServerSession.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/QueryEngine.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/RoutingTDSServer.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/RoutingTDSServerArguments.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/ServerNameFilterType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TDS.Servers.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TDSServerArguments.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TdsServerCertificate.pfx [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSAllHeaders.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSHeaderType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSQueryNotificationsHeader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSTraceHeader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSTransactionDescriptorHeader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AutoTDSStream.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColInfoToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColumnProperty.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColumnStatus.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColMetadataToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnData.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataCollation.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataFlags.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataUpdatableFlag.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSDecimalColumnSpecific.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSShilohVarCharColumnSpecific.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Configurations.props [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/DateFormatType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneInProcToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneProcedureToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneTokenCommandType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneTokenStatusType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSEnvChangeToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSEnvChangeTokenType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSRoutingEnvChangeTokenValue.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSRoutingEnvChangeTokenValueType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Error/TDSErrorToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckFederatedAuthenticationOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckGenericOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckSessionStateOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoId.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOptionSPN.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOptionSTSURL.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthMessage/TDSFedAuthMessageToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/IDeflatable.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/IInflatable.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Info/TDSInfoToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LanguageString.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LanguageType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FeatureOptionToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FeatureOptionsToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FedAuthOptionToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7GenericOptionToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7SessionRecoveryOptionToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7Token.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOffsetProperty.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags1.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags2.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags3.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenTypeFlags.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LoginAck/TDSLoginAckToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Order/TDSOrderToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginAuthenticationType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenEncryptionType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenOptionType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ReturnStatus/TDSReturnStatusToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSNBCRowToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSRowToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSRowTokenBase.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SQLBatch/TDSSQLBatchToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SSPI/TDSSSPIClientToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SSPI/TDSSSPIToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionRecoveryData.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateContextInfoOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateDateFirstDateFormatOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateDeadlockPriorityOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateGenericOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateISOFipsOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateLockTimeoutOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateTextSizeOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateUserOptionsOption.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDS.csproj [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSClientState.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSDataType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSEncryptionType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSFeatureID.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessage.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessageCollection.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessageType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketHeader.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketStatus.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketToken.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSStream.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSTokenFactory.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSTokenType.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSUtilities.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSVersion.cs [deleted file]
src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TransactionIsolationLevelType.cs [deleted file]
src/libraries/System.Runtime.Serialization.Formatters/tests/System.Runtime.Serialization.Formatters.Tests.csproj
src/libraries/pkg/Microsoft.Windows.Compatibility/Microsoft.Windows.Compatibility.pkgproj
src/libraries/restore/binplacePackages/binplacePackages.depproj
src/libraries/shims/Directory.Build.props
src/libraries/shims/manual/System.Data.csproj
src/mono/netcore/CoreFX.issues.rsp
src/mono/netcore/CoreFX.issues_windows.rsp

index 0dabb70..ce1383f 100644 (file)
       "/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs",
       "/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAKeyFileTests.cs",
       "/src/libraries/System.Data.Common/tests/System/Data/Common/DbConnectionStringBuilderTest.cs",
-      "/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs",
-      "/src/libraries/System.Data.SqlClient/tests/FunctionalTests/DiagnosticTest.cs",
-      "/src/libraries/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs",
-      "/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs",
-      "/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TDSServerArguments.cs",
-      "/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TdsServerCertificate.pfx",
       "/src/libraries/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs",
       "/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/constants.cs",
       "/src/libraries/System.DirectoryServices.AccountManagement/tests/PrincipalTest.cs",
index febaad0..a579595 100644 (file)
     <RefOnlyMicrosoftBuildUtilitiesCoreVersion>$(RefOnlyMicrosoftBuildVersion)</RefOnlyMicrosoftBuildUtilitiesCoreVersion>
     <RefOnlyNugetProjectModelVersion>4.9.4</RefOnlyNugetProjectModelVersion>
     <RefOnlyNugetPackagingVersion>4.9.4</RefOnlyNugetPackagingVersion>
-    <!-- sni -->
-    <RuntimeWinX64RuntimeNativeSystemDataSqlClientSniVersion>4.4.0</RuntimeWinX64RuntimeNativeSystemDataSqlClientSniVersion>
+    <!-- System.Data.SqlClient -->
+    <SystemDataSqlClientVersion>4.8.0</SystemDataSqlClientVersion>
     <!-- Testing -->
     <MicrosoftNETTestSdkVersion>16.5.0</MicrosoftNETTestSdkVersion>
     <XUnitVersion>2.4.1</XUnitVersion>
index 1b6e691..e5bfa98 100644 (file)
@@ -27,7 +27,7 @@ echo control, but is easy to implement. This file should be a list of assembly n
 echo without filename extension, one per line, e.g.:
 echo.
 echo     System.Console.Tests
-echo     System.Data.SqlClient.Tests
+echo     System.Data.Common.Tests
 echo     System.Diagnostics.Process.Tests
 echo.
 echo The ^<exclusion rsp file^> is in the form expected by xunit.console.dll as a response file.
diff --git a/src/libraries/Native/pkg/Directory.Build.props b/src/libraries/Native/pkg/Directory.Build.props
deleted file mode 100644 (file)
index 5e62617..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-<Project>
-  <Import Project="..\..\Directory.Build.props" />
-
-  <PropertyGroup>
-    <!-- common properties that point to output of native build.  Can be overriden in case of 
-         a coordinating build that produces all packages from OS-specific native builds -->
-    <LinuxNativePath Condition="'$(LinuxNativePath)' == ''">$(ArtifactsBinDir)Linux.$(PackagePlatform).$(ConfigurationGroup)\native\</LinuxNativePath>
-    <WinNativeAOTPath Condition="'$(WinNativeAOTPath)' == ''">$(ArtifactsBinDir)Windows_NT.$(PackagePlatform).$(ConfigurationGroup)\native_aot\</WinNativeAOTPath>
-    <WinNativePath Condition="'$(WinNativePath)' == ''">$(ArtifactsBinDir)Windows_NT.$(PackagePlatform).$(ConfigurationGroup)\native\</WinNativePath>
-    <RHELNativePath Condition="'$(RHELNativePath)' == ''">$(LinuxNativePath)</RHELNativePath>
-    <DebianNativePath Condition="'$(DebianNativePath)' == ''">$(LinuxNativePath)</DebianNativePath>
-    <Fedora24NativePath Condition="'$(Fedora24NativePath)' == ''">$(LinuxNativePath)</Fedora24NativePath>
-    <OSXNativePath Condition="'$(OSXNativePath)' == ''">$(ArtifactsBinDir)OSX.$(PackagePlatform).$(ConfigurationGroup)\native\</OSXNativePath>
-    <OpenSuse132NativePath Condition="'$(OpenSuse132NativePath)' == ''">$(LinuxNativePath)</OpenSuse132NativePath>
-    <OpenSuse421NativePath Condition="'$(OpenSuse421NativePath)' == ''">$(LinuxNativePath)</OpenSuse421NativePath>
-    <Ubuntu1404NativePath Condition="'$(Ubuntu1404NativePath)' == ''">$(LinuxNativePath)</Ubuntu1404NativePath>
-    <Ubuntu1604NativePath Condition="'$(Ubuntu1604NativePath)' == ''">$(LinuxNativePath)</Ubuntu1604NativePath>
-    <Ubuntu1610NativePath Condition="'$(Ubuntu1610NativePath)' == ''">$(LinuxNativePath)</Ubuntu1610NativePath>
-    <Alpine343NativePath Condition="'$(Alpine343NativePath)' == ''">$(LinuxNativePath)</Alpine343NativePath>
-    <Tizen400NativePath Condition="'$(Tizen400NativePath)' == ''">$(LinuxNativePath)</Tizen400NativePath>
-    <SkipPackageFileCheck>true</SkipPackageFileCheck>
-  </PropertyGroup>
-</Project>
diff --git a/src/libraries/Native/pkg/Directory.Build.targets b/src/libraries/Native/pkg/Directory.Build.targets
deleted file mode 100644 (file)
index be65b4a..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-<Project>
-
-  <!-- Add path globs specific to native binaries to exclude unnecessary files from packages. -->
-  <Choose>
-    <When Condition="$(PackageTargetRuntime.StartsWith('win'))" />
-    <When Condition="$(PackageTargetRuntime.StartsWith('osx'))">
-      <PropertyGroup>
-        <LibraryFileExtension>.dylib</LibraryFileExtension>
-        <SymbolFileExtension>.dwarf</SymbolFileExtension>
-      </PropertyGroup>
-    </When>
-    <Otherwise>
-      <PropertyGroup>
-        <LibraryFileExtension>.so</LibraryFileExtension>
-        <SymbolFileExtension>.dbg</SymbolFileExtension>
-      </PropertyGroup>
-    </Otherwise>
-  </Choose>
-
-  <ItemGroup>
-    <AdditionalLibPackageExcludes Condition="'$(SymbolFileExtension)' != ''" Include="%2A%2A\%2A$(SymbolFileExtension)" />
-    <AdditionalSymbolPackageExcludes Condition="'$(LibraryFileExtension)' != ''" Include="%2A%2A\%2A.a;%2A%2A\%2A$(LibraryFileExtension)" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <File Include="@(NativeFile)" />
-  </ItemGroup>
-
-  <Target Name="GetSymbolPackageFiles" BeforeTargets="GetPackageFiles">
-    <ItemGroup>
-      <!-- On Windows, trim ".dll" before adding ".pdb". On xplat, the symbol extension is simply appended. -->
-      <NativeDllFileWithoutExtension Include="@(NativeFile -> '%(RootDir)%(Directory)%(Filename)')" Condition="'%(NativeFile.Extension)'=='.dll'" />
-      <NativeSoFile Include="@(NativeFile)" Condition="'%(NativeFile.Extension)'=='.so'" />
-      <NativeDylibFile Include="@(NativeFile)" Condition="'%(NativeFile.Extension)'=='.dylib'" />
-
-      <WindowsSymbolFile Include="@(NativeDllFileWithoutExtension -> '%(Identity).pdb')" />
-      <NonWindowsSymbolFile Include="@(NativeSoFile -> '%(Identity).dbg')" />
-      <NonWindowsSymbolFile Include="@(NativeDylibFile -> '%(Identity).dwarf')" />
-
-      <ExistingWindowsSymbolFile Include="@(WindowsSymbolFile)" Condition="Exists('%(Identity)')" />
-      <ExistingNonWindowsSymbolFile Include="@(NonWindowsSymbolFile)" Condition="Exists('%(Identity)') and '$(SkipPackagingXplatSymbols)'!='true'" />
-
-      <File Include="@(ExistingWindowsSymbolFile);@(ExistingNonWindowsSymbolFile)">
-        <IsSymbolFile>true</IsSymbolFile>
-      </File>
-    </ItemGroup>
-
-    <PropertyGroup>
-      <NeedsPlaceholderPdb Condition="'@(ExistingNonWindowsSymbolFile)'!='' and '@(ExistingWindowsSymbolFile)'==''">true</NeedsPlaceholderPdb>
-    </PropertyGroup>
-
-    <ItemGroup>
-      <File Include="$(MSBuildThisFileDirectory)\_.pdb" Condition="'$(NeedsPlaceholderPdb)'=='true' and '$(PackageTargetRuntime)'!=''">
-        <TargetPath>runtimes/$(PackageTargetRuntime)/native</TargetPath>
-        <IsSymbolFile>true</IsSymbolFile>
-      </File>
-    </ItemGroup>
-  </Target>
-
-  <Import Project="..\..\Directory.Build.targets" />
-</Project>
diff --git a/src/libraries/Native/pkg/_.pdb b/src/libraries/Native/pkg/_.pdb
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/src/libraries/Native/pkg/runtime.native.System.Data.SqlClient.sni/runtime.native.System.Data.SqlClient.sni.pkgproj b/src/libraries/Native/pkg/runtime.native.System.Data.SqlClient.sni/runtime.native.System.Data.SqlClient.sni.pkgproj
deleted file mode 100644 (file)
index 4759064..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-<Project DefaultTargets="Build">
-  <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" />
-  <PropertyGroup>
-    <SkipPackageFileCheck>true</SkipPackageFileCheck>
-    <SkipValidatePackage>true</SkipValidatePackage>
-  </PropertyGroup>
-  <ItemGroup>
-    <Dependency Include="runtime.win-x64.runtime.native.System.Data.SqlClient.sni">
-      <Version>$(RuntimeWinX64RuntimeNativeSystemDataSqlClientSniVersion)</Version>
-    </Dependency>
-    <Dependency Include="runtime.win-x86.runtime.native.System.Data.SqlClient.sni">
-      <Version>$(RuntimeWinX64RuntimeNativeSystemDataSqlClientSniVersion)</Version>
-    </Dependency>
-    <Dependency Include="runtime.win-arm64.runtime.native.System.Data.SqlClient.sni">
-      <Version>$(RuntimeWinX64RuntimeNativeSystemDataSqlClientSniVersion)</Version>
-    </Dependency>
-  </ItemGroup>
-  <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" />
-</Project>
index ada40ba..4b1d012 100644 (file)
@@ -76,6 +76,7 @@
     <Compile Include="System\Data\DeletedRowInaccessibleExceptionTest.cs" />
     <Compile Include="System\Data\DuplicateNameExceptionTest.cs" />
     <Compile Include="System\Data\EvaluateExceptionTest.cs" />
+    <Compile Include="System\Data\FacadeTest.cs" />
     <Compile Include="System\Data\ForeignKeyConstraintTest.cs" />
     <Compile Include="System\Data\ForeignKeyConstraintTest2.cs" />
     <Compile Include="System\Data\InRowChangingEventExceptionTest.cs" />
       <Link>Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
     </Compile>
   </ItemGroup>
+  <ItemGroup>
+    <PackageReference Include="System.Data.SqlClient" Version="$(SystemDataSqlClientVersion)" />
+  </ItemGroup>
 </Project>
diff --git a/src/libraries/System.Data.Common/tests/System/Data/FacadeTest.cs b/src/libraries/System.Data.Common/tests/System/Data/FacadeTest.cs
new file mode 100644 (file)
index 0000000..35f5ed1
--- /dev/null
@@ -0,0 +1,19 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+
+using Xunit;
+
+namespace System.Data.Tests
+{
+    public class FacadeTest
+    {
+        [Theory]
+        [InlineData("Microsoft.SqlServer.Server.SqlMetaData")] // Type from System.Data.SqlClient
+        [InlineData("System.Data.SqlTypes.SqlBytes")] // Type from System.Data.Common
+        public void TestSystemData(string typeName)
+        {
+            // Verify that the type can be loaded via .NET Framework compat facade
+            Type.GetType(typeName + ", System.Data", throwOnError: true);
+        }
+    }
+}
index 8cd0adf..cc353a0 100644 (file)
@@ -6,7 +6,6 @@ using System.Collections.Generic;
 using System.ComponentModel;
 using System.Diagnostics;
 using System.Globalization;
-using System.Data.SqlClient;
 
 namespace System.Data.Common
 {
index 55b8fda..87d4e41 100644 (file)
   <ItemGroup Condition="'$(TargetsNetFx)' != 'true'">
     <Reference Include="Microsoft.Win32.Registry" />
     <Reference Include="System.Memory" />
-    <Reference Include="System.Data.SqlClient" />
     <Reference Include="System.Configuration.ConfigurationManager" />
     <Reference Include="System.Diagnostics.PerformanceCounter" />
     <Reference Include="System.Security.Principal.Windows" />
diff --git a/src/libraries/System.Data.SqlClient/Directory.Build.props b/src/libraries/System.Data.SqlClient/Directory.Build.props
deleted file mode 100644 (file)
index 63f02a0..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-<Project>
-  <Import Project="..\Directory.Build.props" />
-  <PropertyGroup>
-    <StrongNameKeyId>Microsoft</StrongNameKeyId>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/System.Data.SqlClient.sln b/src/libraries/System.Data.SqlClient/System.Data.SqlClient.sln
deleted file mode 100644 (file)
index 3d40295..0000000
+++ /dev/null
@@ -1,173 +0,0 @@
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.27213.1
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Data.SqlClient.Tests", "tests\FunctionalTests\System.Data.SqlClient.Tests.csproj", "{F3E72F35-0351-4D67-9388-725BCAD807BA}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Address", "tests\ManualTests\SQL\UdtTest\UDTs\Address\Address.csproj", "{D1392B54-998A-4F27-BC17-4CE149117BCC}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Circle", "tests\ManualTests\SQL\UdtTest\UDTs\Circle\Circle.csproj", "{6C88F00F-9597-43AD-9E5F-9B344DA3B16F}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shapes", "tests\ManualTests\SQL\UdtTest\UDTs\Shapes\Shapes.csproj", "{B73A7063-37C3-415D-AD53-BB3DA20ABD6E}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Utf8String", "tests\ManualTests\SQL\UdtTest\UDTs\Utf8String\Utf8String.csproj", "{E0A6BB21-574B-43D9-890D-6E1144F2EE9E}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Data.SqlClient.ManualTesting.Tests", "tests\ManualTests\System.Data.SqlClient.ManualTesting.Tests.csproj", "{45DB5F86-7AE3-45C6-870D-F9357B66BDB5}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IMonitorLoader", "tests\StressTests\IMonitorLoader\IMonitorLoader.csproj", "{AF78BA88-6428-47EA-8682-442DAF8E9656}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Data.SqlClient.Stress.Tests", "tests\StressTests\System.Data.SqlClient.Stress.Tests\System.Data.SqlClient.Stress.Tests.csproj", "{B94B8E6D-3E41-4046-B758-4A2E281F74EE}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Data.StressFramework", "tests\StressTests\System.Data.StressFramework\System.Data.StressFramework.csproj", "{518A4E22-0144-4699-80AE-757B744E8E38}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Data.StressRunner", "tests\StressTests\System.Data.StressRunner\System.Data.StressRunner.csproj", "{529B187A-DE4F-4F4D-9FBB-D3D416FDB683}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TDS.EndPoint", "tests\Tools\TDS\TDS.EndPoint\TDS.EndPoint.csproj", "{1FF891B4-D3DE-4CCE-887C-CB48F5351A45}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TDS.Servers", "tests\Tools\TDS\TDS.Servers\TDS.Servers.csproj", "{978063D3-FBB5-4E10-8C45-67C90BE1B931}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TDS", "tests\Tools\TDS\TDS\TDS.csproj", "{8DC9D1A0-351B-47BC-A90F-B9DA542550E9}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {D4550556-4745-457F-BA8F-3EBF3836D6B4}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Data.SqlClient", "src\System.Data.SqlClient.csproj", "{D4550556-4745-457F-BA8F-3EBF3836D6B4}"
-       ProjectSection(ProjectDependencies) = postProject
-               {D58E8D2B-3331-4660-8DFB-512D66F8EC63} = {D58E8D2B-3331-4660-8DFB-512D66F8EC63}
-       EndProjectSection
-EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Data.SqlClient", "ref\System.Data.SqlClient.csproj", "{D58E8D2B-3331-4660-8DFB-512D66F8EC63}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{1A2F9F4A-A032-433E-B914-ADD5992BB178}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E107E9C1-E893-4E87-987E-04EF0DCEAEFD}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}"
-EndProject
-Global
-       GlobalSection(SolutionConfigurationPlatforms) = preSolution
-               Debug|Any CPU = Debug|Any CPU
-               Release|Any CPU = Release|Any CPU
-       EndGlobalSection
-       GlobalSection(ProjectConfigurationPlatforms) = postSolution
-               {F3E72F35-0351-4D67-9388-725BCAD807BA}.Debug|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {F3E72F35-0351-4D67-9388-725BCAD807BA}.Debug|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {F3E72F35-0351-4D67-9388-725BCAD807BA}.Release|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {F3E72F35-0351-4D67-9388-725BCAD807BA}.Release|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {D1392B54-998A-4F27-BC17-4CE149117BCC}.Debug|Any CPU.ActiveCfg = netstandard2.0-Debug|Any CPU
-               {D1392B54-998A-4F27-BC17-4CE149117BCC}.Debug|Any CPU.Build.0 = netstandard2.0-Debug|Any CPU
-               {D1392B54-998A-4F27-BC17-4CE149117BCC}.Release|Any CPU.ActiveCfg = netstandard2.0-Release|Any CPU
-               {D1392B54-998A-4F27-BC17-4CE149117BCC}.Release|Any CPU.Build.0 = netstandard2.0-Release|Any CPU
-               {6C88F00F-9597-43AD-9E5F-9B344DA3B16F}.Debug|Any CPU.ActiveCfg = netstandard2.0-Debug|Any CPU
-               {6C88F00F-9597-43AD-9E5F-9B344DA3B16F}.Debug|Any CPU.Build.0 = netstandard2.0-Debug|Any CPU
-               {6C88F00F-9597-43AD-9E5F-9B344DA3B16F}.Release|Any CPU.ActiveCfg = netstandard2.0-Release|Any CPU
-               {6C88F00F-9597-43AD-9E5F-9B344DA3B16F}.Release|Any CPU.Build.0 = netstandard2.0-Release|Any CPU
-               {B73A7063-37C3-415D-AD53-BB3DA20ABD6E}.Debug|Any CPU.ActiveCfg = netstandard2.0-Debug|Any CPU
-               {B73A7063-37C3-415D-AD53-BB3DA20ABD6E}.Debug|Any CPU.Build.0 = netstandard2.0-Debug|Any CPU
-               {B73A7063-37C3-415D-AD53-BB3DA20ABD6E}.Release|Any CPU.ActiveCfg = netstandard2.0-Release|Any CPU
-               {B73A7063-37C3-415D-AD53-BB3DA20ABD6E}.Release|Any CPU.Build.0 = netstandard2.0-Release|Any CPU
-               {E0A6BB21-574B-43D9-890D-6E1144F2EE9E}.Debug|Any CPU.ActiveCfg = netstandard2.0-Debug|Any CPU
-               {E0A6BB21-574B-43D9-890D-6E1144F2EE9E}.Debug|Any CPU.Build.0 = netstandard2.0-Debug|Any CPU
-               {E0A6BB21-574B-43D9-890D-6E1144F2EE9E}.Release|Any CPU.ActiveCfg = netstandard2.0-Release|Any CPU
-               {E0A6BB21-574B-43D9-890D-6E1144F2EE9E}.Release|Any CPU.Build.0 = netstandard2.0-Release|Any CPU
-               {45DB5F86-7AE3-45C6-870D-F9357B66BDB5}.Debug|Any CPU.ActiveCfg = netcoreapp5.0-Debug|Any CPU
-               {45DB5F86-7AE3-45C6-870D-F9357B66BDB5}.Debug|Any CPU.Build.0 = netcoreapp5.0-Debug|Any CPU
-               {45DB5F86-7AE3-45C6-870D-F9357B66BDB5}.Release|Any CPU.ActiveCfg = netcoreapp5.0-Release|Any CPU
-               {45DB5F86-7AE3-45C6-870D-F9357B66BDB5}.Release|Any CPU.Build.0 = netcoreapp5.0-Release|Any CPU
-               {AF78BA88-6428-47EA-8682-442DAF8E9656}.Debug|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Debug|Any CPU
-               {AF78BA88-6428-47EA-8682-442DAF8E9656}.Debug|Any CPU.Build.0 = netstandard2.0-Windows_NT-Debug|Any CPU
-               {AF78BA88-6428-47EA-8682-442DAF8E9656}.Release|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Release|Any CPU
-               {AF78BA88-6428-47EA-8682-442DAF8E9656}.Release|Any CPU.Build.0 = netstandard2.0-Windows_NT-Release|Any CPU
-               {B94B8E6D-3E41-4046-B758-4A2E281F74EE}.Debug|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {B94B8E6D-3E41-4046-B758-4A2E281F74EE}.Debug|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {B94B8E6D-3E41-4046-B758-4A2E281F74EE}.Release|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {B94B8E6D-3E41-4046-B758-4A2E281F74EE}.Release|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {518A4E22-0144-4699-80AE-757B744E8E38}.Debug|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {518A4E22-0144-4699-80AE-757B744E8E38}.Debug|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {518A4E22-0144-4699-80AE-757B744E8E38}.Release|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {518A4E22-0144-4699-80AE-757B744E8E38}.Release|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {529B187A-DE4F-4F4D-9FBB-D3D416FDB683}.Debug|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {529B187A-DE4F-4F4D-9FBB-D3D416FDB683}.Debug|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {529B187A-DE4F-4F4D-9FBB-D3D416FDB683}.Release|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {529B187A-DE4F-4F4D-9FBB-D3D416FDB683}.Release|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {1FF891B4-D3DE-4CCE-887C-CB48F5351A45}.Debug|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Debug|Any CPU
-               {1FF891B4-D3DE-4CCE-887C-CB48F5351A45}.Debug|Any CPU.Build.0 = netstandard2.0-Windows_NT-Debug|Any CPU
-               {1FF891B4-D3DE-4CCE-887C-CB48F5351A45}.Release|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Release|Any CPU
-               {1FF891B4-D3DE-4CCE-887C-CB48F5351A45}.Release|Any CPU.Build.0 = netstandard2.0-Windows_NT-Release|Any CPU
-               {978063D3-FBB5-4E10-8C45-67C90BE1B931}.Debug|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Debug|Any CPU
-               {978063D3-FBB5-4E10-8C45-67C90BE1B931}.Debug|Any CPU.Build.0 = netstandard2.0-Windows_NT-Debug|Any CPU
-               {978063D3-FBB5-4E10-8C45-67C90BE1B931}.Release|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Release|Any CPU
-               {978063D3-FBB5-4E10-8C45-67C90BE1B931}.Release|Any CPU.Build.0 = netstandard2.0-Windows_NT-Release|Any CPU
-               {8DC9D1A0-351B-47BC-A90F-B9DA542550E9}.Debug|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Debug|Any CPU
-               {8DC9D1A0-351B-47BC-A90F-B9DA542550E9}.Debug|Any CPU.Build.0 = netstandard2.0-Windows_NT-Debug|Any CPU
-               {8DC9D1A0-351B-47BC-A90F-B9DA542550E9}.Release|Any CPU.ActiveCfg = netstandard2.0-Windows_NT-Release|Any CPU
-               {8DC9D1A0-351B-47BC-A90F-B9DA542550E9}.Release|Any CPU.Build.0 = netstandard2.0-Windows_NT-Release|Any CPU
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4}.Debug|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4}.Debug|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Debug|Any CPU
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4}.Release|Any CPU.ActiveCfg = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4}.Release|Any CPU.Build.0 = netcoreapp5.0-Windows_NT-Release|Any CPU
-               {D58E8D2B-3331-4660-8DFB-512D66F8EC63}.Debug|Any CPU.ActiveCfg = netcoreapp5.0-Debug|Any CPU
-               {D58E8D2B-3331-4660-8DFB-512D66F8EC63}.Debug|Any CPU.Build.0 = netcoreapp5.0-Debug|Any CPU
-               {D58E8D2B-3331-4660-8DFB-512D66F8EC63}.Release|Any CPU.ActiveCfg = netcoreapp5.0-Release|Any CPU
-               {D58E8D2B-3331-4660-8DFB-512D66F8EC63}.Release|Any CPU.Build.0 = netcoreapp5.0-Release|Any CPU
-       EndGlobalSection
-       GlobalSection(SolutionProperties) = preSolution
-               HideSolutionNode = FALSE
-       EndGlobalSection
-       GlobalSection(NestedProjects) = preSolution
-               {F3E72F35-0351-4D67-9388-725BCAD807BA} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {D1392B54-998A-4F27-BC17-4CE149117BCC} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {6C88F00F-9597-43AD-9E5F-9B344DA3B16F} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {B73A7063-37C3-415D-AD53-BB3DA20ABD6E} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {E0A6BB21-574B-43D9-890D-6E1144F2EE9E} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {45DB5F86-7AE3-45C6-870D-F9357B66BDB5} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {AF78BA88-6428-47EA-8682-442DAF8E9656} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {B94B8E6D-3E41-4046-B758-4A2E281F74EE} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {518A4E22-0144-4699-80AE-757B744E8E38} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {529B187A-DE4F-4F4D-9FBB-D3D416FDB683} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {1FF891B4-D3DE-4CCE-887C-CB48F5351A45} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {978063D3-FBB5-4E10-8C45-67C90BE1B931} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {8DC9D1A0-351B-47BC-A90F-B9DA542550E9} = {1A2F9F4A-A032-433E-B914-ADD5992BB178}
-               {D4550556-4745-457F-BA8F-3EBF3836D6B4} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
-               {D58E8D2B-3331-4660-8DFB-512D66F8EC63} = {2E666815-2EDB-464B-9DF6-380BF4789AD4}
-       EndGlobalSection
-       GlobalSection(ExtensibilityGlobals) = postSolution
-               SolutionGuid = {D25C803E-4BF4-4DC3-BCD4-F9E7C193FF4D}
-       EndGlobalSection
-EndGlobal
diff --git a/src/libraries/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj b/src/libraries/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj
deleted file mode 100644 (file)
index 8d84db8..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-<Project DefaultTargets="Build">
-  <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props))" />
-  <ItemGroup>
-    <ProjectReference Include="..\ref\System.Data.SqlClient.csproj">
-      <SupportedFramework>netcoreapp2.1;netcoreapp3.0;netcoreapp5.0</SupportedFramework>
-    </ProjectReference>
-    <ProjectReference Include="..\src\System.Data.SqlClient.csproj" />
-    <HarvestIncludePaths Include="ref/net451;lib/net451;runtimes/win/lib/net451" />
-    <HarvestIncludePaths Include="ref/net46;lib/net46;runtimes/win/lib/net46" />
-    <HarvestIncludePaths Include="ref/netstandard1.2;lib/netstandard1.2" />
-    <HarvestIncludePaths Include="ref/netstandard1.3;lib/netstandard1.3" />
-    <HarvestIncludePaths Include="ref/netstandard2.0;lib/netstandard2.0" />
-    <HarvestIncludePaths Include="ref/net461;lib/net461;runtimes/win/lib/net461" />
-    <HarvestIncludePaths Include="runtimes/unix/lib/netstandard1.3;runtimes/win/lib/netstandard1.3" />
-    <HarvestIncludePaths Include="runtimes/win/lib/uap10.0.16299" />
-
-    <!-- Since UAP and .NETCoreApp are package based we still want to enable
-         OOBing libraries that happen to overlap with their framework package.
-         This avoids us having to lock the API in our NuGet packages just
-         to match what shipped inbox: since we can provide a new library
-         we can update it to add API without raising the netstandard version. -->
-    <ValidatePackageSuppression Include="TreatAsOutOfBox">
-      <Value>.NETCoreApp;UAP</Value>
-    </ValidatePackageSuppression>
-  </ItemGroup>
-  <ItemGroup>
-    <InboxOnTargetFramework Include="$(AllXamarinFrameworks)" />
-  </ItemGroup>
-  <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.targets))" />
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/ref/Configurations.props b/src/libraries/System.Data.SqlClient/ref/Configurations.props
deleted file mode 100644 (file)
index 96cab88..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<Project>
-  <PropertyGroup>
-    <PackageConfigurations>
-      netcoreapp2.1;
-    </PackageConfigurations>
-    <BuildConfigurations>
-      $(PackageConfigurations)
-      $(NetCoreAppCurrent);
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.Forwards.cs b/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.Forwards.cs
deleted file mode 100644 (file)
index f1a8014..0000000
+++ /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.
-// ------------------------------------------------------------------------------
-// Changes to this file must follow the http://aka.ms/api-review process.
-// ------------------------------------------------------------------------------
-
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlDbType))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.StatementCompletedEventArgs))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.StatementCompletedEventHandler))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.INullable))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlBinary))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlBoolean))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlByte))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlBytes))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlChars))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlCompareOptions))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlDateTime))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlDecimal))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlDouble))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlGuid))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlInt16))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlInt32))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlInt64))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlMoney))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlNullValueException))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlSingle))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlString))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlTruncateException))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlTypeException))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlXml))]
diff --git a/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.Manual.cs b/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.Manual.cs
deleted file mode 100644 (file)
index 245236e..0000000
+++ /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.
-// ------------------------------------------------------------------------------
-// Changes to this file must follow the http://aka.ms/api-review process.
-// ------------------------------------------------------------------------------
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlCommand : System.Data.Common.DbCommand
-    {
-        // SqlCommand expects IDisposable methods to be implemented via System.ComponentModel.Component, which it no longer inherits from
-        protected override void Dispose(bool disposing) { }
-    }
-    public sealed partial class SqlConnection : System.Data.Common.DbConnection
-    {
-        // SqlConection expects IDisposable methods to be implemented via System.ComponentModel.Component, which it no longer inherits from
-        protected override void Dispose(bool disposing) { }
-    }
-    public sealed partial class SqlConnectionStringBuilder
-    {
-        [System.ComponentModel.TypeConverter(typeof(SqlInitialCatalogConverter))]
-        public string InitialCatalog { get { throw null; } set { } }
-
-        private sealed class SqlInitialCatalogConverter { }
-    }
-
-    [System.ComponentModel.TypeConverter(typeof(SqlParameterConverter))]
-    public sealed partial class SqlParameter
-    {
-      internal class SqlParameterConverter { }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.NetCoreApp.cs b/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.NetCoreApp.cs
deleted file mode 100644 (file)
index e71dafc..0000000
+++ /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.
-// ------------------------------------------------------------------------------
-// Changes to this file must follow the http://aka.ms/api-review process.
-// ------------------------------------------------------------------------------
-
-namespace Microsoft.SqlServer.Server
-{
-    [System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false, Inherited=false)]
-    public partial class SqlFacetAttribute : System.Attribute
-    {
-        public SqlFacetAttribute() { }
-        public bool IsFixedLength { get { throw null; } set { } }
-        public bool IsNullable { get { throw null; } set { } }
-        public int MaxSize { get { throw null; } set { } }
-        public int Precision { get { throw null; } set { } }
-        public int Scale { get { throw null; } set { } }
-    }
-}
-namespace System.Data.SqlClient
-{
-    public partial class SqlDataReader : System.Data.Common.IDbColumnSchemaGenerator
-    {
-        public System.Collections.ObjectModel.ReadOnlyCollection<System.Data.Common.DbColumn> GetColumnSchema() { throw null; }
-    }
-    public enum PoolBlockingPeriod
-    {
-        Auto = 0,
-        AlwaysBlock = 1,
-        NeverBlock = 2,
-    }
-    public sealed partial class SqlConnectionStringBuilder : System.Data.Common.DbConnectionStringBuilder
-    {
-        public System.Data.SqlClient.PoolBlockingPeriod PoolBlockingPeriod { get { throw null; } set { } }
-    }
-}
-namespace System.Data.SqlTypes
-{
-    public sealed partial class SqlFileStream : System.IO.Stream
-    {
-        public SqlFileStream(string path, byte[] transactionContext, System.IO.FileAccess access) { }
-        public SqlFileStream(string path, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, long allocationSize) { }
-        public override bool CanRead { get { throw null; } }
-        public override bool CanSeek { get { throw null; } }
-        public override bool CanWrite { get { throw null; } }
-        public override long Length { get { throw null; } }
-        public string Name { get { throw null; } }
-        public override long Position { get { throw null; } set { } }
-        public byte[] TransactionContext { get { throw null; } }
-        public override void Flush() { }
-        public override int Read(byte[] buffer, int offset, int count) { throw null; }
-        public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
-        public override void SetLength(long value) { }
-        public override void Write(byte[] buffer, int offset, int count) { }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.cs b/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.cs
deleted file mode 100644 (file)
index cca1b1a..0000000
+++ /dev/null
@@ -1,845 +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.
-// ------------------------------------------------------------------------------
-// Changes to this file must follow the http://aka.ms/api-review process.
-// ------------------------------------------------------------------------------
-
-namespace Microsoft.SqlServer.Server
-{
-    public enum DataAccessKind
-    {
-        None = 0,
-        Read = 1,
-    }
-    public enum Format
-    {
-        Unknown = 0,
-        Native = 1,
-        UserDefined = 2,
-    }
-    public partial interface IBinarySerialize
-    {
-        void Read(System.IO.BinaryReader r);
-        void Write(System.IO.BinaryWriter w);
-    }
-    public sealed partial class InvalidUdtException : System.SystemException
-    {
-        internal InvalidUdtException() { }
-    }
-    public partial class SqlDataRecord : System.Data.IDataRecord
-    {
-        public SqlDataRecord(params Microsoft.SqlServer.Server.SqlMetaData[] metaData) { }
-        public virtual int FieldCount { get { throw null; } }
-        public virtual object this[int ordinal] { get { throw null; } }
-        public virtual object this[string name] { get { throw null; } }
-        public virtual bool GetBoolean(int ordinal) { throw null; }
-        public virtual byte GetByte(int ordinal) { throw null; }
-        public virtual long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { throw null; }
-        public virtual char GetChar(int ordinal) { throw null; }
-        public virtual long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) { throw null; }
-        public virtual string GetDataTypeName(int ordinal) { throw null; }
-        public virtual System.DateTime GetDateTime(int ordinal) { throw null; }
-        public virtual System.DateTimeOffset GetDateTimeOffset(int ordinal) { throw null; }
-        public virtual decimal GetDecimal(int ordinal) { throw null; }
-        public virtual double GetDouble(int ordinal) { throw null; }
-        public virtual System.Type GetFieldType(int ordinal) { throw null; }
-        public virtual float GetFloat(int ordinal) { throw null; }
-        public virtual System.Guid GetGuid(int ordinal) { throw null; }
-        public virtual short GetInt16(int ordinal) { throw null; }
-        public virtual int GetInt32(int ordinal) { throw null; }
-        public virtual long GetInt64(int ordinal) { throw null; }
-        public virtual string GetName(int ordinal) { throw null; }
-        public virtual int GetOrdinal(string name) { throw null; }
-        public virtual System.Data.SqlTypes.SqlBinary GetSqlBinary(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlBoolean GetSqlBoolean(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlByte GetSqlByte(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlBytes GetSqlBytes(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlChars GetSqlChars(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlDateTime GetSqlDateTime(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlDecimal GetSqlDecimal(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlDouble GetSqlDouble(int ordinal) { throw null; }
-        public virtual System.Type GetSqlFieldType(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlGuid GetSqlGuid(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlInt16 GetSqlInt16(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlInt32 GetSqlInt32(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlInt64 GetSqlInt64(int ordinal) { throw null; }
-        public virtual Microsoft.SqlServer.Server.SqlMetaData GetSqlMetaData(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlMoney GetSqlMoney(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlSingle GetSqlSingle(int ordinal) { throw null; }
-        public virtual System.Data.SqlTypes.SqlString GetSqlString(int ordinal) { throw null; }
-        public virtual object GetSqlValue(int ordinal) { throw null; }
-        public virtual int GetSqlValues(object[] values) { throw null; }
-        public virtual System.Data.SqlTypes.SqlXml GetSqlXml(int ordinal) { throw null; }
-        public virtual string GetString(int ordinal) { throw null; }
-        public virtual System.TimeSpan GetTimeSpan(int ordinal) { throw null; }
-        public virtual object GetValue(int ordinal) { throw null; }
-        public virtual int GetValues(object[] values) { throw null; }
-        public virtual bool IsDBNull(int ordinal) { throw null; }
-        public virtual void SetBoolean(int ordinal, bool value) { }
-        public virtual void SetByte(int ordinal, byte value) { }
-        public virtual void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { }
-        public virtual void SetChar(int ordinal, char value) { }
-        public virtual void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) { }
-        public virtual void SetDateTime(int ordinal, System.DateTime value) { }
-        public virtual void SetDateTimeOffset(int ordinal, System.DateTimeOffset value) { }
-        public virtual void SetDBNull(int ordinal) { }
-        public virtual void SetDecimal(int ordinal, decimal value) { }
-        public virtual void SetDouble(int ordinal, double value) { }
-        public virtual void SetFloat(int ordinal, float value) { }
-        public virtual void SetGuid(int ordinal, System.Guid value) { }
-        public virtual void SetInt16(int ordinal, short value) { }
-        public virtual void SetInt32(int ordinal, int value) { }
-        public virtual void SetInt64(int ordinal, long value) { }
-        public virtual void SetSqlBinary(int ordinal, System.Data.SqlTypes.SqlBinary value) { }
-        public virtual void SetSqlBoolean(int ordinal, System.Data.SqlTypes.SqlBoolean value) { }
-        public virtual void SetSqlByte(int ordinal, System.Data.SqlTypes.SqlByte value) { }
-        public virtual void SetSqlBytes(int ordinal, System.Data.SqlTypes.SqlBytes value) { }
-        public virtual void SetSqlChars(int ordinal, System.Data.SqlTypes.SqlChars value) { }
-        public virtual void SetSqlDateTime(int ordinal, System.Data.SqlTypes.SqlDateTime value) { }
-        public virtual void SetSqlDecimal(int ordinal, System.Data.SqlTypes.SqlDecimal value) { }
-        public virtual void SetSqlDouble(int ordinal, System.Data.SqlTypes.SqlDouble value) { }
-        public virtual void SetSqlGuid(int ordinal, System.Data.SqlTypes.SqlGuid value) { }
-        public virtual void SetSqlInt16(int ordinal, System.Data.SqlTypes.SqlInt16 value) { }
-        public virtual void SetSqlInt32(int ordinal, System.Data.SqlTypes.SqlInt32 value) { }
-        public virtual void SetSqlInt64(int ordinal, System.Data.SqlTypes.SqlInt64 value) { }
-        public virtual void SetSqlMoney(int ordinal, System.Data.SqlTypes.SqlMoney value) { }
-        public virtual void SetSqlSingle(int ordinal, System.Data.SqlTypes.SqlSingle value) { }
-        public virtual void SetSqlString(int ordinal, System.Data.SqlTypes.SqlString value) { }
-        public virtual void SetSqlXml(int ordinal, System.Data.SqlTypes.SqlXml value) { }
-        public virtual void SetString(int ordinal, string value) { }
-        public virtual void SetTimeSpan(int ordinal, System.TimeSpan value) { }
-        public virtual void SetValue(int ordinal, object value) { }
-        public virtual int SetValues(params object[] values) { throw null; }
-        System.Data.IDataReader System.Data.IDataRecord.GetData(int ordinal) { throw null; }
-    }
-    [System.AttributeUsageAttribute(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
-    public partial class SqlFunctionAttribute : System.Attribute
-    {
-        public SqlFunctionAttribute() { }
-        public Microsoft.SqlServer.Server.DataAccessKind DataAccess { get { throw null; } set { } }
-        public string FillRowMethodName { get { throw null; } set { } }
-        public bool IsDeterministic { get { throw null; } set { } }
-        public bool IsPrecise { get { throw null; } set { } }
-        public string Name { get { throw null; } set { } }
-        public Microsoft.SqlServer.Server.SystemDataAccessKind SystemDataAccess { get { throw null; } set { } }
-        public string TableDefinition { get { throw null; } set { } }
-    }
-    public sealed partial class SqlMetaData
-    {
-        public SqlMetaData(string name, System.Data.SqlDbType dbType) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, bool useServerDefault, bool isUniqueKey, System.Data.SqlClient.SortOrder columnSortOrder, int sortOrdinal) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, byte precision, byte scale) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, byte precision, byte scale, bool useServerDefault, bool isUniqueKey, System.Data.SqlClient.SortOrder columnSortOrder, int sortOrdinal) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, long maxLength) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, long maxLength, bool useServerDefault, bool isUniqueKey, System.Data.SqlClient.SortOrder columnSortOrder, int sortOrdinal) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, long maxLength, byte precision, byte scale, long locale, System.Data.SqlTypes.SqlCompareOptions compareOptions, System.Type userDefinedType) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, System.Data.SqlTypes.SqlCompareOptions compareOptions, System.Type userDefinedType, bool useServerDefault, bool isUniqueKey, System.Data.SqlClient.SortOrder columnSortOrder, int sortOrdinal) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, long maxLength, long locale, System.Data.SqlTypes.SqlCompareOptions compareOptions) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, long maxLength, long locale, System.Data.SqlTypes.SqlCompareOptions compareOptions, bool useServerDefault, bool isUniqueKey, System.Data.SqlClient.SortOrder columnSortOrder, int sortOrdinal) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, string database, string owningSchema, string objectName) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, string database, string owningSchema, string objectName, bool useServerDefault, bool isUniqueKey, System.Data.SqlClient.SortOrder columnSortOrder, int sortOrdinal) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, System.Type userDefinedType) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, System.Type userDefinedType, string serverTypeName) { }
-        public SqlMetaData(string name, System.Data.SqlDbType dbType, System.Type userDefinedType, string serverTypeName, bool useServerDefault, bool isUniqueKey, System.Data.SqlClient.SortOrder columnSortOrder, int sortOrdinal) { }
-        public System.Data.SqlTypes.SqlCompareOptions CompareOptions { get { throw null; } }
-        public System.Data.DbType DbType { get { throw null; } }
-        public bool IsUniqueKey { get { throw null; } }
-        public long LocaleId { get { throw null; } }
-        public static long Max { get { throw null; } }
-        public long MaxLength { get { throw null; } }
-        public string Name { get { throw null; } }
-        public byte Precision { get { throw null; } }
-        public byte Scale { get { throw null; } }
-        public System.Data.SqlClient.SortOrder SortOrder { get { throw null; } }
-        public int SortOrdinal { get { throw null; } }
-        public System.Data.SqlDbType SqlDbType { get { throw null; } }
-        public System.Type Type { get { throw null; } }
-        public string TypeName { get { throw null; } }
-        public bool UseServerDefault { get { throw null; } }
-        public string XmlSchemaCollectionDatabase { get { throw null; } }
-        public string XmlSchemaCollectionName { get { throw null; } }
-        public string XmlSchemaCollectionOwningSchema { get { throw null; } }
-        public bool Adjust(bool value) { throw null; }
-        public byte Adjust(byte value) { throw null; }
-        public byte[] Adjust(byte[] value) { throw null; }
-        public char Adjust(char value) { throw null; }
-        public char[] Adjust(char[] value) { throw null; }
-        public System.Data.SqlTypes.SqlBinary Adjust(System.Data.SqlTypes.SqlBinary value) { throw null; }
-        public System.Data.SqlTypes.SqlBoolean Adjust(System.Data.SqlTypes.SqlBoolean value) { throw null; }
-        public System.Data.SqlTypes.SqlByte Adjust(System.Data.SqlTypes.SqlByte value) { throw null; }
-        public System.Data.SqlTypes.SqlBytes Adjust(System.Data.SqlTypes.SqlBytes value) { throw null; }
-        public System.Data.SqlTypes.SqlChars Adjust(System.Data.SqlTypes.SqlChars value) { throw null; }
-        public System.Data.SqlTypes.SqlDateTime Adjust(System.Data.SqlTypes.SqlDateTime value) { throw null; }
-        public System.Data.SqlTypes.SqlDecimal Adjust(System.Data.SqlTypes.SqlDecimal value) { throw null; }
-        public System.Data.SqlTypes.SqlDouble Adjust(System.Data.SqlTypes.SqlDouble value) { throw null; }
-        public System.Data.SqlTypes.SqlGuid Adjust(System.Data.SqlTypes.SqlGuid value) { throw null; }
-        public System.Data.SqlTypes.SqlInt16 Adjust(System.Data.SqlTypes.SqlInt16 value) { throw null; }
-        public System.Data.SqlTypes.SqlInt32 Adjust(System.Data.SqlTypes.SqlInt32 value) { throw null; }
-        public System.Data.SqlTypes.SqlInt64 Adjust(System.Data.SqlTypes.SqlInt64 value) { throw null; }
-        public System.Data.SqlTypes.SqlMoney Adjust(System.Data.SqlTypes.SqlMoney value) { throw null; }
-        public System.Data.SqlTypes.SqlSingle Adjust(System.Data.SqlTypes.SqlSingle value) { throw null; }
-        public System.Data.SqlTypes.SqlString Adjust(System.Data.SqlTypes.SqlString value) { throw null; }
-        public System.Data.SqlTypes.SqlXml Adjust(System.Data.SqlTypes.SqlXml value) { throw null; }
-        public System.DateTime Adjust(System.DateTime value) { throw null; }
-        public System.DateTimeOffset Adjust(System.DateTimeOffset value) { throw null; }
-        public decimal Adjust(decimal value) { throw null; }
-        public double Adjust(double value) { throw null; }
-        public System.Guid Adjust(System.Guid value) { throw null; }
-        public short Adjust(short value) { throw null; }
-        public int Adjust(int value) { throw null; }
-        public long Adjust(long value) { throw null; }
-        public object Adjust(object value) { throw null; }
-        public float Adjust(float value) { throw null; }
-        public string Adjust(string value) { throw null; }
-        public System.TimeSpan Adjust(System.TimeSpan value) { throw null; }
-        public static Microsoft.SqlServer.Server.SqlMetaData InferFromValue(object value, string name) { throw null; }
-    }
-    [System.AttributeUsageAttribute(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
-    public sealed partial class SqlMethodAttribute : Microsoft.SqlServer.Server.SqlFunctionAttribute
-    {
-        public SqlMethodAttribute() { }
-        public bool InvokeIfReceiverIsNull { get { throw null; } set { } }
-        public bool IsMutator { get { throw null; } set { } }
-        public bool OnNullCall { get { throw null; } set { } }
-    }
-    [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=false)]
-    public sealed partial class SqlUserDefinedAggregateAttribute : System.Attribute
-    {
-        public const int MaxByteSizeValue = 8000;
-        public SqlUserDefinedAggregateAttribute(Microsoft.SqlServer.Server.Format format) { }
-        public Microsoft.SqlServer.Server.Format Format { get { throw null; } }
-        public bool IsInvariantToDuplicates { get { throw null; } set { } }
-        public bool IsInvariantToNulls { get { throw null; } set { } }
-        public bool IsInvariantToOrder { get { throw null; } set { } }
-        public bool IsNullIfEmpty { get { throw null; } set { } }
-        public int MaxByteSize { get { throw null; } set { } }
-        public string Name { get { throw null; } set { } }
-    }
-    [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=true)]
-    public sealed partial class SqlUserDefinedTypeAttribute : System.Attribute
-    {
-        public SqlUserDefinedTypeAttribute(Microsoft.SqlServer.Server.Format format) { }
-        public Microsoft.SqlServer.Server.Format Format { get { throw null; } }
-        public bool IsByteOrdered { get { throw null; } set { } }
-        public bool IsFixedLength { get { throw null; } set { } }
-        public int MaxByteSize { get { throw null; } set { } }
-        public string Name { get { throw null; } set { } }
-        public string ValidationMethodName { get { throw null; } set { } }
-    }
-    public enum SystemDataAccessKind
-    {
-        None = 0,
-        Read = 1,
-    }
-}
-namespace System.Data
-{
-    public sealed partial class OperationAbortedException : System.SystemException
-    {
-        internal OperationAbortedException() { }
-    }
-}
-namespace System.Data.Sql
-{
-    public sealed partial class SqlNotificationRequest
-    {
-        public SqlNotificationRequest() { }
-        public SqlNotificationRequest(string userData, string options, int timeout) { }
-        public string Options { get { throw null; } set { } }
-        public int Timeout { get { throw null; } set { } }
-        public string UserData { get { throw null; } set { } }
-    }
-}
-namespace System.Data.SqlClient
-{
-    public enum ApplicationIntent
-    {
-        ReadWrite = 0,
-        ReadOnly = 1,
-    }
-    public delegate void OnChangeEventHandler(object sender, System.Data.SqlClient.SqlNotificationEventArgs e);
-    public enum SortOrder
-    {
-        Unspecified = -1,
-        Ascending = 0,
-        Descending = 1,
-    }
-    public sealed partial class SqlBulkCopy : System.IDisposable
-    {
-        public SqlBulkCopy(System.Data.SqlClient.SqlConnection connection) { }
-        public SqlBulkCopy(System.Data.SqlClient.SqlConnection connection, System.Data.SqlClient.SqlBulkCopyOptions copyOptions, System.Data.SqlClient.SqlTransaction externalTransaction) { }
-        public SqlBulkCopy(string connectionString) { }
-        public SqlBulkCopy(string connectionString, System.Data.SqlClient.SqlBulkCopyOptions copyOptions) { }
-        public int BatchSize { get { throw null; } set { } }
-        public int BulkCopyTimeout { get { throw null; } set { } }
-        public System.Data.SqlClient.SqlBulkCopyColumnMappingCollection ColumnMappings { get { throw null; } }
-        public string DestinationTableName { get { throw null; } set { } }
-        public bool EnableStreaming { get { throw null; } set { } }
-        public int NotifyAfter { get { throw null; } set { } }
-        public event System.Data.SqlClient.SqlRowsCopiedEventHandler SqlRowsCopied { add { } remove { } }
-        public void Close() { }
-        void System.IDisposable.Dispose() { }
-        public void WriteToServer(System.Data.Common.DbDataReader reader) { }
-        public void WriteToServer(System.Data.DataRow[] rows) { }
-        public void WriteToServer(System.Data.DataTable table) { }
-        public void WriteToServer(System.Data.DataTable table, System.Data.DataRowState rowState) { }
-        public void WriteToServer(System.Data.IDataReader reader) { }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.Common.DbDataReader reader) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.Common.DbDataReader reader, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.DataRow[] rows) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.DataRow[] rows, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.DataTable table) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.DataTable table, System.Data.DataRowState rowState) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.DataTable table, System.Data.DataRowState rowState, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.DataTable table, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.IDataReader reader) { throw null; }
-        public System.Threading.Tasks.Task WriteToServerAsync(System.Data.IDataReader reader, System.Threading.CancellationToken cancellationToken) { throw null; }
-    }
-    public sealed partial class SqlBulkCopyColumnMapping
-    {
-        public SqlBulkCopyColumnMapping() { }
-        public SqlBulkCopyColumnMapping(int sourceColumnOrdinal, int destinationOrdinal) { }
-        public SqlBulkCopyColumnMapping(int sourceColumnOrdinal, string destinationColumn) { }
-        public SqlBulkCopyColumnMapping(string sourceColumn, int destinationOrdinal) { }
-        public SqlBulkCopyColumnMapping(string sourceColumn, string destinationColumn) { }
-        public string DestinationColumn { get { throw null; } set { } }
-        public int DestinationOrdinal { get { throw null; } set { } }
-        public string SourceColumn { get { throw null; } set { } }
-        public int SourceOrdinal { get { throw null; } set { } }
-    }
-    public sealed partial class SqlBulkCopyColumnMappingCollection : System.Collections.CollectionBase
-    {
-        internal SqlBulkCopyColumnMappingCollection() { }
-        public System.Data.SqlClient.SqlBulkCopyColumnMapping this[int index] { get { throw null; } }
-        public System.Data.SqlClient.SqlBulkCopyColumnMapping Add(System.Data.SqlClient.SqlBulkCopyColumnMapping bulkCopyColumnMapping) { throw null; }
-        public System.Data.SqlClient.SqlBulkCopyColumnMapping Add(int sourceColumnIndex, int destinationColumnIndex) { throw null; }
-        public System.Data.SqlClient.SqlBulkCopyColumnMapping Add(int sourceColumnIndex, string destinationColumn) { throw null; }
-        public System.Data.SqlClient.SqlBulkCopyColumnMapping Add(string sourceColumn, int destinationColumnIndex) { throw null; }
-        public System.Data.SqlClient.SqlBulkCopyColumnMapping Add(string sourceColumn, string destinationColumn) { throw null; }
-        public new void Clear() { }
-        public bool Contains(System.Data.SqlClient.SqlBulkCopyColumnMapping value) { throw null; }
-        public void CopyTo(System.Data.SqlClient.SqlBulkCopyColumnMapping[] array, int index) { }
-        public int IndexOf(System.Data.SqlClient.SqlBulkCopyColumnMapping value) { throw null; }
-        public void Insert(int index, System.Data.SqlClient.SqlBulkCopyColumnMapping value) { }
-        public void Remove(System.Data.SqlClient.SqlBulkCopyColumnMapping value) { }
-        public new void RemoveAt(int index) { }
-    }
-    [System.FlagsAttribute]
-    public enum SqlBulkCopyOptions
-    {
-        Default = 0,
-        KeepIdentity = 1,
-        CheckConstraints = 2,
-        TableLock = 4,
-        KeepNulls = 8,
-        FireTriggers = 16,
-        UseInternalTransaction = 32,
-    }
-    public sealed partial class SqlClientFactory : System.Data.Common.DbProviderFactory
-    {
-        internal SqlClientFactory() { }
-        public static readonly System.Data.SqlClient.SqlClientFactory Instance;
-        public override System.Data.Common.DbCommand CreateCommand() { throw null; }
-        public override System.Data.Common.DbCommandBuilder CreateCommandBuilder() { throw null; }
-        public override System.Data.Common.DbConnection CreateConnection() { throw null; }
-        public override System.Data.Common.DbConnectionStringBuilder CreateConnectionStringBuilder() { throw null; }
-        public override System.Data.Common.DbDataAdapter CreateDataAdapter() { throw null; }
-        public override System.Data.Common.DbParameter CreateParameter() { throw null; }
-    }
-    public static partial class SqlClientMetaDataCollectionNames
-    {
-        public static readonly string Columns;
-        public static readonly string Databases;
-        public static readonly string ForeignKeys;
-        public static readonly string IndexColumns;
-        public static readonly string Indexes;
-        public static readonly string Parameters;
-        public static readonly string ProcedureColumns;
-        public static readonly string Procedures;
-        public static readonly string Tables;
-        public static readonly string UserDefinedTypes;
-        public static readonly string Users;
-        public static readonly string ViewColumns;
-        public static readonly string Views;
-    }
-    public sealed partial class SqlCommand : System.Data.Common.DbCommand, System.ICloneable
-    {
-        public SqlCommand() { }
-        public SqlCommand(string cmdText) { }
-        public SqlCommand(string cmdText, System.Data.SqlClient.SqlConnection connection) { }
-        public SqlCommand(string cmdText, System.Data.SqlClient.SqlConnection connection, System.Data.SqlClient.SqlTransaction transaction) { }
-        public override string CommandText { get { throw null; } set { } }
-        public override int CommandTimeout { get { throw null; } set { } }
-        public override System.Data.CommandType CommandType { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlConnection Connection { get { throw null; } set { } }
-        protected override System.Data.Common.DbConnection DbConnection { get { throw null; } set { } }
-        protected override System.Data.Common.DbParameterCollection DbParameterCollection { get { throw null; } }
-        protected override System.Data.Common.DbTransaction DbTransaction { get { throw null; } set { } }
-        public override bool DesignTimeVisible { get { throw null; } set { } }
-        public System.Data.Sql.SqlNotificationRequest Notification { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlParameterCollection Parameters { get { throw null; } }
-        public new System.Data.SqlClient.SqlTransaction Transaction { get { throw null; } set { } }
-        public override System.Data.UpdateRowSource UpdatedRowSource { get { throw null; } set { } }
-        public event System.Data.StatementCompletedEventHandler StatementCompleted { add { } remove { } }
-        public System.IAsyncResult BeginExecuteNonQuery() { throw null; }
-        public System.IAsyncResult BeginExecuteNonQuery(System.AsyncCallback callback, object stateObject) { throw null; }
-        public System.IAsyncResult BeginExecuteReader() { throw null; }
-        public System.IAsyncResult BeginExecuteReader(System.AsyncCallback callback, object stateObject) { throw null; }
-        public System.IAsyncResult BeginExecuteReader(System.AsyncCallback callback, object stateObject, System.Data.CommandBehavior behavior) { throw null; }
-        public System.IAsyncResult BeginExecuteReader(System.Data.CommandBehavior behavior) { throw null; }
-        public System.IAsyncResult BeginExecuteXmlReader() { throw null; }
-        public System.IAsyncResult BeginExecuteXmlReader(System.AsyncCallback callback, object stateObject) { throw null; }
-        public override void Cancel() { }
-        public System.Data.SqlClient.SqlCommand Clone() { throw null; }
-        protected override System.Data.Common.DbParameter CreateDbParameter() { throw null; }
-        public new System.Data.SqlClient.SqlParameter CreateParameter() { throw null; }
-        public int EndExecuteNonQuery(System.IAsyncResult asyncResult) { throw null; }
-        public System.Data.SqlClient.SqlDataReader EndExecuteReader(System.IAsyncResult asyncResult) { throw null; }
-        public System.Xml.XmlReader EndExecuteXmlReader(System.IAsyncResult asyncResult) { throw null; }
-        protected override System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior) { throw null; }
-        protected override System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteDbDataReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public override int ExecuteNonQuery() { throw null; }
-        public override System.Threading.Tasks.Task<int> ExecuteNonQueryAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
-        public new System.Data.SqlClient.SqlDataReader ExecuteReader() { throw null; }
-        public new System.Data.SqlClient.SqlDataReader ExecuteReader(System.Data.CommandBehavior behavior) { throw null; }
-        public new System.Threading.Tasks.Task<System.Data.SqlClient.SqlDataReader> ExecuteReaderAsync() { throw null; }
-        public new System.Threading.Tasks.Task<System.Data.SqlClient.SqlDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior) { throw null; }
-        public new System.Threading.Tasks.Task<System.Data.SqlClient.SqlDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public new System.Threading.Tasks.Task<System.Data.SqlClient.SqlDataReader> ExecuteReaderAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
-        public override object ExecuteScalar() { throw null; }
-        public override System.Threading.Tasks.Task<object> ExecuteScalarAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
-        public System.Xml.XmlReader ExecuteXmlReader() { throw null; }
-        public System.Threading.Tasks.Task<System.Xml.XmlReader> ExecuteXmlReaderAsync() { throw null; }
-        public System.Threading.Tasks.Task<System.Xml.XmlReader> ExecuteXmlReaderAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
-        public override void Prepare() { }
-        public void ResetCommandTimeout() { }
-        object System.ICloneable.Clone() { throw null; }
-    }
-    public sealed partial class SqlCommandBuilder : System.Data.Common.DbCommandBuilder
-    {
-        public SqlCommandBuilder() { }
-        public SqlCommandBuilder(System.Data.SqlClient.SqlDataAdapter adapter) { }
-        public override System.Data.Common.CatalogLocation CatalogLocation { get { throw null; } set { } }
-        public override string CatalogSeparator { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlDataAdapter DataAdapter { get { throw null; } set { } }
-        public override string QuotePrefix { get { throw null; } set { } }
-        public override string QuoteSuffix { get { throw null; } set { } }
-        public override string SchemaSeparator { get { throw null; } set { } }
-        protected override void ApplyParameterInfo(System.Data.Common.DbParameter parameter, System.Data.DataRow datarow, System.Data.StatementType statementType, bool whereClause) { }
-        public static void DeriveParameters(System.Data.SqlClient.SqlCommand command) { }
-        public new System.Data.SqlClient.SqlCommand GetDeleteCommand() { throw null; }
-        public new System.Data.SqlClient.SqlCommand GetDeleteCommand(bool useColumnsForParameterNames) { throw null; }
-        public new System.Data.SqlClient.SqlCommand GetInsertCommand() { throw null; }
-        public new System.Data.SqlClient.SqlCommand GetInsertCommand(bool useColumnsForParameterNames) { throw null; }
-        protected override string GetParameterName(int parameterOrdinal) { throw null; }
-        protected override string GetParameterName(string parameterName) { throw null; }
-        protected override string GetParameterPlaceholder(int parameterOrdinal) { throw null; }
-        protected override System.Data.DataTable GetSchemaTable(System.Data.Common.DbCommand srcCommand) { throw null; }
-        public new System.Data.SqlClient.SqlCommand GetUpdateCommand() { throw null; }
-        public new System.Data.SqlClient.SqlCommand GetUpdateCommand(bool useColumnsForParameterNames) { throw null; }
-        protected override System.Data.Common.DbCommand InitializeCommand(System.Data.Common.DbCommand command) { throw null; }
-        public override string QuoteIdentifier(string unquotedIdentifier) { throw null; }
-        protected override void SetRowUpdatingHandler(System.Data.Common.DbDataAdapter adapter) { }
-        public override string UnquoteIdentifier(string quotedIdentifier) { throw null; }
-    }
-    public sealed partial class SqlConnection : System.Data.Common.DbConnection, System.ICloneable
-    {
-        public SqlConnection() { }
-        public SqlConnection(string connectionString) { }
-        public SqlConnection(string connectionString, System.Data.SqlClient.SqlCredential credential) { }
-        public string AccessToken { get { throw null; } set { } }
-        public System.Guid ClientConnectionId { get { throw null; } }
-        public override string ConnectionString { get { throw null; } set { } }
-        public override int ConnectionTimeout { get { throw null; } }
-        public System.Data.SqlClient.SqlCredential Credential { get { throw null; } set { } }
-        public override string Database { get { throw null; } }
-        public override string DataSource { get { throw null; } }
-        public bool FireInfoMessageEventOnUserErrors { get { throw null; } set { } }
-        public int PacketSize { get { throw null; } }
-        public override string ServerVersion { get { throw null; } }
-        public override System.Data.ConnectionState State { get { throw null; } }
-        public bool StatisticsEnabled { get { throw null; } set { } }
-        public string WorkstationId { get { throw null; } }
-        public event System.Data.SqlClient.SqlInfoMessageEventHandler InfoMessage { add { } remove { } }
-        protected override System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { throw null; }
-        public new System.Data.SqlClient.SqlTransaction BeginTransaction() { throw null; }
-        public new System.Data.SqlClient.SqlTransaction BeginTransaction(System.Data.IsolationLevel iso) { throw null; }
-        public System.Data.SqlClient.SqlTransaction BeginTransaction(System.Data.IsolationLevel iso, string transactionName) { throw null; }
-        public System.Data.SqlClient.SqlTransaction BeginTransaction(string transactionName) { throw null; }
-        public override void ChangeDatabase(string database) { }
-        public static void ChangePassword(string connectionString, System.Data.SqlClient.SqlCredential credential, System.Security.SecureString newPassword) { }
-        public static void ChangePassword(string connectionString, string newPassword) { }
-        public static void ClearAllPools() { }
-        public static void ClearPool(System.Data.SqlClient.SqlConnection connection) { }
-        public override void Close() { }
-        public new System.Data.SqlClient.SqlCommand CreateCommand() { throw null; }
-        protected override System.Data.Common.DbCommand CreateDbCommand() { throw null; }
-        public override System.Data.DataTable GetSchema() { throw null; }
-        public override System.Data.DataTable GetSchema(string collectionName) { throw null; }
-        public override System.Data.DataTable GetSchema(string collectionName, string[] restrictionValues) { throw null; }
-        public override void Open() { }
-        public override System.Threading.Tasks.Task OpenAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
-        public void ResetStatistics() { }
-        public System.Collections.IDictionary RetrieveStatistics() { throw null; }
-        object System.ICloneable.Clone() { throw null; }
-    }
-    public sealed partial class SqlConnectionStringBuilder : System.Data.Common.DbConnectionStringBuilder
-    {
-        public SqlConnectionStringBuilder() { }
-        public SqlConnectionStringBuilder(string connectionString) { }
-        public System.Data.SqlClient.ApplicationIntent ApplicationIntent { get { throw null; } set { } }
-        public string ApplicationName { get { throw null; } set { } }
-        public string AttachDBFilename { get { throw null; } set { } }
-        public int ConnectRetryCount { get { throw null; } set { } }
-        public int ConnectRetryInterval { get { throw null; } set { } }
-        public int ConnectTimeout { get { throw null; } set { } }
-        public string CurrentLanguage { get { throw null; } set { } }
-        public string DataSource { get { throw null; } set { } }
-        public bool Encrypt { get { throw null; } set { } }
-        public bool Enlist { get { throw null; } set { } }
-        public string FailoverPartner { get { throw null; } set { } }
-        public bool IntegratedSecurity { get { throw null; } set { } }
-        public override object this[string keyword] { get { throw null; } set { } }
-        public override System.Collections.ICollection Keys { get { throw null; } }
-        public int LoadBalanceTimeout { get { throw null; } set { } }
-        public int MaxPoolSize { get { throw null; } set { } }
-        public int MinPoolSize { get { throw null; } set { } }
-        public bool MultipleActiveResultSets { get { throw null; } set { } }
-        public bool MultiSubnetFailover { get { throw null; } set { } }
-        public int PacketSize { get { throw null; } set { } }
-        public string Password { get { throw null; } set { } }
-        public bool PersistSecurityInfo { get { throw null; } set { } }
-        public bool Pooling { get { throw null; } set { } }
-        public bool Replication { get { throw null; } set { } }
-        public string TransactionBinding { get { throw null; } set { } }
-        public bool TrustServerCertificate { get { throw null; } set { } }
-        public string TypeSystemVersion { get { throw null; } set { } }
-        public string UserID { get { throw null; } set { } }
-        public bool UserInstance { get { throw null; } set { } }
-        public override System.Collections.ICollection Values { get { throw null; } }
-        public string WorkstationID { get { throw null; } set { } }
-        public override void Clear() { }
-        public override bool ContainsKey(string keyword) { throw null; }
-        public override bool Remove(string keyword) { throw null; }
-        public override bool ShouldSerialize(string keyword) { throw null; }
-        public override bool TryGetValue(string keyword, out object value) { throw null; }
-    }
-    public sealed partial class SqlCredential
-    {
-        public SqlCredential(string userId, System.Security.SecureString password) { }
-        public System.Security.SecureString Password { get { throw null; } }
-        public string UserId { get { throw null; } }
-    }
-    public sealed partial class SqlDataAdapter : System.Data.Common.DbDataAdapter, System.Data.IDataAdapter, System.Data.IDbDataAdapter, System.ICloneable
-    {
-        public SqlDataAdapter() { }
-        public SqlDataAdapter(System.Data.SqlClient.SqlCommand selectCommand) { }
-        public SqlDataAdapter(string selectCommandText, System.Data.SqlClient.SqlConnection selectConnection) { }
-        public SqlDataAdapter(string selectCommandText, string selectConnectionString) { }
-        public new System.Data.SqlClient.SqlCommand DeleteCommand { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlCommand InsertCommand { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlCommand SelectCommand { get { throw null; } set { } }
-        System.Data.IDbCommand System.Data.IDbDataAdapter.DeleteCommand { get { throw null; } set { } }
-        System.Data.IDbCommand System.Data.IDbDataAdapter.InsertCommand { get { throw null; } set { } }
-        System.Data.IDbCommand System.Data.IDbDataAdapter.SelectCommand { get { throw null; } set { } }
-        System.Data.IDbCommand System.Data.IDbDataAdapter.UpdateCommand { get { throw null; } set { } }
-        public override int UpdateBatchSize { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlCommand UpdateCommand { get { throw null; } set { } }
-        public event System.Data.SqlClient.SqlRowUpdatedEventHandler RowUpdated { add { } remove { } }
-        public event System.Data.SqlClient.SqlRowUpdatingEventHandler RowUpdating { add { } remove { } }
-        protected override void OnRowUpdated(System.Data.Common.RowUpdatedEventArgs value) { }
-        protected override void OnRowUpdating(System.Data.Common.RowUpdatingEventArgs value) { }
-        object System.ICloneable.Clone() { throw null; }
-    }
-    public partial class SqlDataReader : System.Data.Common.DbDataReader, System.IDisposable
-    {
-        internal SqlDataReader() { }
-        protected System.Data.SqlClient.SqlConnection Connection { get { throw null; } }
-        public override int Depth { get { throw null; } }
-        public override int FieldCount { get { throw null; } }
-        public override bool HasRows { get { throw null; } }
-        public override bool IsClosed { get { throw null; } }
-        public override object this[int i] { get { throw null; } }
-        public override object this[string name] { get { throw null; } }
-        public override int RecordsAffected { get { throw null; } }
-        public override int VisibleFieldCount { get { throw null; } }
-        public override bool GetBoolean(int i) { throw null; }
-        public override byte GetByte(int i) { throw null; }
-        public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { throw null; }
-        public override char GetChar(int i) { throw null; }
-        public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) { throw null; }
-        public override string GetDataTypeName(int i) { throw null; }
-        public override System.DateTime GetDateTime(int i) { throw null; }
-        public virtual System.DateTimeOffset GetDateTimeOffset(int i) { throw null; }
-        public override decimal GetDecimal(int i) { throw null; }
-        public override double GetDouble(int i) { throw null; }
-        public override System.Collections.IEnumerator GetEnumerator() { throw null; }
-        public override System.Type GetFieldType(int i) { throw null; }
-        public override System.Threading.Tasks.Task<T> GetFieldValueAsync<T>(int i, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public override T GetFieldValue<T>(int i) { throw null; }
-        public override float GetFloat(int i) { throw null; }
-        public override System.Guid GetGuid(int i) { throw null; }
-        public override short GetInt16(int i) { throw null; }
-        public override int GetInt32(int i) { throw null; }
-        public override long GetInt64(int i) { throw null; }
-        public override string GetName(int i) { throw null; }
-        public override int GetOrdinal(string name) { throw null; }
-        public override System.Type GetProviderSpecificFieldType(int i) { throw null; }
-        public override object GetProviderSpecificValue(int i) { throw null; }
-        public override int GetProviderSpecificValues(object[] values) { throw null; }
-        public override System.Data.DataTable GetSchemaTable() { throw null; }
-        public virtual System.Data.SqlTypes.SqlBinary GetSqlBinary(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlBoolean GetSqlBoolean(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlByte GetSqlByte(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlBytes GetSqlBytes(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlChars GetSqlChars(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlDateTime GetSqlDateTime(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlDecimal GetSqlDecimal(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlDouble GetSqlDouble(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlGuid GetSqlGuid(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlInt16 GetSqlInt16(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlInt32 GetSqlInt32(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlInt64 GetSqlInt64(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlMoney GetSqlMoney(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlSingle GetSqlSingle(int i) { throw null; }
-        public virtual System.Data.SqlTypes.SqlString GetSqlString(int i) { throw null; }
-        public virtual object GetSqlValue(int i) { throw null; }
-        public virtual int GetSqlValues(object[] values) { throw null; }
-        public virtual System.Data.SqlTypes.SqlXml GetSqlXml(int i) { throw null; }
-        public override System.IO.Stream GetStream(int i) { throw null; }
-        public override string GetString(int i) { throw null; }
-        public override System.IO.TextReader GetTextReader(int i) { throw null; }
-        public virtual System.TimeSpan GetTimeSpan(int i) { throw null; }
-        public override object GetValue(int i) { throw null; }
-        public override int GetValues(object[] values) { throw null; }
-        public virtual System.Xml.XmlReader GetXmlReader(int i) { throw null; }
-        protected internal bool IsCommandBehavior(System.Data.CommandBehavior condition) { throw null; }
-        public override bool IsDBNull(int i) { throw null; }
-        public override System.Threading.Tasks.Task<bool> IsDBNullAsync(int i, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public override bool NextResult() { throw null; }
-        public override System.Threading.Tasks.Task<bool> NextResultAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
-        public override bool Read() { throw null; }
-        public override System.Threading.Tasks.Task<bool> ReadAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
-    }
-    public sealed partial class SqlDependency
-    {
-        public SqlDependency() { }
-        public SqlDependency(System.Data.SqlClient.SqlCommand command) { }
-        public SqlDependency(System.Data.SqlClient.SqlCommand command, string options, int timeout) { }
-        public bool HasChanges { get { throw null; } }
-        public string Id { get { throw null; } }
-        public event System.Data.SqlClient.OnChangeEventHandler OnChange { add { } remove { } }
-        public void AddCommandDependency(System.Data.SqlClient.SqlCommand command) { }
-        public static bool Start(string connectionString) { throw null; }
-        public static bool Start(string connectionString, string queue) { throw null; }
-        public static bool Stop(string connectionString) { throw null; }
-        public static bool Stop(string connectionString, string queue) { throw null; }
-    }
-    public sealed partial class SqlError
-    {
-        internal SqlError() { }
-        public byte Class { get { throw null; } }
-        public int LineNumber { get { throw null; } }
-        public string Message { get { throw null; } }
-        public int Number { get { throw null; } }
-        public string Procedure { get { throw null; } }
-        public string Server { get { throw null; } }
-        public string Source { get { throw null; } }
-        public byte State { get { throw null; } }
-        public override string ToString() { throw null; }
-    }
-    public sealed partial class SqlErrorCollection : System.Collections.ICollection, System.Collections.IEnumerable
-    {
-        internal SqlErrorCollection() { }
-        public int Count { get { throw null; } }
-        public System.Data.SqlClient.SqlError this[int index] { get { throw null; } }
-        bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
-        object System.Collections.ICollection.SyncRoot { get { throw null; } }
-        public void CopyTo(System.Array array, int index) { }
-        public void CopyTo(System.Data.SqlClient.SqlError[] array, int index) { }
-        public System.Collections.IEnumerator GetEnumerator() { throw null; }
-    }
-    public sealed partial class SqlException : System.Data.Common.DbException
-    {
-        internal SqlException() { }
-        public byte Class { get { throw null; } }
-        public System.Guid ClientConnectionId { get { throw null; } }
-        public System.Data.SqlClient.SqlErrorCollection Errors { get { throw null; } }
-        public int LineNumber { get { throw null; } }
-        public int Number { get { throw null; } }
-        public string Procedure { get { throw null; } }
-        public string Server { get { throw null; } }
-        public override string Source { get { throw null; } }
-        public byte State { get { throw null; } }
-        public override void GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context) { }
-        public override string ToString() { throw null; }
-    }
-    public sealed partial class SqlInfoMessageEventArgs : System.EventArgs
-    {
-        internal SqlInfoMessageEventArgs() { }
-        public System.Data.SqlClient.SqlErrorCollection Errors { get { throw null; } }
-        public string Message { get { throw null; } }
-        public string Source { get { throw null; } }
-        public override string ToString() { throw null; }
-    }
-    public delegate void SqlInfoMessageEventHandler(object sender, System.Data.SqlClient.SqlInfoMessageEventArgs e);
-    public partial class SqlNotificationEventArgs : System.EventArgs
-    {
-        public SqlNotificationEventArgs(System.Data.SqlClient.SqlNotificationType type, System.Data.SqlClient.SqlNotificationInfo info, System.Data.SqlClient.SqlNotificationSource source) { }
-        public System.Data.SqlClient.SqlNotificationInfo Info { get { throw null; } }
-        public System.Data.SqlClient.SqlNotificationSource Source { get { throw null; } }
-        public System.Data.SqlClient.SqlNotificationType Type { get { throw null; } }
-    }
-    public enum SqlNotificationInfo
-    {
-        AlreadyChanged = -2,
-        Unknown = -1,
-        Truncate = 0,
-        Insert = 1,
-        Update = 2,
-        Delete = 3,
-        Drop = 4,
-        Alter = 5,
-        Restart = 6,
-        Error = 7,
-        Query = 8,
-        Invalid = 9,
-        Options = 10,
-        Isolation = 11,
-        Expired = 12,
-        Resource = 13,
-        PreviousFire = 14,
-        TemplateLimit = 15,
-        Merge = 16,
-    }
-    public enum SqlNotificationSource
-    {
-        Client = -2,
-        Unknown = -1,
-        Data = 0,
-        Timeout = 1,
-        Object = 2,
-        Database = 3,
-        System = 4,
-        Statement = 5,
-        Environment = 6,
-        Execution = 7,
-        Owner = 8,
-    }
-    public enum SqlNotificationType
-    {
-        Unknown = -1,
-        Change = 0,
-        Subscribe = 1,
-    }
-    public sealed partial class SqlParameter : System.Data.Common.DbParameter, System.ICloneable
-    {
-        public SqlParameter() { }
-        public SqlParameter(string parameterName, System.Data.SqlDbType dbType) { }
-        public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size) { }
-        public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size, System.Data.ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, object value) { }
-        public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size, System.Data.ParameterDirection direction, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value, string xmlSchemaCollectionDatabase, string xmlSchemaCollectionOwningSchema, string xmlSchemaCollectionName) { }
-        public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size, string sourceColumn) { }
-        public SqlParameter(string parameterName, object value) { }
-        public System.Data.SqlTypes.SqlCompareOptions CompareInfo { get { throw null; } set { } }
-        public override System.Data.DbType DbType { get { throw null; } set { } }
-        public override System.Data.ParameterDirection Direction { get { throw null; } set { } }
-        public override bool IsNullable { get { throw null; } set { } }
-        public int LocaleId { get { throw null; } set { } }
-        public int Offset { get { throw null; } set { } }
-        public override string ParameterName { get { throw null; } set { } }
-        [System.ComponentModel.DefaultValueAttribute((byte)0)]
-        public new byte Precision { get { throw null; } set { } }
-        [System.ComponentModel.DefaultValueAttribute((byte)0)]
-        public new byte Scale { get { throw null; } set { } }
-        public override int Size { get { throw null; } set { } }
-        public override string SourceColumn { get { throw null; } set { } }
-        public override bool SourceColumnNullMapping { get { throw null; } set { } }
-        public override System.Data.DataRowVersion SourceVersion { get { throw null; } set { } }
-        [System.Data.Common.DbProviderSpecificTypePropertyAttribute(true)]
-        public System.Data.SqlDbType SqlDbType { get { throw null; } set { } }
-        public object SqlValue { get { throw null; } set { } }
-        public string TypeName { get { throw null; } set { } }
-        public string UdtTypeName { get { throw null; } set { } }
-        [System.ComponentModel.TypeConverterAttribute(typeof(System.ComponentModel.StringConverter))]
-        public override object Value { get { throw null; } set { } }
-        public string XmlSchemaCollectionDatabase { get { throw null; } set { } }
-        public string XmlSchemaCollectionName { get { throw null; } set { } }
-        public string XmlSchemaCollectionOwningSchema { get { throw null; } set { } }
-        public override void ResetDbType() { }
-        public void ResetSqlDbType() { }
-        object System.ICloneable.Clone() { throw null; }
-        public override string ToString() { throw null; }
-    }
-    public sealed partial class SqlParameterCollection : System.Data.Common.DbParameterCollection
-    {
-        internal SqlParameterCollection() { }
-        public override int Count { get { throw null; } }
-        public override bool IsFixedSize { get { throw null; } }
-        public override bool IsReadOnly { get { throw null; } }
-        public new System.Data.SqlClient.SqlParameter this[int index] { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlParameter this[string parameterName] { get { throw null; } set { } }
-        public override object SyncRoot { get { throw null; } }
-        public System.Data.SqlClient.SqlParameter Add(System.Data.SqlClient.SqlParameter value) { throw null; }
-        public override int Add(object value) { throw null; }
-        public System.Data.SqlClient.SqlParameter Add(string parameterName, System.Data.SqlDbType sqlDbType) { throw null; }
-        public System.Data.SqlClient.SqlParameter Add(string parameterName, System.Data.SqlDbType sqlDbType, int size) { throw null; }
-        public System.Data.SqlClient.SqlParameter Add(string parameterName, System.Data.SqlDbType sqlDbType, int size, string sourceColumn) { throw null; }
-        public override void AddRange(System.Array values) { }
-        public void AddRange(System.Data.SqlClient.SqlParameter[] values) { }
-        public System.Data.SqlClient.SqlParameter AddWithValue(string parameterName, object value) { throw null; }
-        public override void Clear() { }
-        public bool Contains(System.Data.SqlClient.SqlParameter value) { throw null; }
-        public override bool Contains(object value) { throw null; }
-        public override bool Contains(string value) { throw null; }
-        public override void CopyTo(System.Array array, int index) { }
-        public void CopyTo(System.Data.SqlClient.SqlParameter[] array, int index) { }
-        public override System.Collections.IEnumerator GetEnumerator() { throw null; }
-        protected override System.Data.Common.DbParameter GetParameter(int index) { throw null; }
-        protected override System.Data.Common.DbParameter GetParameter(string parameterName) { throw null; }
-        public int IndexOf(System.Data.SqlClient.SqlParameter value) { throw null; }
-        public override int IndexOf(object value) { throw null; }
-        public override int IndexOf(string parameterName) { throw null; }
-        public void Insert(int index, System.Data.SqlClient.SqlParameter value) { }
-        public override void Insert(int index, object value) { }
-        public void Remove(System.Data.SqlClient.SqlParameter value) { }
-        public override void Remove(object value) { }
-        public override void RemoveAt(int index) { }
-        public override void RemoveAt(string parameterName) { }
-        protected override void SetParameter(int index, System.Data.Common.DbParameter value) { }
-        protected override void SetParameter(string parameterName, System.Data.Common.DbParameter value) { }
-    }
-    public partial class SqlRowsCopiedEventArgs : System.EventArgs
-    {
-        public SqlRowsCopiedEventArgs(long rowsCopied) { }
-        public bool Abort { get { throw null; } set { } }
-        public long RowsCopied { get { throw null; } }
-    }
-    public delegate void SqlRowsCopiedEventHandler(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e);
-    public sealed partial class SqlRowUpdatedEventArgs : System.Data.Common.RowUpdatedEventArgs
-    {
-        public SqlRowUpdatedEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { }
-        public new System.Data.SqlClient.SqlCommand Command { get { throw null; } }
-    }
-    public delegate void SqlRowUpdatedEventHandler(object sender, System.Data.SqlClient.SqlRowUpdatedEventArgs e);
-    public sealed partial class SqlRowUpdatingEventArgs : System.Data.Common.RowUpdatingEventArgs
-    {
-        public SqlRowUpdatingEventArgs(System.Data.DataRow row, System.Data.IDbCommand command, System.Data.StatementType statementType, System.Data.Common.DataTableMapping tableMapping) : base (default(System.Data.DataRow), default(System.Data.IDbCommand), default(System.Data.StatementType), default(System.Data.Common.DataTableMapping)) { }
-        protected override System.Data.IDbCommand BaseCommand { get { throw null; } set { } }
-        public new System.Data.SqlClient.SqlCommand Command { get { throw null; } set { } }
-    }
-    public delegate void SqlRowUpdatingEventHandler(object sender, System.Data.SqlClient.SqlRowUpdatingEventArgs e);
-    public sealed partial class SqlTransaction : System.Data.Common.DbTransaction
-    {
-        internal SqlTransaction() { }
-        public new System.Data.SqlClient.SqlConnection Connection { get { throw null; } }
-        protected override System.Data.Common.DbConnection DbConnection { get { throw null; } }
-        public override System.Data.IsolationLevel IsolationLevel { get { throw null; } }
-        public override void Commit() { }
-        protected override void Dispose(bool disposing) { }
-        public override void Rollback() { }
-        public void Rollback(string transactionName) { }
-        public void Save(string savePointName) { }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.csproj b/src/libraries/System.Data.SqlClient/ref/System.Data.SqlClient.csproj
deleted file mode 100644 (file)
index a526f20..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <Configurations>$(NetCoreAppCurrent)-Debug;$(NetCoreAppCurrent)-Release;netcoreapp2.1-Debug;netcoreapp2.1-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="System.Data.SqlClient.cs" />
-    <Compile Include="System.Data.SqlClient.Forwards.cs" />
-    <Compile Include="System.Data.SqlClient.Manual.cs" />
-    <Compile Include="System.Data.SqlClient.NetCoreApp.cs" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp2.1'">
-    <Reference Include="System.Runtime" />
-    <Reference Include="System.Runtime.Extensions" />
-    <Reference Include="System.Data.Common" />
-    <Reference Include="System.Collections.NonGeneric" />
-    <Reference Include="System.ComponentModel.Primitives" />
-    <Reference Include="System.ComponentModel.TypeConverter" />
-    <Reference Include="System.Xml.ReaderWriter" />
-    <Reference Include="System.Runtime.InteropServices" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(TargetFramework)' == '$(NetCoreAppCurrent)'">
-    <ProjectReference Include="..\..\System.Runtime\ref\System.Runtime.csproj" />
-    <ProjectReference Include="..\..\System.Runtime.Extensions\ref\System.Runtime.Extensions.csproj" />
-    <ProjectReference Include="..\..\System.Data.Common\ref\System.Data.Common.csproj" />
-    <ProjectReference Include="..\..\System.Collections.NonGeneric\ref\System.Collections.NonGeneric.csproj" />
-    <ProjectReference Include="..\..\System.ComponentModel.Primitives\ref\System.ComponentModel.Primitives.csproj" />
-    <ProjectReference Include="..\..\System.ComponentModel.TypeConverter\ref\System.ComponentModel.TypeConverter.csproj" />
-    <ProjectReference Include="..\..\System.ObjectModel\ref\System.ObjectModel.csproj" />
-    <ProjectReference Include="..\..\System.Xml.ReaderWriter\ref\System.Xml.ReaderWriter.csproj" />
-    <ProjectReference Include="..\..\System.Runtime.InteropServices\ref\System.Runtime.InteropServices.csproj" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/Configurations.props b/src/libraries/System.Data.SqlClient/src/Configurations.props
deleted file mode 100644 (file)
index 3e86819..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-<Project>
-  <PropertyGroup>
-    <PackageConfigurations>
-      netstandard2.0-Unix;
-      netstandard2.0-Windows_NT;
-      netcoreapp2.1;
-      netcoreapp2.1-Unix;
-      netcoreapp2.1-Windows_NT;
-    </PackageConfigurations>
-    <BuildConfigurations>
-      $(PackageConfigurations)
-      $(NetCoreAppCurrent);
-      $(NetCoreAppCurrent)-Unix;
-      $(NetCoreAppCurrent)-Windows_NT;
-      _$(NetFrameworkCurrent)-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/GenerateThisAssemblyCs.targets b/src/libraries/System.Data.SqlClient/src/GenerateThisAssemblyCs.targets
deleted file mode 100644 (file)
index a01191f..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-<Project>
-  <ItemGroup>
-    <Compile Include="$(IntermediateOutputPath)\ThisAssembly.cs"/>
-  </ItemGroup>
-
-  <Target Name="GenerateThisAssemblyCs"
-          DependsOnTargets="GetAssemblyVersion"
-          BeforeTargets="CoreCompile">
-    <PropertyGroup>
-      <ThisAssemblyCsContents>
-namespace System
-{
-internal static class ThisAssembly
-{
-internal const string InformationalVersion = "$(FileVersion)"%3B
-}
-}
-      </ThisAssemblyCsContents>
-    </PropertyGroup>
-
-    <!-- Get the last version number we built with (if any) -->
-    <ReadLinesFromFile
-      Condition="Exists('$(IntermediateOutputPath)\LastVersionNumber')"
-      File="$(IntermediateOutputPath)\LastVersionNumber">
-      <Output TaskParameter="Lines" PropertyName="LastVersionNumber"/>
-    </ReadLinesFromFile>
-
-    <!-- Write ThisAssembly.cs if this is a new version number, or it is missing -->
-    <WriteLinesToFile
-      Condition="('$(LastVersionNumber)'!='$(FileVersion)') or !Exists('$(IntermediateOutputPath)\ThisAssembly.cs')"
-      File="$(IntermediateOutputPath)\ThisAssembly.cs"
-      Lines="$(ThisAssemblyCsContents)"
-      Overwrite="true"
-      Encoding="Unicode"/>
-
-    <!-- Write the new version number (if it has changed) -->
-    <WriteLinesToFile
-      Condition="'$(LastVersionNumber)'!='$(FileVersion)'"
-      File="$(IntermediateOutputPath)\LastVersionNumber"
-      Lines="$(FileVersion)"
-      Overwrite="true"
-      Encoding="Unicode"/>
-  </Target>
-</Project>
diff --git a/src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Common.cs b/src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Common.cs
deleted file mode 100644 (file)
index 5093d47..0000000
+++ /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.Data.SqlClient.SNI;
-
-namespace System.Data.SqlClient
-{
-    internal static partial class SNINativeMethodWrapper
-    {
-        internal enum SniSpecialErrors : uint
-        {
-            LocalDBErrorCode = SNICommon.LocalDBErrorCode,
-
-            // multi-subnet-failover specific error codes
-            MultiSubnetFailoverWithMoreThan64IPs = SNICommon.MultiSubnetFailoverWithMoreThan64IPs,
-            MultiSubnetFailoverWithInstanceSpecified = SNICommon.MultiSubnetFailoverWithInstanceSpecified,
-            MultiSubnetFailoverWithNonTcpProtocol = SNICommon.MultiSubnetFailoverWithNonTcpProtocol,
-
-            // max error code value
-            MaxErrorValue = SNICommon.MaxErrorValue
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs b/src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs
deleted file mode 100644 (file)
index 329bb4f..0000000
+++ /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.Data.SqlClient.SNI;
-
-namespace System.Data
-{
-    internal static partial class SafeNativeMethods
-    {
-        internal static IntPtr GetProcAddress(IntPtr HModule, string funcName)
-        {
-            throw new PlatformNotSupportedException("SafeNativeMethods.GetProcAddress is not supported on non-Windows platforms");
-        }
-    }
-}
-
-namespace System.Data
-{
-    internal static class Win32NativeMethods
-    {
-        internal static bool IsTokenRestrictedWrapper(IntPtr token)
-        {
-            throw new PlatformNotSupportedException("Win32NativeMethods.IsTokenRestrictedWrapper is not supported on non-Windows platforms");
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs b/src/libraries/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs
deleted file mode 100644 (file)
index 65fea05..0000000
+++ /dev/null
@@ -1,429 +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.Data.Common;
-using System.Data.SqlClient;
-using System.Runtime.InteropServices;
-
-namespace System.Data.SqlClient
-{
-    internal static partial class SNINativeMethodWrapper
-    {
-        private const string SNI = "sni.dll";
-
-        private static int s_sniMaxComposedSpnLength = -1;
-
-        private const int SniOpenTimeOut = -1; // infinite
-
-        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
-        internal delegate void SqlAsyncCallbackDelegate(IntPtr m_ConsKey, IntPtr pPacket, uint dwError);
-
-        internal static int SniMaxComposedSpnLength
-        {
-            get
-            {
-                if (s_sniMaxComposedSpnLength == -1)
-                {
-                    s_sniMaxComposedSpnLength = checked((int)GetSniMaxComposedSpnLength());
-                }
-                return s_sniMaxComposedSpnLength;
-            }
-        }
-
-        #region Structs\Enums
-        [StructLayout(LayoutKind.Sequential)]
-        internal struct ConsumerInfo
-        {
-            internal int defaultBufferSize;
-            internal SqlAsyncCallbackDelegate readDelegate;
-            internal SqlAsyncCallbackDelegate writeDelegate;
-            internal IntPtr key;
-        }
-
-        internal enum ConsumerNumber
-        {
-            SNI_Consumer_SNI,
-            SNI_Consumer_SSB,
-            SNI_Consumer_PacketIsReleased,
-            SNI_Consumer_Invalid,
-        }
-
-        internal enum IOType
-        {
-            READ,
-            WRITE,
-        }
-
-        internal enum PrefixEnum
-        {
-            UNKNOWN_PREFIX,
-            SM_PREFIX,
-            TCP_PREFIX,
-            NP_PREFIX,
-            VIA_PREFIX,
-            INVALID_PREFIX,
-        }
-
-        internal enum ProviderEnum
-        {
-            HTTP_PROV,
-            NP_PROV,
-            SESSION_PROV,
-            SIGN_PROV,
-            SM_PROV,
-            SMUX_PROV,
-            SSL_PROV,
-            TCP_PROV,
-            VIA_PROV,
-            MAX_PROVS,
-            INVALID_PROV,
-        }
-
-        internal enum QTypes
-        {
-            SNI_QUERY_CONN_INFO,
-            SNI_QUERY_CONN_BUFSIZE,
-            SNI_QUERY_CONN_KEY,
-            SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE,
-            SNI_QUERY_SERVER_ENCRYPT_POSSIBLE,
-            SNI_QUERY_CERTIFICATE,
-            SNI_QUERY_LOCALDB_HMODULE,
-            SNI_QUERY_CONN_ENCRYPT,
-            SNI_QUERY_CONN_PROVIDERNUM,
-            SNI_QUERY_CONN_CONNID,
-            SNI_QUERY_CONN_PARENTCONNID,
-            SNI_QUERY_CONN_SECPKG,
-            SNI_QUERY_CONN_NETPACKETSIZE,
-            SNI_QUERY_CONN_NODENUM,
-            SNI_QUERY_CONN_PACKETSRECD,
-            SNI_QUERY_CONN_PACKETSSENT,
-            SNI_QUERY_CONN_PEERADDR,
-            SNI_QUERY_CONN_PEERPORT,
-            SNI_QUERY_CONN_LASTREADTIME,
-            SNI_QUERY_CONN_LASTWRITETIME,
-            SNI_QUERY_CONN_CONSUMER_ID,
-            SNI_QUERY_CONN_CONNECTTIME,
-            SNI_QUERY_CONN_HTTPENDPOINT,
-            SNI_QUERY_CONN_LOCALADDR,
-            SNI_QUERY_CONN_LOCALPORT,
-            SNI_QUERY_CONN_SSLHANDSHAKESTATE,
-            SNI_QUERY_CONN_SOBUFAUTOTUNING,
-            SNI_QUERY_CONN_SECPKGNAME,
-            SNI_QUERY_CONN_SECPKGMUTUALAUTH,
-            SNI_QUERY_CONN_CONSUMERCONNID,
-            SNI_QUERY_CONN_SNIUCI,
-            SNI_QUERY_CONN_SUPPORTS_EXTENDED_PROTECTION,
-            SNI_QUERY_CONN_CHANNEL_PROVIDES_AUTHENTICATION_CONTEXT,
-            SNI_QUERY_CONN_PEERID,
-            SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC,
-        }
-
-        internal enum TransparentNetworkResolutionMode : byte
-        {
-            DisabledMode = 0,
-            SequentialMode,
-            ParallelMode
-        };
-
-        [StructLayout(LayoutKind.Sequential)]
-        private struct Sni_Consumer_Info
-        {
-            public int DefaultUserDataLength;
-            public IntPtr ConsumerKey;
-            public IntPtr fnReadComp;
-            public IntPtr fnWriteComp;
-            public IntPtr fnTrace;
-            public IntPtr fnAcceptComp;
-            public uint dwNumProts;
-            public IntPtr rgListenInfo;
-            public IntPtr NodeAffinity;
-        }
-
-        [StructLayout(LayoutKind.Sequential)]
-        private unsafe struct SNI_CLIENT_CONSUMER_INFO
-        {
-            public Sni_Consumer_Info ConsumerInfo;
-            [MarshalAs(UnmanagedType.LPWStr)]
-            public string wszConnectionString;
-            public PrefixEnum networkLibrary;
-            public byte* szSPN;
-            public uint cchSPN;
-            public byte* szInstanceName;
-            public uint cchInstanceName;
-            [MarshalAs(UnmanagedType.Bool)]
-            public bool fOverrideLastConnectCache;
-            [MarshalAs(UnmanagedType.Bool)]
-            public bool fSynchronousConnection;
-            public int timeout;
-            [MarshalAs(UnmanagedType.Bool)]
-            public bool fParallel;
-            public TransparentNetworkResolutionMode transparentNetworkResolution;
-            public int totalTimeout;
-            public bool isAzureSqlServerEndpoint;
-        }
-
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        internal struct SNI_Error
-        {
-            internal ProviderEnum provider;
-            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 261)]
-            internal string errorMessage;
-            internal uint nativeError;
-            internal uint sniError;
-            [MarshalAs(UnmanagedType.LPWStr)]
-            internal string fileName;
-            [MarshalAs(UnmanagedType.LPWStr)]
-            internal string function;
-            internal uint lineNumber;
-        }
-
-        #endregion
-
-        #region DLL Imports
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIAddProviderWrapper")]
-        internal static extern uint SNIAddProvider(SNIHandle pConn, ProviderEnum ProvNum, [In] ref uint pInfo);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICheckConnectionWrapper")]
-        internal static extern uint SNICheckConnection([In] SNIHandle pConn);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNICloseWrapper")]
-        internal static extern uint SNIClose(IntPtr pConn);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern void SNIGetLastError(out SNI_Error pErrorStruct);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern void SNIPacketRelease(IntPtr pPacket);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIPacketResetWrapper")]
-        internal static extern void SNIPacketReset([In] SNIHandle pConn, IOType IOType, SNIPacket pPacket, ConsumerNumber ConsNum);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern uint SNIQueryInfo(QTypes QType, ref uint pbQInfo);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern uint SNIQueryInfo(QTypes QType, ref IntPtr pbQInfo);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIReadAsyncWrapper")]
-        internal static extern uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIRemoveProviderWrapper")]
-        internal static extern uint SNIRemoveProvider(SNIHandle pConn, ProviderEnum ProvNum);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern uint SNISecInitPackage(ref uint pcbMaxToken);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNISetInfoWrapper")]
-        internal static extern uint SNISetInfo(SNIHandle pConn, QTypes QType, [In] ref uint pbQInfo);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern uint SNITerminate();
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SNIWaitForSSLHandshakeToCompleteWrapper")]
-        internal static extern uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        internal static extern uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint GetSniMaxComposedSpnLength();
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out Guid pbQInfo);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint SNIInitialize([In] IntPtr pmo);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint SNIOpenSyncExWrapper(ref SNI_CLIENT_CONSUMER_INFO pClientConsumerInfo, out IntPtr ppConn);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint SNIOpenWrapper(
-            [In] ref Sni_Consumer_Info pConsumerInfo,
-            [MarshalAs(UnmanagedType.LPStr)] string szConnect,
-            [In] SNIHandle pConn,
-            out IntPtr ppConn,
-            [MarshalAs(UnmanagedType.Bool)] bool fSync);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IOType IOType);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern unsafe uint SNISecGenClientContextWrapper(
-            [In] SNIHandle pConn,
-            [In, Out] byte[] pIn,
-            uint cbIn,
-            [In, Out] byte[] pOut,
-            [In] ref uint pcbOut,
-            [MarshalAsAttribute(UnmanagedType.Bool)] out bool pfDone,
-            byte* szServerInfo,
-            uint cbServerInfo,
-            [MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszUserName,
-            [MarshalAsAttribute(UnmanagedType.LPWStr)] string pwszPassword);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket);
-
-        [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
-        private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket);
-        #endregion
-
-        internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId)
-        {
-            return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId);
-        }
-
-        internal static uint SNIInitialize()
-        {
-            return SNIInitialize(IntPtr.Zero);
-        }
-
-        internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync)
-        {
-            // initialize consumer info for MARS
-            Sni_Consumer_Info native_consumerInfo = default;
-            MarshalConsumerInfo(consumerInfo, ref native_consumerInfo);
-
-            return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync);
-        }
-
-        internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel)
-        {
-            fixed (byte* pin_instanceName = &instanceName[0])
-            {
-                SNI_CLIENT_CONSUMER_INFO clientConsumerInfo = default;
-
-                // initialize client ConsumerInfo part first
-                MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo);
-
-                clientConsumerInfo.wszConnectionString = constring;
-                clientConsumerInfo.networkLibrary = PrefixEnum.UNKNOWN_PREFIX;
-
-                clientConsumerInfo.szInstanceName = pin_instanceName;
-                clientConsumerInfo.cchInstanceName = (uint)instanceName.Length;
-                clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache;
-                clientConsumerInfo.fSynchronousConnection = fSync;
-                clientConsumerInfo.timeout = timeout;
-                clientConsumerInfo.fParallel = fParallel;
-
-                clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.DisabledMode;
-                clientConsumerInfo.totalTimeout = SniOpenTimeOut;
-                clientConsumerInfo.isAzureSqlServerEndpoint = ADP.IsAzureSqlServerEndpoint(constring);
-
-                if (spnBuffer != null)
-                {
-                    fixed (byte* pin_spnBuffer = &spnBuffer[0])
-                    {
-                        clientConsumerInfo.szSPN = pin_spnBuffer;
-                        clientConsumerInfo.cchSPN = (uint)spnBuffer.Length;
-                        return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn);
-                    }
-                }
-                else
-                {
-                    // else leave szSPN null (SQL Auth)
-                    return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn);
-                }
-            }
-        }
-
-        internal static void SNIPacketAllocate(SafeHandle pConn, IOType IOType, ref IntPtr pPacket)
-        {
-            pPacket = SNIPacketAllocateWrapper(pConn, IOType);
-        }
-
-        internal static unsafe uint SNIPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize)
-        {
-            return SNIPacketGetDataWrapper(packet, readBuffer, (uint)readBuffer.Length, out dataSize);
-        }
-
-        internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int length)
-        {
-            fixed (byte* pin_data = &data[0])
-            {
-                SNIPacketSetData(packet, pin_data, (uint)length);
-            }
-        }
-
-        internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, byte[] inBuff, uint receivedLength, byte[] OutBuff, ref uint sendLength, byte[] serverUserName)
-        {
-            fixed (byte* pin_serverUserName = &serverUserName[0])
-            {
-                bool local_fDone;
-                return SNISecGenClientContextWrapper(
-                    pConnectionObject,
-                    inBuff,
-                    receivedLength,
-                    OutBuff,
-                    ref sendLength,
-                    out local_fDone,
-                    pin_serverUserName,
-                    (uint)serverUserName.Length,
-                    null,
-                    null);
-            }
-        }
-
-        internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync)
-        {
-            if (sync)
-            {
-                return SNIWriteSyncOverAsync(pConn, packet);
-            }
-            else
-            {
-                return SNIWriteAsyncWrapper(pConn, packet);
-            }
-        }
-
-        private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo)
-        {
-            native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize;
-            native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate
-                ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate)
-                : IntPtr.Zero;
-            native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate
-                ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate)
-                : IntPtr.Zero;
-            native_consumerInfo.ConsumerKey = consumerInfo.key;
-        }
-    }
-}
-
-namespace System.Data
-{
-    internal static partial class SafeNativeMethods
-    {
-        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)]
-        internal static extern IntPtr GetProcAddress(IntPtr HModule, [MarshalAs(UnmanagedType.LPStr), In] string funcName);
-    }
-}
-
-namespace System.Data
-{
-    internal static class Win32NativeMethods
-    {
-        internal static bool IsTokenRestrictedWrapper(IntPtr token)
-        {
-            bool isRestricted;
-            uint result = SNINativeMethodWrapper.UnmanagedIsTokenRestricted(token, out isRestricted);
-
-            if (result != 0)
-            {
-                Marshal.ThrowExceptionForHR(unchecked((int)result));
-            }
-
-            return isRestricted;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/MatchingRefApiCompatBaseline.netstandard2.0.txt b/src/libraries/System.Data.SqlClient/src/MatchingRefApiCompatBaseline.netstandard2.0.txt
deleted file mode 100644 (file)
index e9342d6..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# netstandard dll has been shipped with IDbColumnSchemaGenerator inherited and SqlDataReader.GetColumnScheme() implemented in source, but not exposed in ref contract.
-# Removing SqlDataReader.GetColumnScheme() from netstandard implementation potentially breaks existing customer source code
-# that utilizes SqlDataReader.GetColumnScheme() indirectly by casting SqlDataReader to IDbColumnSchemaGenerator type.
-# In order to prevent it, the API needs to be kept in public, and following 2 error message should be remaining in this baseline file.
-#
-CannotRemoveBaseTypeOrInterface : Type 'System.Data.SqlClient.SqlDataReader' does not implement interface 'System.Data.Common.IDbColumnSchemaGenerator' in the reference but it does in the implementation.
-MembersMustExist : Member 'System.Data.SqlClient.SqlDataReader.GetColumnSchema()' does not exist in the reference but it does exist in the implementation.
-
-# We cannot fix these issues in the netstandard2.0 assembly since we no longer build it.
-CannotRemoveAttribute : Attribute 'System.ComponentModel.TypeConverterAttribute' exists on 'System.Data.SqlClient.SqlConnectionStringBuilder.InitialCatalog' in the implementation but not the reference.
-CannotRemoveAttribute : Attribute 'System.ComponentModel.DefaultValueAttribute' exists on 'System.Data.SqlClient.SqlParameter.Precision' in the implementation but not the reference.
-CannotRemoveAttribute : Attribute 'System.ComponentModel.DefaultValueAttribute' exists on 'System.Data.SqlClient.SqlParameter.Scale' in the implementation but not the reference.
-CannotRemoveAttribute : Attribute 'System.Data.Common.DbProviderSpecificTypePropertyAttribute' exists on 'System.Data.SqlClient.SqlParameter.SqlDbType' in the implementation but not the reference.
-CannotRemoveAttribute : Attribute 'System.ComponentModel.TypeConverterAttribute' exists on 'System.Data.SqlClient.SqlParameter.Value' in the implementation but not the reference.
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ExtendedClrTypeCode.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ExtendedClrTypeCode.cs
deleted file mode 100644 (file)
index 5790926..0000000
+++ /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.
-
-
-
-//------------------------------------------------------------------------------
-
-namespace Microsoft.SqlServer.Server
-{
-    internal enum ExtendedClrTypeCode
-    {
-        Invalid = -1,
-        Boolean,                    // System.Boolean
-        Byte,                       // System.Byte
-        Char,                       // System.Char
-        DateTime,                   // System.DateTime
-        DBNull,                     // System.DBNull
-        Decimal,                    // System.Decimal
-        Double,                     // System.Double
-        Empty,                      // null reference
-        Int16,                      // System.Int16
-        Int32,                      // System.Int32
-        Int64,                      // System.Int64
-        SByte,                      // System.SByte
-        Single,                     // System.Single
-        String,                     // System.String
-        UInt16,                     // System.UInt16
-        UInt32,                     // System.UInt32
-        UInt64,                     // System.UInt64
-        Object,                     // System.Object
-        ByteArray,                  // System.ByteArray
-        CharArray,                  // System.CharArray
-        Guid,                       // System.Guid
-        SqlBinary,                  // System.Data.SqlTypes.SqlBinary
-        SqlBoolean,                 // System.Data.SqlTypes.SqlBoolean
-        SqlByte,                    // System.Data.SqlTypes.SqlByte
-        SqlDateTime,                // System.Data.SqlTypes.SqlDateTime
-        SqlDouble,                  // System.Data.SqlTypes.SqlDouble
-        SqlGuid,                    // System.Data.SqlTypes.SqlGuid
-        SqlInt16,                   // System.Data.SqlTypes.SqlInt16
-        SqlInt32,                   // System.Data.SqlTypes.SqlInt32
-        SqlInt64,                   // System.Data.SqlTypes.SqlInt64
-        SqlMoney,                   // System.Data.SqlTypes.SqlMoney
-        SqlDecimal,                 // System.Data.SqlTypes.SqlDecimal
-        SqlSingle,                  // System.Data.SqlTypes.SqlSingle
-        SqlString,                  // System.Data.SqlTypes.SqlString
-        SqlChars,                   // System.Data.SqlTypes.SqlChars
-        SqlBytes,                   // System.Data.SqlTypes.SqlBytes
-        SqlXml,                     // System.Data.SqlTypes.SqlXml
-        DataTable,                  // System.Data.DataTable
-        DbDataReader,               // System.Data.DbDataReader (SqlDataReader falls under this category)
-        IEnumerableOfSqlDataRecord, // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord>
-        TimeSpan,                   // System.TimeSpan
-        DateTimeOffset,             // System.DateTimeOffset
-        Stream,                     // System.IO.Stream
-        TextReader,                 // System.IO.TextReader
-        XmlReader,                  // System.Xml.XmlReader
-        Last = XmlReader,           // end-of-enum marker
-        First = Boolean,            // beginning-of-enum marker
-    };
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedGetters.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedGetters.cs
deleted file mode 100644 (file)
index bd360b7..0000000
+++ /dev/null
@@ -1,103 +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.Data;
-using System.Data.SqlTypes;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Interface for strongly-typed value getters
-    internal interface ITypedGetters
-    {
-        // Null test
-        bool IsDBNull(int ordinal);
-
-        // Check what type current sql_variant value is
-        SqlDbType GetVariantType(int ordinal);
-
-        // By value accessors  (data copy across the interface boundary implied)
-        bool GetBoolean(int ordinal);
-
-        byte GetByte(int ordinal);
-
-        long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
-
-        char GetChar(int ordinal);
-
-        long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
-
-        short GetInt16(int ordinal);
-
-        int GetInt32(int ordinal);
-
-        long GetInt64(int ordinal);
-
-        float GetFloat(int ordinal);
-
-        double GetDouble(int ordinal);
-
-        string GetString(int ordinal);
-
-        decimal GetDecimal(int ordinal);
-
-        DateTime GetDateTime(int ordinal);
-
-        Guid GetGuid(int ordinal);
-
-        SqlBoolean GetSqlBoolean(int ordinal);
-
-        SqlByte GetSqlByte(int ordinal);
-
-        SqlInt16 GetSqlInt16(int ordinal);
-
-        SqlInt32 GetSqlInt32(int ordinal);
-
-        SqlInt64 GetSqlInt64(int ordinal);
-
-        SqlSingle GetSqlSingle(int ordinal);
-
-        SqlDouble GetSqlDouble(int ordinal);
-
-        SqlMoney GetSqlMoney(int ordinal);
-
-        SqlDateTime GetSqlDateTime(int ordinal);
-
-        SqlDecimal GetSqlDecimal(int ordinal);
-
-        SqlString GetSqlString(int ordinal);
-
-        SqlBinary GetSqlBinary(int ordinal);
-
-        SqlGuid GetSqlGuid(int ordinal);
-
-        SqlChars GetSqlChars(int ordinal);
-
-        SqlBytes GetSqlBytes(int ordinal);
-
-        SqlXml GetSqlXml(int ordinal);
-
-
-        // "By reference" accessors
-        //    May hook to buffer.
-        //    Semantics guarantee is that as long as the object exposing the accessor is not logically
-        //    moved to a new set of values and the overall state (open/closed) isn't changed, it will not
-        //    change the underlying value returned and continue to allow access to it.
-        //
-        //    Example: GetSqlCharsRef called on an event stream value.  The back-end optimizes by re-using
-        //        the buffer wrapped by the returned SqlChars on the next row event, but guarantees that it
-        //        won't change the value until the next event is consumed.
-        //
-        //    Simplest way to guarantee this behavior is to simply call the corresponding by-value accessor.
-        SqlBytes GetSqlBytesRef(int ordinal);
-
-        SqlChars GetSqlCharsRef(int ordinal);
-
-        SqlXml GetSqlXmlRef(int ordinal);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedGettersV3.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedGettersV3.cs
deleted file mode 100644 (file)
index 729b7bc..0000000
+++ /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.Data.SqlTypes;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Interface for strongly-typed value getters
-    internal interface ITypedGettersV3
-    {
-        // Null test
-        //      valid for all types
-        bool IsDBNull(SmiEventSink sink, int ordinal);
-
-        // Check what type current sql_variant value is
-        //      valid for SqlDbType.Variant
-        SmiMetaData GetVariantType(SmiEventSink sink, int ordinal);
-
-        //
-        //  Actual value accessors
-        //      valid type indicates column must be of the type or column must be variant
-        //           and GetVariantType returned the type
-        //
-
-        //  valid for SqlDbType.Bit
-        bool GetBoolean(SmiEventSink sink, int ordinal);
-
-        //  valid for SqlDbType.TinyInt
-        byte GetByte(SmiEventSink sink, int ordinal);
-
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml, Char, VarChar, Text, NChar, NVarChar, NText
-        //  (Character type support needed for ExecuteXmlReader handling)
-        long GetBytesLength(SmiEventSink sink, int ordinal);
-        int GetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        long GetCharsLength(SmiEventSink sink, int ordinal);
-        int GetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
-        string GetString(SmiEventSink sink, int ordinal);
-
-        // valid for SqlDbType.SmallInt
-        short GetInt16(SmiEventSink sink, int ordinal);
-
-        // valid for SqlDbType.Int
-        int GetInt32(SmiEventSink sink, int ordinal);
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        long GetInt64(SmiEventSink sink, int ordinal);
-
-        // valid for SqlDbType.Real
-        float GetSingle(SmiEventSink sink, int ordinal);
-
-        // valid for SqlDbType.Float
-        double GetDouble(SmiEventSink sink, int ordinal);
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        SqlDecimal GetSqlDecimal(SmiEventSink sink, int ordinal);
-
-        // valid for DateTime & SmallDateTime
-        DateTime GetDateTime(SmiEventSink sink, int ordinal);
-
-        // valid for UniqueIdentifier
-        Guid GetGuid(SmiEventSink sink, int ordinal);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedSetters.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedSetters.cs
deleted file mode 100644 (file)
index 55cee16..0000000
+++ /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.Data.SqlTypes;
-
-namespace Microsoft.SqlServer.Server
-{
-    // interface for strongly-typed value setters
-    internal interface ITypedSetters
-    {
-        // By value setters (data copy across the interface boundary implied)
-        void SetDBNull(int ordinal);
-
-        void SetBoolean(int ordinal, bool value);
-
-        void SetByte(int ordinal, byte value);
-
-        void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
-
-        void SetChar(int ordinal, char value);
-
-        void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
-
-        void SetInt16(int ordinal, short value);
-
-        void SetInt32(int ordinal, int value);
-
-        void SetInt64(int ordinal, long value);
-
-        void SetFloat(int ordinal, float value);
-
-        void SetDouble(int ordinal, double value);
-
-        [ObsoleteAttribute("Not supported as of SMI v2.  Will be removed when v1 support dropped.  Use setter with offset.")]
-        void SetString(int ordinal, string value);
-
-        // Method introduced as of SMI V2
-        void SetString(int ordinal, string value, int offset);
-
-        void SetDecimal(int ordinal, decimal value);
-
-        void SetDateTime(int ordinal, DateTime value);
-
-        void SetGuid(int ordinal, Guid value);
-
-        void SetSqlBoolean(int ordinal, SqlBoolean value);
-
-        void SetSqlByte(int ordinal, SqlByte value);
-
-        void SetSqlInt16(int ordinal, SqlInt16 value);
-
-        void SetSqlInt32(int ordinal, SqlInt32 value);
-
-        void SetSqlInt64(int ordinal, SqlInt64 value);
-
-        void SetSqlSingle(int ordinal, SqlSingle value);
-
-        void SetSqlDouble(int ordinal, SqlDouble value);
-
-        void SetSqlMoney(int ordinal, SqlMoney value);
-
-        void SetSqlDateTime(int ordinal, SqlDateTime value);
-
-        void SetSqlDecimal(int ordinal, SqlDecimal value);
-
-        [ObsoleteAttribute("Not supported as of SMI v2.  Will be removed when v1 support dropped.  Use setter with offset.")]
-        void SetSqlString(int ordinal, SqlString value);
-
-        // Method introduced as of SMI V2
-        void SetSqlString(int ordinal, SqlString value, int offset);
-
-        [ObsoleteAttribute("Not supported as of SMI v2.  Will be removed when v1 support dropped.  Use setter with offset.")]
-        void SetSqlBinary(int ordinal, SqlBinary value);
-
-        // Method introduced as of SMI V2
-        void SetSqlBinary(int ordinal, SqlBinary value, int offset);
-
-        void SetSqlGuid(int ordinal, SqlGuid value);
-
-        [ObsoleteAttribute("Not supported as of SMI v2.  Will be removed when v1 support dropped.  Use setter with offset.")]
-        void SetSqlChars(int ordinal, SqlChars value);
-
-        // Method introduced as of SMI V2
-        void SetSqlChars(int ordinal, SqlChars value, int offset);
-
-        [ObsoleteAttribute("Not supported as of SMI v2.  Will be removed when v1 support dropped.  Use setter with offset.")]
-        void SetSqlBytes(int ordinal, SqlBytes value);
-
-        // Method introduced as of SMI V2
-        void SetSqlBytes(int ordinal, SqlBytes value, int offset);
-
-        void SetSqlXml(int ordinal, SqlXml value);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedSettersV3.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ITypedSettersV3.cs
deleted file mode 100644 (file)
index 397fa74..0000000
+++ /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.Data.SqlTypes;
-
-namespace Microsoft.SqlServer.Server
-{
-    // interface for strongly-typed value setters
-    internal interface ITypedSettersV3
-    {
-        // By value setters (data copy across the interface boundary implied)
-        //  All setters are valid for SqlDbType.Variant
-
-        // SetVariantMetaData is used to set the precise type of data just before pushing
-        //  data into a variant type via one of the other setters. It
-        //  is only valid to set metadata with a SqlDbType that associated with the
-        //  data setter that will be called.
-        //  Since LOBs, Udt's and fixed-length types are not currently stored in a variant,
-        //  the following pairs are the only setters/sqldbtypes that need this call:
-        //      NVarChar/VarChar + SetString (needed only for non-global collation, i.e. SqlString)
-        //      Money/SmallMoney + SetInt64
-        void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData);
-
-        // Set value to null
-        //  valid for all types
-        void SetDBNull(SmiEventSink sink, int ordinal);
-
-        //  valid for SqlDbType.Bit
-        void SetBoolean(SmiEventSink sink, int ordinal, bool value);
-
-        //  valid for SqlDbType.TinyInt
-        void SetByte(SmiEventSink sink, int ordinal, byte value);
-
-        // Semantics for SetBytes are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
-        //      (VarBinary assumed for variants)
-        int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
-        void SetBytesLength(SmiEventSink sink, int ordinal, long length);
-
-        // Semantics for SetChars are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        //      (NVarChar and global clr collation assumed for variants)
-        int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
-        void SetCharsLength(SmiEventSink sink, int ordinal, long length);
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length);
-
-        // valid for SqlDbType.SmallInt
-        void SetInt16(SmiEventSink sink, int ordinal, short value);
-
-        // valid for SqlDbType.Int
-        void SetInt32(SmiEventSink sink, int ordinal, int value);
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        void SetInt64(SmiEventSink sink, int ordinal, long value);
-
-        // valid for SqlDbType.Real
-        void SetSingle(SmiEventSink sink, int ordinal, float value);
-
-        // valid for SqlDbType.Float
-        void SetDouble(SmiEventSink sink, int ordinal, double value);
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value);
-
-        // valid for DateTime & SmallDateTime
-        void SetDateTime(SmiEventSink sink, int ordinal, DateTime value);
-
-        // valid for UniqueIdentifier
-        void SetGuid(SmiEventSink sink, int ordinal, Guid value);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/MemoryRecordBuffer.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/MemoryRecordBuffer.cs
deleted file mode 100644 (file)
index f07f84e..0000000
+++ /dev/null
@@ -1,267 +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.Data.SqlTypes;
-using System.Diagnostics;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Class for implementing a record object used in out-of-proc scenarios.
-    internal sealed class MemoryRecordBuffer : SmiRecordBuffer
-    {
-        private readonly SqlRecordBuffer[] _buffer;
-
-        internal MemoryRecordBuffer(SmiMetaData[] metaData)
-        {
-            Debug.Assert(null != metaData, "invalid attempt to instantiate MemoryRecordBuffer with null SmiMetaData[]");
-
-            _buffer = new SqlRecordBuffer[metaData.Length];
-
-            for (int i = 0; i < _buffer.Length; ++i)
-            {
-                _buffer[i] = new SqlRecordBuffer(metaData[i]);
-            }
-        }
-
-        #region Getters
-        // Null test
-        //      valid for all types
-        public override bool IsDBNull(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].IsNull;
-        }
-
-        // Check what type current sql_variant value is
-        //      valid for SqlDbType.Variant
-        public override SmiMetaData GetVariantType(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].VariantType;
-        }
-
-        //  valid for SqlDbType.Bit
-        public override bool GetBoolean(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Boolean;
-        }
-
-        //  valid for SqlDbType.TinyInt
-        public override byte GetByte(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Byte;
-        }
-
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml, Char, VarChar, Text, NChar, NVarChar, NText
-        //  (Character type support needed for ExecuteXmlReader handling)
-        public override long GetBytesLength(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].BytesLength;
-        }
-        public override int GetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            return _buffer[ordinal].GetBytes(fieldOffset, buffer, bufferOffset, length);
-        }
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        public override long GetCharsLength(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].CharsLength;
-        }
-        public override int GetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            return _buffer[ordinal].GetChars(fieldOffset, buffer, bufferOffset, length);
-        }
-        public override string GetString(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].String;
-        }
-
-        // valid for SqlDbType.SmallInt
-        public override short GetInt16(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Int16;
-        }
-
-        // valid for SqlDbType.Int
-        public override int GetInt32(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Int32;
-        }
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        public override long GetInt64(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Int64;
-        }
-
-        // valid for SqlDbType.Real
-        public override float GetSingle(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Single;
-        }
-
-        // valid for SqlDbType.Float
-        public override double GetDouble(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Double;
-        }
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        public override SqlDecimal GetSqlDecimal(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].SqlDecimal;
-        }
-
-        // valid for DateTime, SmallDateTime, Date, and DateTime2
-        public override DateTime GetDateTime(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].DateTime;
-        }
-
-        // valid for UniqueIdentifier
-        public override Guid GetGuid(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].Guid;
-        }
-
-        // valid for SqlDbType.Time
-        public override TimeSpan GetTimeSpan(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].TimeSpan;
-        }
-
-        // valid for DateTimeOffset
-        public override DateTimeOffset GetDateTimeOffset(SmiEventSink sink, int ordinal)
-        {
-            return _buffer[ordinal].DateTimeOffset;
-        }
-        #endregion
-
-        #region Setters
-        // Set value to null
-        //  valid for all types
-        public override void SetDBNull(SmiEventSink sink, int ordinal)
-        {
-            _buffer[ordinal].SetNull();
-        }
-
-        //  valid for SqlDbType.Bit
-        public override void SetBoolean(SmiEventSink sink, int ordinal, bool value)
-        {
-            _buffer[ordinal].Boolean = value;
-        }
-
-        //  valid for SqlDbType.TinyInt
-        public override void SetByte(SmiEventSink sink, int ordinal, byte value)
-        {
-            _buffer[ordinal].Byte = value;
-        }
-
-        // Semantics for SetBytes are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
-        //      (VarBinary assumed for variants)
-        public override int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            return _buffer[ordinal].SetBytes(fieldOffset, buffer, bufferOffset, length);
-        }
-        public override void SetBytesLength(SmiEventSink sink, int ordinal, long length)
-        {
-            _buffer[ordinal].BytesLength = length;
-        }
-
-        // Semantics for SetChars are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        //      (NVarChar and global clr collation assumed for variants)
-        public override int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            return _buffer[ordinal].SetChars(fieldOffset, buffer, bufferOffset, length);
-        }
-        public override void SetCharsLength(SmiEventSink sink, int ordinal, long length)
-        {
-            _buffer[ordinal].CharsLength = length;
-        }
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        public override void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length)
-        {
-            Debug.Assert(offset == 0 && length <= value.Length, "Invalid string length or offset"); // for sqlvariant, length could be less than value.Length
-
-            _buffer[ordinal].String = value.Substring(offset, length); // Perf test shows that Substring method has already optimized the case where length = value.Length
-        }
-
-        // valid for SqlDbType.SmallInt
-        public override void SetInt16(SmiEventSink sink, int ordinal, short value)
-        {
-            _buffer[ordinal].Int16 = value;
-        }
-
-        // valid for SqlDbType.Int
-        public override void SetInt32(SmiEventSink sink, int ordinal, int value)
-        {
-            _buffer[ordinal].Int32 = value;
-        }
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        public override void SetInt64(SmiEventSink sink, int ordinal, long value)
-        {
-            _buffer[ordinal].Int64 = value;
-        }
-
-        // valid for SqlDbType.Real
-        public override void SetSingle(SmiEventSink sink, int ordinal, float value)
-        {
-            _buffer[ordinal].Single = value;
-        }
-
-        // valid for SqlDbType.Float
-        public override void SetDouble(SmiEventSink sink, int ordinal, double value)
-        {
-            _buffer[ordinal].Double = value;
-        }
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        public override void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value)
-        {
-            _buffer[ordinal].SqlDecimal = value;
-        }
-
-        // valid for DateTime, SmallDateTime, Date, and DateTime2
-        public override void SetDateTime(SmiEventSink sink, int ordinal, DateTime value)
-        {
-            _buffer[ordinal].DateTime = value;
-        }
-
-        // valid for UniqueIdentifier
-        public override void SetGuid(SmiEventSink sink, int ordinal, Guid value)
-        {
-            _buffer[ordinal].Guid = value;
-        }
-
-        // SqlDbType.Time
-        public override void SetTimeSpan(SmiEventSink sink, int ordinal, TimeSpan value)
-        {
-            _buffer[ordinal].TimeSpan = value;
-        }
-
-        // DateTimeOffset
-        public override void SetDateTimeOffset(SmiEventSink sink, int ordinal, DateTimeOffset value)
-        {
-            _buffer[ordinal].DateTimeOffset = value;
-        }
-
-        // valid for SqlDbType.Variant
-        public override void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData)
-        {
-            _buffer[ordinal].VariantType = metaData;
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/MetadataUtilsSmi.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/MetadataUtilsSmi.cs
deleted file mode 100644 (file)
index 59e3fb1..0000000
+++ /dev/null
@@ -1,964 +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;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Globalization;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Utilities for manipulating smi-related metadata.
-    //
-    //  Since this class is built on top of SMI, SMI should not have a dependency on this class
-    //
-    //  These are all based off of knowing the clr type of the value
-    //  as an ExtendedClrTypeCode enum for rapid access.
-    internal class MetaDataUtilsSmi
-    {
-        internal const SqlDbType InvalidSqlDbType = (SqlDbType)(-1);
-        internal const long InvalidMaxLength = -2;
-
-        // Standard type inference map to get SqlDbType when all you know is the value's type (typecode)
-        //  This map's index is off by one (add one to typecode locate correct entry) in order
-        //  to support ExtendedSqlDbType.Invalid
-        //  This array is meant to be accessed from InferSqlDbTypeFromTypeCode.
-        private static readonly SqlDbType[] s_extendedTypeCodeToSqlDbTypeMap = {
-            InvalidSqlDbType,               // Invalid extended type code
-            SqlDbType.Bit,                  // System.Boolean
-            SqlDbType.TinyInt,              // System.Byte
-            SqlDbType.NVarChar,             // System.Char
-            SqlDbType.DateTime,             // System.DateTime
-            InvalidSqlDbType,               // System.DBNull doesn't have an inferable SqlDbType
-            SqlDbType.Decimal,              // System.Decimal
-            SqlDbType.Float,                // System.Double
-            InvalidSqlDbType,               // null reference doesn't have an inferable SqlDbType
-            SqlDbType.SmallInt,             // System.Int16
-            SqlDbType.Int,                  // System.Int32
-            SqlDbType.BigInt,               // System.Int64
-            InvalidSqlDbType,               // System.SByte doesn't have an inferable SqlDbType
-            SqlDbType.Real,                 // System.Single
-            SqlDbType.NVarChar,             // System.String
-            InvalidSqlDbType,               // System.UInt16 doesn't have an inferable SqlDbType
-            InvalidSqlDbType,               // System.UInt32 doesn't have an inferable SqlDbType
-            InvalidSqlDbType,               // System.UInt64 doesn't have an inferable SqlDbType
-            InvalidSqlDbType,               // System.Object doesn't have an inferable SqlDbType
-            SqlDbType.VarBinary,            // System.ByteArray
-            SqlDbType.NVarChar,             // System.CharArray
-            SqlDbType.UniqueIdentifier,     // System.Guid
-            SqlDbType.VarBinary,            // System.Data.SqlTypes.SqlBinary
-            SqlDbType.Bit,                  // System.Data.SqlTypes.SqlBoolean
-            SqlDbType.TinyInt,              // System.Data.SqlTypes.SqlByte
-            SqlDbType.DateTime,             // System.Data.SqlTypes.SqlDateTime
-            SqlDbType.Float,                // System.Data.SqlTypes.SqlDouble
-            SqlDbType.UniqueIdentifier,     // System.Data.SqlTypes.SqlGuid
-            SqlDbType.SmallInt,             // System.Data.SqlTypes.SqlInt16
-            SqlDbType.Int,                  // System.Data.SqlTypes.SqlInt32
-            SqlDbType.BigInt,               // System.Data.SqlTypes.SqlInt64
-            SqlDbType.Money,                // System.Data.SqlTypes.SqlMoney
-            SqlDbType.Decimal,              // System.Data.SqlTypes.SqlDecimal
-            SqlDbType.Real,                 // System.Data.SqlTypes.SqlSingle
-            SqlDbType.NVarChar,             // System.Data.SqlTypes.SqlString
-            SqlDbType.NVarChar,             // System.Data.SqlTypes.SqlChars
-            SqlDbType.VarBinary,            // System.Data.SqlTypes.SqlBytes
-            SqlDbType.Xml,                  // System.Data.SqlTypes.SqlXml
-            SqlDbType.Structured,           // System.Data.DataTable
-            SqlDbType.Structured,           // System.Collections.IEnumerable, used for TVPs it must return IDataRecord
-            SqlDbType.Structured,           // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord>
-            SqlDbType.Time,                 // System.TimeSpan
-            SqlDbType.DateTimeOffset,       // System.DateTimeOffset
-        };
-
-        // Dictionary to map from clr type object to ExtendedClrTypeCodeMap enum.
-        // This dictionary should only be accessed from DetermineExtendedTypeCode and class ctor for setup.
-        private static readonly Dictionary<Type, ExtendedClrTypeCode> s_typeToExtendedTypeCodeMap = CreateTypeToExtendedTypeCodeMap();
-
-        private static Dictionary<Type, ExtendedClrTypeCode> CreateTypeToExtendedTypeCodeMap()
-        {
-            int Count = 42;
-            // Keep this initialization list in the same order as ExtendedClrTypeCode for ease in validating!
-            var dictionary = new Dictionary<Type, ExtendedClrTypeCode>(Count)
-            {
-                { typeof(bool), ExtendedClrTypeCode.Boolean },
-                { typeof(byte), ExtendedClrTypeCode.Byte },
-                { typeof(char), ExtendedClrTypeCode.Char },
-                { typeof(DateTime), ExtendedClrTypeCode.DateTime },
-                { typeof(DBNull), ExtendedClrTypeCode.DBNull },
-                { typeof(decimal), ExtendedClrTypeCode.Decimal },
-                { typeof(double), ExtendedClrTypeCode.Double },
-                // lookup code will handle special-case null-ref, omitting the addition of ExtendedTypeCode.Empty
-                { typeof(short), ExtendedClrTypeCode.Int16 },
-                { typeof(int), ExtendedClrTypeCode.Int32 },
-                { typeof(long), ExtendedClrTypeCode.Int64 },
-                { typeof(sbyte), ExtendedClrTypeCode.SByte },
-                { typeof(float), ExtendedClrTypeCode.Single },
-                { typeof(string), ExtendedClrTypeCode.String },
-                { typeof(ushort), ExtendedClrTypeCode.UInt16 },
-                { typeof(uint), ExtendedClrTypeCode.UInt32 },
-                { typeof(ulong), ExtendedClrTypeCode.UInt64 },
-                { typeof(object), ExtendedClrTypeCode.Object },
-                { typeof(byte[]), ExtendedClrTypeCode.ByteArray },
-                { typeof(char[]), ExtendedClrTypeCode.CharArray },
-                { typeof(Guid), ExtendedClrTypeCode.Guid },
-                { typeof(SqlBinary), ExtendedClrTypeCode.SqlBinary },
-                { typeof(SqlBoolean), ExtendedClrTypeCode.SqlBoolean },
-                { typeof(SqlByte), ExtendedClrTypeCode.SqlByte },
-                { typeof(SqlDateTime), ExtendedClrTypeCode.SqlDateTime },
-                { typeof(SqlDouble), ExtendedClrTypeCode.SqlDouble },
-                { typeof(SqlGuid), ExtendedClrTypeCode.SqlGuid },
-                { typeof(SqlInt16), ExtendedClrTypeCode.SqlInt16 },
-                { typeof(SqlInt32), ExtendedClrTypeCode.SqlInt32 },
-                { typeof(SqlInt64), ExtendedClrTypeCode.SqlInt64 },
-                { typeof(SqlMoney), ExtendedClrTypeCode.SqlMoney },
-                { typeof(SqlDecimal), ExtendedClrTypeCode.SqlDecimal },
-                { typeof(SqlSingle), ExtendedClrTypeCode.SqlSingle },
-                { typeof(SqlString), ExtendedClrTypeCode.SqlString },
-                { typeof(SqlChars), ExtendedClrTypeCode.SqlChars },
-                { typeof(SqlBytes), ExtendedClrTypeCode.SqlBytes },
-                { typeof(SqlXml), ExtendedClrTypeCode.SqlXml },
-                { typeof(DataTable), ExtendedClrTypeCode.DataTable },
-                { typeof(DbDataReader), ExtendedClrTypeCode.DbDataReader },
-                { typeof(IEnumerable<SqlDataRecord>), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord },
-                { typeof(TimeSpan), ExtendedClrTypeCode.TimeSpan },
-                { typeof(DateTimeOffset), ExtendedClrTypeCode.DateTimeOffset },
-            };
-            return dictionary;
-        }
-
-        internal static bool IsCharOrXmlType(SqlDbType type)
-        {
-            return IsUnicodeType(type) ||
-                    IsAnsiType(type) ||
-                    type == SqlDbType.Xml;
-        }
-
-        internal static bool IsUnicodeType(SqlDbType type)
-        {
-            return type == SqlDbType.NChar ||
-                    type == SqlDbType.NVarChar ||
-                    type == SqlDbType.NText;
-        }
-
-        internal static bool IsAnsiType(SqlDbType type)
-        {
-            return type == SqlDbType.Char ||
-                    type == SqlDbType.VarChar ||
-                    type == SqlDbType.Text;
-        }
-
-        internal static bool IsBinaryType(SqlDbType type)
-        {
-            return type == SqlDbType.Binary ||
-                    type == SqlDbType.VarBinary ||
-                    type == SqlDbType.Image;
-        }
-
-        // Does this type use PLP format values?
-        internal static bool IsPlpFormat(SmiMetaData metaData)
-        {
-            return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator ||
-                    metaData.SqlDbType == SqlDbType.Image ||
-                    metaData.SqlDbType == SqlDbType.NText ||
-                    metaData.SqlDbType == SqlDbType.Text ||
-                    metaData.SqlDbType == SqlDbType.Udt;
-        }
-
-        // If we know we're only going to use this object to assign to a specific SqlDbType back end object,
-        //  we can save some processing time by only checking for the few valid types that can be assigned to the dbType.
-        //  This assumes a switch statement over SqlDbType is faster than getting the ClrTypeCode and iterating over a
-        //  series of if statements, or using a hash table.
-        // NOTE: the form of these checks is taking advantage of a feature of the JIT compiler that is supposed to
-        //      optimize checks of the form '(xxx.GetType() == typeof( YYY ))'.  The JIT team claimed at one point that
-        //      this doesn't even instantiate a Type instance, thus was the fastest method for individual comparisons.
-        //      Given that there's a known SqlDbType, thus a minimal number of comparisons, it's likely this is faster
-        //      than the other approaches considered (both GetType().GetTypeCode() switch and hash table using Type keys
-        //      must instantiate a Type object.  The typecode switch also degenerates into a large if-then-else for
-        //      all but the primitive clr types.
-        internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType(
-                SqlDbType dbType,
-                bool isMultiValued,
-                object value,
-                Type udtType)
-        {
-            ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid;
-
-            // fast-track null, which is valid for all types
-            if (null == value)
-            {
-                extendedCode = ExtendedClrTypeCode.Empty;
-            }
-            else if (DBNull.Value == value)
-            {
-                extendedCode = ExtendedClrTypeCode.DBNull;
-            }
-            else
-            {
-                switch (dbType)
-                {
-                    case SqlDbType.BigInt:
-                        if (value.GetType() == typeof(long))
-                            extendedCode = ExtendedClrTypeCode.Int64;
-                        else if (value.GetType() == typeof(SqlInt64))
-                            extendedCode = ExtendedClrTypeCode.SqlInt64;
-                        break;
-                    case SqlDbType.Binary:
-                    case SqlDbType.VarBinary:
-                    case SqlDbType.Image:
-                    case SqlDbType.Timestamp:
-                        if (value.GetType() == typeof(byte[]))
-                            extendedCode = ExtendedClrTypeCode.ByteArray;
-                        else if (value.GetType() == typeof(SqlBinary))
-                            extendedCode = ExtendedClrTypeCode.SqlBinary;
-                        else if (value.GetType() == typeof(SqlBytes))
-                            extendedCode = ExtendedClrTypeCode.SqlBytes;
-                        else if (value.GetType() == typeof(StreamDataFeed))
-                            extendedCode = ExtendedClrTypeCode.Stream;
-                        break;
-                    case SqlDbType.Bit:
-                        if (value.GetType() == typeof(bool))
-                            extendedCode = ExtendedClrTypeCode.Boolean;
-                        else if (value.GetType() == typeof(SqlBoolean))
-                            extendedCode = ExtendedClrTypeCode.SqlBoolean;
-                        break;
-                    case SqlDbType.Char:
-                    case SqlDbType.NChar:
-                    case SqlDbType.NText:
-                    case SqlDbType.NVarChar:
-                    case SqlDbType.Text:
-                    case SqlDbType.VarChar:
-                        if (value.GetType() == typeof(string))
-                            extendedCode = ExtendedClrTypeCode.String;
-                        if (value.GetType() == typeof(TextDataFeed))
-                            extendedCode = ExtendedClrTypeCode.TextReader;
-                        else if (value.GetType() == typeof(SqlString))
-                            extendedCode = ExtendedClrTypeCode.SqlString;
-                        else if (value.GetType() == typeof(char[]))
-                            extendedCode = ExtendedClrTypeCode.CharArray;
-                        else if (value.GetType() == typeof(SqlChars))
-                            extendedCode = ExtendedClrTypeCode.SqlChars;
-                        else if (value.GetType() == typeof(char))
-                            extendedCode = ExtendedClrTypeCode.Char;
-                        break;
-                    case SqlDbType.Date:
-                    case SqlDbType.DateTime2:
-                    case SqlDbType.DateTime:
-                    case SqlDbType.SmallDateTime:
-                        if (value.GetType() == typeof(DateTime))
-                            extendedCode = ExtendedClrTypeCode.DateTime;
-                        else if (value.GetType() == typeof(SqlDateTime))
-                            extendedCode = ExtendedClrTypeCode.SqlDateTime;
-                        break;
-                    case SqlDbType.Decimal:
-                        if (value.GetType() == typeof(decimal))
-                            extendedCode = ExtendedClrTypeCode.Decimal;
-                        else if (value.GetType() == typeof(SqlDecimal))
-                            extendedCode = ExtendedClrTypeCode.SqlDecimal;
-                        break;
-                    case SqlDbType.Real:
-                        if (value.GetType() == typeof(float))
-                            extendedCode = ExtendedClrTypeCode.Single;
-                        else if (value.GetType() == typeof(SqlSingle))
-                            extendedCode = ExtendedClrTypeCode.SqlSingle;
-                        break;
-                    case SqlDbType.Int:
-                        if (value.GetType() == typeof(int))
-                            extendedCode = ExtendedClrTypeCode.Int32;
-                        else if (value.GetType() == typeof(SqlInt32))
-                            extendedCode = ExtendedClrTypeCode.SqlInt32;
-                        break;
-                    case SqlDbType.Money:
-                    case SqlDbType.SmallMoney:
-                        if (value.GetType() == typeof(SqlMoney))
-                            extendedCode = ExtendedClrTypeCode.SqlMoney;
-                        else if (value.GetType() == typeof(decimal))
-                            extendedCode = ExtendedClrTypeCode.Decimal;
-                        break;
-                    case SqlDbType.Float:
-                        if (value.GetType() == typeof(SqlDouble))
-                            extendedCode = ExtendedClrTypeCode.SqlDouble;
-                        else if (value.GetType() == typeof(double))
-                            extendedCode = ExtendedClrTypeCode.Double;
-                        break;
-                    case SqlDbType.UniqueIdentifier:
-                        if (value.GetType() == typeof(SqlGuid))
-                            extendedCode = ExtendedClrTypeCode.SqlGuid;
-                        else if (value.GetType() == typeof(Guid))
-                            extendedCode = ExtendedClrTypeCode.Guid;
-                        break;
-                    case SqlDbType.SmallInt:
-                        if (value.GetType() == typeof(short))
-                            extendedCode = ExtendedClrTypeCode.Int16;
-                        else if (value.GetType() == typeof(SqlInt16))
-                            extendedCode = ExtendedClrTypeCode.SqlInt16;
-                        break;
-                    case SqlDbType.TinyInt:
-                        if (value.GetType() == typeof(byte))
-                            extendedCode = ExtendedClrTypeCode.Byte;
-                        else if (value.GetType() == typeof(SqlByte))
-                            extendedCode = ExtendedClrTypeCode.SqlByte;
-                        break;
-                    case SqlDbType.Variant:
-                        // SqlDbType doesn't help us here, call general-purpose function
-                        extendedCode = DetermineExtendedTypeCode(value);
-
-                        // Some types aren't allowed for Variants but are for the general-purpose function.
-                        //  Match behavior of other types and return invalid in these cases.
-                        if (ExtendedClrTypeCode.SqlXml == extendedCode)
-                        {
-                            extendedCode = ExtendedClrTypeCode.Invalid;
-                        }
-                        break;
-                    case SqlDbType.Udt:
-                        // Validate UDT type if caller gave us a type to validate against
-                        if (null == udtType || value.GetType() == udtType)
-                        {
-                            extendedCode = ExtendedClrTypeCode.Object;
-                        }
-                        else
-                        {
-                            extendedCode = ExtendedClrTypeCode.Invalid;
-                        }
-                        break;
-                    case SqlDbType.Time:
-                        if (value.GetType() == typeof(TimeSpan))
-                            extendedCode = ExtendedClrTypeCode.TimeSpan;
-                        break;
-                    case SqlDbType.DateTimeOffset:
-                        if (value.GetType() == typeof(DateTimeOffset))
-                            extendedCode = ExtendedClrTypeCode.DateTimeOffset;
-                        break;
-                    case SqlDbType.Xml:
-                        if (value.GetType() == typeof(SqlXml))
-                            extendedCode = ExtendedClrTypeCode.SqlXml;
-                        if (value.GetType() == typeof(XmlDataFeed))
-                            extendedCode = ExtendedClrTypeCode.XmlReader;
-                        else if (value.GetType() == typeof(string))
-                            extendedCode = ExtendedClrTypeCode.String;
-                        break;
-                    case SqlDbType.Structured:
-                        if (isMultiValued)
-                        {
-                            if (value is DataTable)
-                            {
-                                extendedCode = ExtendedClrTypeCode.DataTable;
-                            }
-                            else if (value is IEnumerable<SqlDataRecord>)
-                            {
-                                extendedCode = ExtendedClrTypeCode.IEnumerableOfSqlDataRecord;
-                            }
-                            else if (value is DbDataReader)
-                            {
-                                extendedCode = ExtendedClrTypeCode.DbDataReader;
-                            }
-                        }
-                        break;
-                    default:
-                        // Leave as invalid
-                        break;
-                }
-            }
-
-            return extendedCode;
-        }
-
-        // Method to map from Type to ExtendedTypeCode
-        internal static ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType)
-        {
-            ExtendedClrTypeCode resultCode;
-            return s_typeToExtendedTypeCodeMap.TryGetValue(clrType, out resultCode) ?
-                resultCode :
-                ExtendedClrTypeCode.Invalid;
-        }
-
-        // Returns the ExtendedClrTypeCode that describes the given value
-        internal static ExtendedClrTypeCode DetermineExtendedTypeCode(object value)
-        {
-            return value != null ?
-                DetermineExtendedTypeCodeFromType(value.GetType()) :
-                ExtendedClrTypeCode.Empty;
-        }
-
-        // returns a sqldbtype for the given type code
-        internal static SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCode)
-        {
-            Debug.Assert(typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!");
-
-            return s_extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1];
-        }
-
-        // Infer SqlDbType from Type in the general case.  Katmai-only (or later) features that need to
-        //  infer types should use InferSqlDbTypeFromType_Katmai.
-        internal static SqlDbType InferSqlDbTypeFromType(Type type)
-        {
-            ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type);
-            SqlDbType returnType;
-            if (ExtendedClrTypeCode.Invalid == typeCode)
-            {
-                returnType = InvalidSqlDbType;  // Return invalid type so caller can generate specific error
-            }
-            else
-            {
-                returnType = InferSqlDbTypeFromTypeCode(typeCode);
-            }
-
-            return returnType;
-        }
-
-        // Inference rules changed for Katmai-or-later-only cases.  Only features that are guaranteed to be
-        //  running against Katmai and don't have backward compat issues should call this code path.
-        //      example: TVP's are a new Katmai feature (no back compat issues) so can infer DATETIME2
-        //          when mapping System.DateTime from DateTable or DbDataReader.  DATETIME2 is better because
-        //          of greater range that can handle all DateTime values.
-        internal static SqlDbType InferSqlDbTypeFromType_Katmai(Type type)
-        {
-            SqlDbType returnType = InferSqlDbTypeFromType(type);
-            if (SqlDbType.DateTime == returnType)
-            {
-                returnType = SqlDbType.DateTime2;
-            }
-            return returnType;
-        }
-
-        internal static SqlMetaData SmiExtendedMetaDataToSqlMetaData(SmiExtendedMetaData source)
-        {
-            if (SqlDbType.Xml == source.SqlDbType)
-            {
-                return new SqlMetaData(source.Name,
-                    source.SqlDbType,
-                    source.MaxLength,
-                    source.Precision,
-                    source.Scale,
-                    source.LocaleId,
-                    source.CompareOptions,
-                    source.TypeSpecificNamePart1,
-                    source.TypeSpecificNamePart2,
-                    source.TypeSpecificNamePart3,
-                    true,
-                    source.Type);
-            }
-
-            return new SqlMetaData(source.Name,
-                source.SqlDbType,
-                source.MaxLength,
-                source.Precision,
-                source.Scale,
-                source.LocaleId,
-                source.CompareOptions,
-                null);
-        }
-
-        // Convert SqlMetaData instance to an SmiExtendedMetaData instance.
-        internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source)
-        {
-            // now map everything across to the extended metadata object
-            string typeSpecificNamePart1 = null;
-            string typeSpecificNamePart2 = null;
-            string typeSpecificNamePart3 = null;
-
-            if (SqlDbType.Xml == source.SqlDbType)
-            {
-                typeSpecificNamePart1 = source.XmlSchemaCollectionDatabase;
-                typeSpecificNamePart2 = source.XmlSchemaCollectionOwningSchema;
-                typeSpecificNamePart3 = source.XmlSchemaCollectionName;
-            }
-            else if (SqlDbType.Udt == source.SqlDbType)
-            {
-                // Split the input name. UdtTypeName is specified as single 3 part name.
-                // NOTE: ParseUdtTypeName throws if format is incorrect
-                string typeName = source.ServerTypeName;
-                if (null != typeName)
-                {
-                    string[] names = SqlParameter.ParseTypeName(typeName, true /* isUdtTypeName */);
-
-                    if (1 == names.Length)
-                    {
-                        typeSpecificNamePart3 = names[0];
-                    }
-                    else if (2 == names.Length)
-                    {
-                        typeSpecificNamePart2 = names[0];
-                        typeSpecificNamePart3 = names[1];
-                    }
-                    else if (3 == names.Length)
-                    {
-                        typeSpecificNamePart1 = names[0];
-                        typeSpecificNamePart2 = names[1];
-                        typeSpecificNamePart3 = names[2];
-                    }
-                    else
-                    {
-                        throw ADP.ArgumentOutOfRange(nameof(typeName));
-                    }
-
-                    if ((!string.IsNullOrEmpty(typeSpecificNamePart1) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart1.Length)
-                        || (!string.IsNullOrEmpty(typeSpecificNamePart2) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart2.Length)
-                        || (!string.IsNullOrEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length))
-                    {
-                        throw ADP.ArgumentOutOfRange(nameof(typeName));
-                    }
-                }
-            }
-
-            return new SmiExtendedMetaData(source.SqlDbType,
-                                            source.MaxLength,
-                                            source.Precision,
-                                            source.Scale,
-                                            source.LocaleId,
-                                            source.CompareOptions,
-                                            null,
-                                            source.Name,
-                                            typeSpecificNamePart1,
-                                            typeSpecificNamePart2,
-                                            typeSpecificNamePart3);
-        }
-
-        // compare SmiMetaData to SqlMetaData and determine if they are compatible.
-        internal static bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd)
-        {
-            return firstMd.SqlDbType == secondMd.SqlDbType &&
-                    firstMd.MaxLength == secondMd.MaxLength &&
-                    firstMd.Precision == secondMd.Precision &&
-                    firstMd.Scale == secondMd.Scale &&
-                    firstMd.CompareOptions == secondMd.CompareOptions &&
-                    firstMd.LocaleId == secondMd.LocaleId &&
-                    firstMd.SqlDbType != SqlDbType.Structured &&  // SqlMetaData doesn't support Structured types
-                    !firstMd.IsMultiValued;  // SqlMetaData doesn't have a "multivalued" option
-        }
-
-        // Extract metadata for a single DataColumn
-        internal static SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, DataTable parent)
-        {
-            SqlDbType dbType = InferSqlDbTypeFromType_Katmai(column.DataType);
-            if (InvalidSqlDbType == dbType)
-            {
-                throw SQL.UnsupportedColumnTypeForSqlProvider(column.ColumnName, column.DataType.Name);
-            }
-
-            long maxLength = AdjustMaxLength(dbType, column.MaxLength);
-            if (InvalidMaxLength == maxLength)
-            {
-                throw SQL.InvalidColumnMaxLength(column.ColumnName, maxLength);
-            }
-
-            byte precision;
-            byte scale;
-            if (column.DataType == typeof(SqlDecimal))
-            {
-                // Must scan all values in column to determine best-fit precision & scale
-                Debug.Assert(null != parent);
-                scale = 0;
-                byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision
-                foreach (DataRow row in parent.Rows)
-                {
-                    object obj = row[column];
-                    if (!(obj is DBNull))
-                    {
-                        SqlDecimal value = (SqlDecimal)obj;
-                        if (!value.IsNull)
-                        {
-                            byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale));
-                            if (tempNonFractPrec > nonFractionalPrecision)
-                            {
-                                nonFractionalPrecision = tempNonFractPrec;
-                            }
-
-                            if (value.Scale > scale)
-                            {
-                                scale = value.Scale;
-                            }
-                        }
-                    }
-                }
-
-                precision = checked((byte)(nonFractionalPrecision + scale));
-
-                if (SqlDecimal.MaxPrecision < precision)
-                {
-                    throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision);
-                }
-                else if (0 == precision)
-                {
-                    precision = 1;
-                }
-            }
-            else if (dbType == SqlDbType.DateTime2 || dbType == SqlDbType.DateTimeOffset || dbType == SqlDbType.Time)
-            {
-                // Time types care about scale, too.  But have to infer maximums for these.
-                precision = 0;
-                scale = SmiMetaData.DefaultTime.Scale;
-            }
-            else if (dbType == SqlDbType.Decimal)
-            {
-                // Must scan all values in column to determine best-fit precision & scale
-                Debug.Assert(null != parent);
-                scale = 0;
-                byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision
-                foreach (DataRow row in parent.Rows)
-                {
-                    object obj = row[column];
-                    if (!(obj is DBNull))
-                    {
-                        SqlDecimal value = (SqlDecimal)(decimal)obj;
-                        byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale));
-                        if (tempNonFractPrec > nonFractionalPrecision)
-                        {
-                            nonFractionalPrecision = tempNonFractPrec;
-                        }
-
-                        if (value.Scale > scale)
-                        {
-                            scale = value.Scale;
-                        }
-                    }
-                }
-
-                precision = checked((byte)(nonFractionalPrecision + scale));
-
-                if (SqlDecimal.MaxPrecision < precision)
-                {
-                    throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision);
-                }
-                else if (0 == precision)
-                {
-                    precision = 1;
-                }
-            }
-            else
-            {
-                precision = 0;
-                scale = 0;
-            }
-
-            // In Net Core, since DataColumn.Locale is not accessible because it is internal and in a separate assembly,
-            // we try to get the Locale from the parent
-            CultureInfo columnLocale = ((null != parent) ? parent.Locale : CultureInfo.CurrentCulture);
-
-            return new SmiExtendedMetaData(
-                                        dbType,
-                                        maxLength,
-                                        precision,
-                                        scale,
-                                        columnLocale.LCID,
-                                        SmiMetaData.DefaultNVarChar.CompareOptions,
-                                        null,
-                                        false,  // no support for multi-valued columns in a TVP yet
-                                        null,   // no support for structured columns yet
-                                        null,   // no support for structured columns yet
-                                        column.ColumnName,
-                                        null,
-                                        null,
-                                        null);
-        }
-
-        internal static long AdjustMaxLength(SqlDbType dbType, long maxLength)
-        {
-            if (SmiMetaData.UnlimitedMaxLengthIndicator != maxLength)
-            {
-                if (maxLength < 0)
-                {
-                    maxLength = InvalidMaxLength;
-                }
-
-                switch (dbType)
-                {
-                    case SqlDbType.Binary:
-                        if (maxLength > SmiMetaData.MaxBinaryLength)
-                        {
-                            maxLength = InvalidMaxLength;
-                        }
-                        break;
-                    case SqlDbType.Char:
-                        if (maxLength > SmiMetaData.MaxANSICharacters)
-                        {
-                            maxLength = InvalidMaxLength;
-                        }
-                        break;
-                    case SqlDbType.NChar:
-                        if (maxLength > SmiMetaData.MaxUnicodeCharacters)
-                        {
-                            maxLength = InvalidMaxLength;
-                        }
-                        break;
-                    case SqlDbType.NVarChar:
-                        // Promote to MAX type if it won't fit in a normal type
-                        if (SmiMetaData.MaxUnicodeCharacters < maxLength)
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-                        break;
-                    case SqlDbType.VarBinary:
-                        // Promote to MAX type if it won't fit in a normal type
-                        if (SmiMetaData.MaxBinaryLength < maxLength)
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-                        break;
-                    case SqlDbType.VarChar:
-                        // Promote to MAX type if it won't fit in a normal type
-                        if (SmiMetaData.MaxANSICharacters < maxLength)
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-                        break;
-                    default:
-                        break;
-                }
-            }
-
-            return maxLength;
-        }
-
-        // Map SmiMetaData from a schema table.
-        // DEVNOTE: Since we're using SchemaTable, we can assume that we aren't directly using a SqlDataReader
-        // so we don't support the Sql-specific stuff, like collation.
-        internal static SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schemaRow)
-        {
-            string colName = "";
-            object temp = schemaRow[SchemaTableColumn.ColumnName];
-            if (DBNull.Value != temp)
-            {
-                colName = (string)temp;
-            }
-
-            // Determine correct SqlDbType.
-            temp = schemaRow[SchemaTableColumn.DataType];
-            if (DBNull.Value == temp)
-            {
-                throw SQL.NullSchemaTableDataTypeNotSupported(colName);
-            }
-
-            Type colType = (Type)temp;
-            SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType);
-            if (InvalidSqlDbType == colDbType)
-            {
-                // Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise error
-                if (typeof(object) == colType)
-                {
-                    colDbType = SqlDbType.VarBinary;
-                }
-                else
-                {
-                    throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString());
-                }
-            }
-
-            // Determine metadata modifier values per type (maxlength, precision, scale, etc)
-            long maxLength = 0;
-            byte precision = 0;
-            byte scale = 0;
-            switch (colDbType)
-            {
-                case SqlDbType.BigInt:
-                case SqlDbType.Bit:
-                case SqlDbType.DateTime:
-                case SqlDbType.Float:
-                case SqlDbType.Image:
-                case SqlDbType.Int:
-                case SqlDbType.Money:
-                case SqlDbType.NText:
-                case SqlDbType.Real:
-                case SqlDbType.UniqueIdentifier:
-                case SqlDbType.SmallDateTime:
-                case SqlDbType.SmallInt:
-                case SqlDbType.SmallMoney:
-                case SqlDbType.Text:
-                case SqlDbType.Timestamp:
-                case SqlDbType.TinyInt:
-                case SqlDbType.Variant:
-                case SqlDbType.Xml:
-                case SqlDbType.Date:
-                    // These types require no  metadata modifies
-                    break;
-                case SqlDbType.Binary:
-                case SqlDbType.VarBinary:
-                    // These types need a binary max length
-                    temp = schemaRow[SchemaTableColumn.ColumnSize];
-                    if (DBNull.Value == temp)
-                    {
-                        // source isn't specifying a size, so assume the worst
-                        if (SqlDbType.Binary == colDbType)
-                        {
-                            maxLength = SmiMetaData.MaxBinaryLength;
-                        }
-                        else
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-                    }
-                    else
-                    {
-                        // We (should) have a valid maxlength, so use it.
-                        maxLength = Convert.ToInt64(temp, null);
-
-                        // Max length must be 0 to MaxBinaryLength or it can be UnlimitedMAX if type is varbinary.
-                        // If it's greater than MaxBinaryLength, just promote it to UnlimitedMAX, if possible.
-                        if (maxLength > SmiMetaData.MaxBinaryLength)
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-
-                        if ((maxLength < 0 &&
-                                (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator ||
-                                 SqlDbType.Binary == colDbType)))
-                        {
-                            throw SQL.InvalidColumnMaxLength(colName, maxLength);
-                        }
-                    }
-                    break;
-                case SqlDbType.Char:
-                case SqlDbType.VarChar:
-                    // These types need an ANSI max length
-                    temp = schemaRow[SchemaTableColumn.ColumnSize];
-                    if (DBNull.Value == temp)
-                    {
-                        // source isn't specifying a size, so assume the worst
-                        if (SqlDbType.Char == colDbType)
-                        {
-                            maxLength = SmiMetaData.MaxANSICharacters;
-                        }
-                        else
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-                    }
-                    else
-                    {
-                        // We (should) have a valid maxlength, so use it.
-                        maxLength = Convert.ToInt64(temp, null);
-
-                        // Max length must be 0 to MaxANSICharacters or it can be UnlimitedMAX if type is varbinary.
-                        // If it's greater than MaxANSICharacters, just promote it to UnlimitedMAX, if possible.
-                        if (maxLength > SmiMetaData.MaxANSICharacters)
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-
-                        if ((maxLength < 0 &&
-                                (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator ||
-                                 SqlDbType.Char == colDbType)))
-                        {
-                            throw SQL.InvalidColumnMaxLength(colName, maxLength);
-                        }
-                    }
-                    break;
-                case SqlDbType.NChar:
-                case SqlDbType.NVarChar:
-                    // These types need a unicode max length
-                    temp = schemaRow[SchemaTableColumn.ColumnSize];
-                    if (DBNull.Value == temp)
-                    {
-                        // source isn't specifying a size, so assume the worst
-                        if (SqlDbType.NChar == colDbType)
-                        {
-                            maxLength = SmiMetaData.MaxUnicodeCharacters;
-                        }
-                        else
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-                    }
-                    else
-                    {
-                        // We (should) have a valid maxlength, so use it.
-                        maxLength = Convert.ToInt64(temp, null);
-
-                        // Max length must be 0 to MaxUnicodeCharacters or it can be UnlimitedMAX if type is varbinary.
-                        // If it's greater than MaxUnicodeCharacters, just promote it to UnlimitedMAX, if possible.
-                        if (maxLength > SmiMetaData.MaxUnicodeCharacters)
-                        {
-                            maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-
-                        if ((maxLength < 0 &&
-                                (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator ||
-                                 SqlDbType.NChar == colDbType)))
-                        {
-                            throw SQL.InvalidColumnMaxLength(colName, maxLength);
-                        }
-                    }
-                    break;
-                case SqlDbType.Decimal:
-                    // Decimal requires precision and scale
-                    temp = schemaRow[SchemaTableColumn.NumericPrecision];
-                    if (DBNull.Value == temp)
-                    {
-                        precision = SmiMetaData.DefaultDecimal.Precision;
-                    }
-                    else
-                    {
-                        precision = Convert.ToByte(temp, null);
-                    }
-
-                    temp = schemaRow[SchemaTableColumn.NumericScale];
-                    if (DBNull.Value == temp)
-                    {
-                        scale = SmiMetaData.DefaultDecimal.Scale;
-                    }
-                    else
-                    {
-                        scale = Convert.ToByte(temp, null);
-                    }
-
-                    if (precision < SmiMetaData.MinPrecision ||
-                            precision > SqlDecimal.MaxPrecision ||
-                            scale < SmiMetaData.MinScale ||
-                            scale > SqlDecimal.MaxScale ||
-                            scale > precision)
-                    {
-                        throw SQL.InvalidColumnPrecScale();
-                    }
-                    break;
-                case SqlDbType.Time:
-                case SqlDbType.DateTime2:
-                case SqlDbType.DateTimeOffset:
-                    // requires scale
-                    temp = schemaRow[SchemaTableColumn.NumericScale];
-                    if (DBNull.Value == temp)
-                    {
-                        scale = SmiMetaData.DefaultTime.Scale;
-                    }
-                    else
-                    {
-                        scale = Convert.ToByte(temp, null);
-                    }
-
-                    if (scale > SmiMetaData.MaxTimeScale)
-                    {
-                        throw SQL.InvalidColumnPrecScale();
-                    }
-                    else if (scale < 0)
-                    {
-                        scale = SmiMetaData.DefaultTime.Scale;
-                    }
-                    break;
-                case SqlDbType.Udt:
-                case SqlDbType.Structured:
-                default:
-                    // These types are not supported from SchemaTable
-                    throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString());
-            }
-
-            return new SmiExtendedMetaData(
-                            colDbType,
-                            maxLength,
-                            precision,
-                            scale,
-                            System.Globalization.CultureInfo.CurrentCulture.LCID,
-                            SmiMetaData.GetDefaultForType(colDbType).CompareOptions,
-                            null,
-                            false,  // no support for multi-valued columns in a TVP yet
-                            null,   // no support for structured columns yet
-                            null,   // no support for structured columns yet
-                            colName,
-                            null,
-                            null,
-                            null);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiEventSink.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiEventSink.cs
deleted file mode 100644 (file)
index 103c074..0000000
+++ /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;
-using System.Data;
-
-
-namespace Microsoft.SqlServer.Server
-{
-    // SqlEventSink is implemented by calling code.  In all methods that accept
-    // a SqlEventSink directly the sink must be able to handle multiple callbacks
-    // without control returning from the original call.
-
-    // Methods that do not accept SmiEventSync are (generally) ProcessEvent on
-    // the SmiEventStream methods returning a SmiEventStream and methods that
-    // are certain to never call to the server (most will, for in-proc back end).
-
-    // Methods are commented with their corresponding TDS token
-
-    // NOTE: Throwing from these methods will not usually produce the desired
-    //       effect -- the managed to native boundary will eat any exceptions,
-    //       and will cause a simple "Something bad happened" exception to be
-    //       thrown in the native to managed boundary...
-    internal abstract class SmiEventSink
-    {
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiEventSink_Default.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiEventSink_Default.cs
deleted file mode 100644 (file)
index 99bd083..0000000
+++ /dev/null
@@ -1,115 +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.Data.SqlClient;
-using System.Diagnostics;
-
-namespace Microsoft.SqlServer.Server
-{
-    internal class SmiEventSink_Default : SmiEventSink
-    {
-        private SqlErrorCollection _errors;
-        private SqlErrorCollection _warnings;
-
-
-        internal bool HasMessages
-        {
-            get
-            {
-                {
-                    bool result = (null != _errors || null != _warnings);
-                    return result;
-                }
-            }
-        }
-
-        internal virtual string ServerVersion
-        {
-            get
-            {
-                return null;
-            }
-        }
-
-
-        protected virtual void DispatchMessages()
-        {
-            // virtual because we want a default implementation in the cases
-            // where we don't have a connection to process stuff, but we want to
-            // provide the connection the ability to fire info messages when it
-            // hooks up.
-            {
-                SqlException errors = ProcessMessages(true);   // ignore warnings, because there's no place to send them...
-                if (null != errors)
-                {
-                    throw errors;
-                }
-            }
-        }
-
-        protected SqlException ProcessMessages(bool ignoreWarnings)
-        {
-            SqlException result = null;
-            SqlErrorCollection temp = null;  // temp variable to store that which is being thrown - so that local copies can be deleted
-
-            if (null != _errors)
-            {
-                Debug.Assert(0 != _errors.Count, "empty error collection?"); // must be something in the collection
-
-                {
-                    if (null != _warnings)
-                    {
-                        // When we throw an exception we place all the warnings that
-                        // occurred at the end of the collection - after all the errors.
-                        // That way the user can see all the errors AND warnings that
-                        // occurred for the exception.
-                        foreach (SqlError warning in _warnings)
-                        {
-                            _errors.Add(warning);
-                        }
-                    }
-                    temp = _errors;
-                }
-
-                _errors = null;
-                _warnings = null;
-            }
-            else
-            {
-                Debug.Assert(null == _warnings || 0 != _warnings.Count, "empty warning collection?"); // must be something in the collection
-
-                if (!ignoreWarnings)
-                {
-                    temp = _warnings;
-                }
-                _warnings = null;
-            }
-
-            if (null != temp)
-            {
-                result = SqlException.CreateException(temp, ServerVersion);
-            }
-            return result;
-        }
-
-
-        internal void ProcessMessagesAndThrow()
-        {
-            if (HasMessages)
-            {
-                DispatchMessages();
-            }
-        }
-
-
-
-        internal SmiEventSink_Default()
-        {
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiGettersStream.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiGettersStream.cs
deleted file mode 100644 (file)
index d661cd8..0000000
+++ /dev/null
@@ -1,112 +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.Data.Common;
-using System.Data.SqlClient;
-using System.IO;
-using System.Diagnostics;
-
-namespace Microsoft.SqlServer.Server
-{
-    internal class SmiGettersStream : Stream
-    {
-        private readonly SmiEventSink_Default _sink;
-        private readonly ITypedGettersV3 _getters;
-        private readonly int _ordinal;
-        private long _readPosition;
-        private readonly SmiMetaData _metaData;
-
-        internal SmiGettersStream(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            Debug.Assert(null != sink);
-            Debug.Assert(null != getters);
-            Debug.Assert(0 <= ordinal);
-            Debug.Assert(null != metaData);
-
-            _sink = sink;
-            _getters = getters;
-            _ordinal = ordinal;
-            _readPosition = 0;
-            _metaData = metaData;
-        }
-
-        public override bool CanRead
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        // If CanSeek is false, Position, Seek, Length, and SetLength should throw.
-        public override bool CanSeek
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public override bool CanWrite
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public override long Length
-        {
-            get
-            {
-                return ValueUtilsSmi.GetBytesInternal(_sink, _getters, _ordinal, _metaData, 0, null, 0, 0, false);
-            }
-        }
-
-        public override long Position
-        {
-            get
-            {
-                return _readPosition;
-            }
-            set
-            {
-                throw SQL.StreamSeekNotSupported();
-            }
-        }
-
-        public override void Flush()
-        {
-            throw SQL.StreamWriteNotSupported();
-        }
-
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            throw SQL.StreamSeekNotSupported();
-        }
-
-        public override void SetLength(long value)
-        {
-            throw SQL.StreamWriteNotSupported();
-        }
-
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            long bytesRead = ValueUtilsSmi.GetBytesInternal(_sink, _getters, _ordinal, _metaData, _readPosition, buffer, offset, count, false);
-            _readPosition += bytesRead;
-
-            return checked((int)bytesRead);
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            throw SQL.StreamWriteNotSupported();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiMetaData.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiMetaData.cs
deleted file mode 100644 (file)
index 33bbfc5..0000000
+++ /dev/null
@@ -1,1287 +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.Diagnostics;
-using System.Data;
-using System.Data.SqlTypes;
-using System.Globalization;
-
-namespace Microsoft.SqlServer.Server
-{
-    // DESIGN NOTES
-    //
-    //  The following classes are a tight inheritance hierarchy, and are not designed for
-    //  being inherited outside of this file.  Instances are guaranteed to be immutable, and
-    //  outside classes rely on this fact.
-    //
-    //  The various levels may not all be used outside of this file, but for clarity of purpose
-    //  they are all useful distinctions to make.
-    //
-    //  In general, moving lower in the type hierarchy exposes less portable values.  Thus,
-    //  the root metadata can be readily shared across different (MSSQL) servers and clients,
-    //  while QueryMetaData has attributes tied to a specific query, running against specific
-    //  data storage on a specific server.
-    //
-    //  The SmiMetaData hierarchy does not do data validation on retail builds!  It will assert
-    //  that the values passed to it have been validated externally, however.
-    //
-
-
-    // SmiMetaData
-    //
-    //  Root of the hierarchy.
-    //  Represents the minimal amount of metadata required to represent any Sql Server datum
-    //  without any references to any particular server or schema (thus, no server-specific multi-part names).
-    //  It could be used to communicate solely between two disconnected clients, for instance.
-    //
-    //  NOTE: It currently does not contain sufficient information to describe typed XML, since we
-    //      don't have a good server-independent mechanism for such.
-    //
-    //  This class is also used as implementation for the public SqlMetaData class.
-    internal class SmiMetaData
-    {
-        private SqlDbType _databaseType;          // Main enum that determines what is valid for other attributes.
-        private long _maxLength;             // Varies for variable-length types, others are fixed value per type
-        private byte _precision;             // Varies for SqlDbType.Decimal, others are fixed value per type
-        private byte _scale;                 // Varies for SqlDbType.Decimal, others are fixed value per type
-        private long _localeId;              // Valid only for character types, others are 0
-        private SqlCompareOptions _compareOptions;        // Valid only for character types, others are SqlCompareOptions.Default
-        private Type _clrType;               // Varies for SqlDbType.Udt, others are fixed value per type.
-        private string _udtAssemblyQualifiedName;           // Valid only for UDT types when _clrType is not available
-        private bool _isMultiValued;         // Multiple instances per value? (I.e. tables, arrays)
-        private IList<SmiExtendedMetaData> _fieldMetaData;         // Metadata of fields for structured types
-        private SmiMetaDataPropertyCollection _extendedProperties;  // Extended properties, Key columns, sort order, etc.
-
-        // Limits for attributes (SmiMetaData will assert that these limits as applicable in constructor)
-        internal const long UnlimitedMaxLengthIndicator = -1;  // unlimited (except by implementation) max-length.
-        internal const long MaxUnicodeCharacters = 4000;        // Maximum for limited type
-        internal const long MaxANSICharacters = 8000;           // Maximum for limited type
-        internal const long MaxBinaryLength = 8000;             // Maximum for limited type
-        internal const int MinPrecision = 1;       // SqlDecimal defines max precision
-        internal const int MinScale = 0;            // SqlDecimal defines max scale
-        internal const int MaxTimeScale = 7;        // Max scale for time, datetime2, and datetimeoffset
-        internal static readonly DateTime MaxSmallDateTime = new DateTime(2079, 06, 06, 23, 59, 29, 998);
-        internal static readonly DateTime MinSmallDateTime = new DateTime(1899, 12, 31, 23, 59, 29, 999);
-        internal static readonly SqlMoney MaxSmallMoney = new SqlMoney(((decimal)int.MaxValue) / 10000);
-        internal static readonly SqlMoney MinSmallMoney = new SqlMoney(((decimal)int.MinValue) / 10000);
-        internal const SqlCompareOptions DefaultStringCompareOptions = SqlCompareOptions.IgnoreCase
-                                        | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
-
-        internal const long MaxNameLength = 128;        // maximum length in the server is 128.
-        private static readonly IList<SmiExtendedMetaData> s_emptyFieldList = new List<SmiExtendedMetaData>().AsReadOnly();
-
-        // Precision to max length lookup table
-        private static readonly byte[] s_maxLenFromPrecision = new byte[]
-        {
-            5, 5, 5, 5, 5, 5, 5, 5, 5, 9, 9, 9, 9, 9, 9, 9,
-            9, 9, 9, 13, 13, 13, 13, 13, 13, 13, 13, 13, 17,
-            17, 17, 17, 17, 17, 17, 17, 17, 17
-        };
-
-        // Scale offset to max length lookup table
-        private static readonly byte[] s_maxVarTimeLenOffsetFromScale = new byte[] { 2, 2, 2, 1, 1, 0, 0, 0 };
-
-        // Defaults
-        internal static readonly SmiMetaData DefaultBigInt = new SmiMetaData(SqlDbType.BigInt, 8, 19, 0, SqlCompareOptions.None);     // SqlDbType.BigInt
-        internal static readonly SmiMetaData DefaultBinary = new SmiMetaData(SqlDbType.Binary, 1, 0, 0, SqlCompareOptions.None);     // SqlDbType.Binary
-        internal static readonly SmiMetaData DefaultBit = new SmiMetaData(SqlDbType.Bit, 1, 1, 0, SqlCompareOptions.None);     // SqlDbType.Bit
-        internal static readonly SmiMetaData DefaultChar_NoCollation = new SmiMetaData(SqlDbType.Char, 1, 0, 0, DefaultStringCompareOptions); // SqlDbType.Char
-        internal static readonly SmiMetaData DefaultDateTime = new SmiMetaData(SqlDbType.DateTime, 8, 23, 3, SqlCompareOptions.None);     // SqlDbType.DateTime
-        internal static readonly SmiMetaData DefaultDecimal = new SmiMetaData(SqlDbType.Decimal, 9, 18, 0, SqlCompareOptions.None);     // SqlDbType.Decimal
-        internal static readonly SmiMetaData DefaultFloat = new SmiMetaData(SqlDbType.Float, 8, 53, 0, SqlCompareOptions.None);     // SqlDbType.Float
-        internal static readonly SmiMetaData DefaultImage = new SmiMetaData(SqlDbType.Image, UnlimitedMaxLengthIndicator, 0, 0, SqlCompareOptions.None);     // SqlDbType.Image
-        internal static readonly SmiMetaData DefaultInt = new SmiMetaData(SqlDbType.Int, 4, 10, 0, SqlCompareOptions.None);     // SqlDbType.Int
-        internal static readonly SmiMetaData DefaultMoney = new SmiMetaData(SqlDbType.Money, 8, 19, 4, SqlCompareOptions.None);     // SqlDbType.Money
-        internal static readonly SmiMetaData DefaultNChar_NoCollation = new SmiMetaData(SqlDbType.NChar, 1, 0, 0, DefaultStringCompareOptions); // SqlDbType.NChar
-        internal static readonly SmiMetaData DefaultNText_NoCollation = new SmiMetaData(SqlDbType.NText, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions); // SqlDbType.NText
-        internal static readonly SmiMetaData DefaultNVarChar_NoCollation = new SmiMetaData(SqlDbType.NVarChar, MaxUnicodeCharacters, 0, 0, DefaultStringCompareOptions); // SqlDbType.NVarChar
-        internal static readonly SmiMetaData DefaultReal = new SmiMetaData(SqlDbType.Real, 4, 24, 0, SqlCompareOptions.None);     // SqlDbType.Real
-        internal static readonly SmiMetaData DefaultUniqueIdentifier = new SmiMetaData(SqlDbType.UniqueIdentifier, 16, 0, 0, SqlCompareOptions.None);     // SqlDbType.UniqueIdentifier
-        internal static readonly SmiMetaData DefaultSmallDateTime = new SmiMetaData(SqlDbType.SmallDateTime, 4, 16, 0, SqlCompareOptions.None);     // SqlDbType.SmallDateTime
-        internal static readonly SmiMetaData DefaultSmallInt = new SmiMetaData(SqlDbType.SmallInt, 2, 5, 0, SqlCompareOptions.None);     // SqlDbType.SmallInt
-        internal static readonly SmiMetaData DefaultSmallMoney = new SmiMetaData(SqlDbType.SmallMoney, 4, 10, 4, SqlCompareOptions.None);     // SqlDbType.SmallMoney
-        internal static readonly SmiMetaData DefaultText_NoCollation = new SmiMetaData(SqlDbType.Text, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions); // SqlDbType.Text
-        internal static readonly SmiMetaData DefaultTimestamp = new SmiMetaData(SqlDbType.Timestamp, 8, 0, 0, SqlCompareOptions.None);     // SqlDbType.Timestamp
-        internal static readonly SmiMetaData DefaultTinyInt = new SmiMetaData(SqlDbType.TinyInt, 1, 3, 0, SqlCompareOptions.None);     // SqlDbType.TinyInt
-        internal static readonly SmiMetaData DefaultVarBinary = new SmiMetaData(SqlDbType.VarBinary, MaxBinaryLength, 0, 0, SqlCompareOptions.None);     // SqlDbType.VarBinary
-        internal static readonly SmiMetaData DefaultVarChar_NoCollation = new SmiMetaData(SqlDbType.VarChar, MaxANSICharacters, 0, 0, DefaultStringCompareOptions); // SqlDbType.VarChar
-        internal static readonly SmiMetaData DefaultVariant = new SmiMetaData(SqlDbType.Variant, 8016, 0, 0, SqlCompareOptions.None);     // SqlDbType.Variant
-        internal static readonly SmiMetaData DefaultXml = new SmiMetaData(SqlDbType.Xml, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions); // SqlDbType.Xml
-        internal static readonly SmiMetaData DefaultUdt_NoType = new SmiMetaData(SqlDbType.Udt, 0, 0, 0, SqlCompareOptions.None);     // SqlDbType.Udt
-        internal static readonly SmiMetaData DefaultStructured = new SmiMetaData(SqlDbType.Structured, 0, 0, 0, SqlCompareOptions.None);     // SqlDbType.Structured
-        internal static readonly SmiMetaData DefaultDate = new SmiMetaData(SqlDbType.Date, 3, 10, 0, SqlCompareOptions.None);     // SqlDbType.Date
-        internal static readonly SmiMetaData DefaultTime = new SmiMetaData(SqlDbType.Time, 5, 0, 7, SqlCompareOptions.None);     // SqlDbType.Time
-        internal static readonly SmiMetaData DefaultDateTime2 = new SmiMetaData(SqlDbType.DateTime2, 8, 0, 7, SqlCompareOptions.None);     // SqlDbType.DateTime2
-        internal static readonly SmiMetaData DefaultDateTimeOffset = new SmiMetaData(SqlDbType.DateTimeOffset, 10, 0, 7, SqlCompareOptions.None);     // SqlDbType.DateTimeOffset
-        // No default for generic UDT
-
-        // character defaults hook thread-local culture to get collation
-        internal static SmiMetaData DefaultChar
-            => new SmiMetaData(
-                DefaultChar_NoCollation.SqlDbType,
-                DefaultChar_NoCollation.MaxLength,
-                DefaultChar_NoCollation.Precision,
-                DefaultChar_NoCollation.Scale,
-                CultureInfo.CurrentCulture.LCID,
-                SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth,
-                null);
-
-        internal static SmiMetaData DefaultNChar
-            => new SmiMetaData(
-                DefaultNChar_NoCollation.SqlDbType,
-                DefaultNChar_NoCollation.MaxLength,
-                DefaultNChar_NoCollation.Precision,
-                DefaultNChar_NoCollation.Scale,
-                CultureInfo.CurrentCulture.LCID,
-                SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth,
-                null);
-
-        internal static SmiMetaData DefaultNText
-            => new SmiMetaData(
-                DefaultNText_NoCollation.SqlDbType,
-                DefaultNText_NoCollation.MaxLength,
-                DefaultNText_NoCollation.Precision,
-                DefaultNText_NoCollation.Scale,
-                CultureInfo.CurrentCulture.LCID,
-                SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth,
-                null);
-
-        internal static SmiMetaData DefaultNVarChar
-            => new SmiMetaData(
-                DefaultNVarChar_NoCollation.SqlDbType,
-                DefaultNVarChar_NoCollation.MaxLength,
-                DefaultNVarChar_NoCollation.Precision,
-                DefaultNVarChar_NoCollation.Scale,
-                CultureInfo.CurrentCulture.LCID,
-                SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth,
-                null);
-
-        internal static SmiMetaData DefaultText
-            => new SmiMetaData(
-                DefaultText_NoCollation.SqlDbType,
-                DefaultText_NoCollation.MaxLength,
-                DefaultText_NoCollation.Precision,
-                DefaultText_NoCollation.Scale,
-                CultureInfo.CurrentCulture.LCID,
-                SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth,
-                null);
-
-        internal static SmiMetaData DefaultVarChar
-            => new SmiMetaData(
-                DefaultVarChar_NoCollation.SqlDbType,
-                DefaultVarChar_NoCollation.MaxLength,
-                DefaultVarChar_NoCollation.Precision,
-                DefaultVarChar_NoCollation.Scale,
-                CultureInfo.CurrentCulture.LCID,
-                SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth,
-                null);
-
-        // The one and only constructor for use by outside code.
-        //
-        //  Parameters that matter for given values of dbType (other parameters are ignored in favor of internal defaults).
-        //  Thus, if dbType parameter value is SqlDbType.Decimal, the values of precision and scale passed in are used, but
-        //  maxLength, localeId, compareOptions, etc are set to defaults for the Decimal type:
-        //      SqlDbType.BigInt:               dbType
-        //      SqlDbType.Binary:               dbType, maxLength
-        //      SqlDbType.Bit:                  dbType
-        //      SqlDbType.Char:                 dbType, maxLength, localeId, compareOptions
-        //      SqlDbType.DateTime:             dbType
-        //      SqlDbType.Decimal:              dbType, precision, scale
-        //      SqlDbType.Float:                dbType
-        //      SqlDbType.Image:                dbType
-        //      SqlDbType.Int:                  dbType
-        //      SqlDbType.Money:                dbType
-        //      SqlDbType.NChar:                dbType, maxLength, localeId, compareOptions
-        //      SqlDbType.NText:                dbType, localeId, compareOptions
-        //      SqlDbType.NVarChar:             dbType, maxLength, localeId, compareOptions
-        //      SqlDbType.Real:                 dbType
-        //      SqlDbType.UniqueIdentifier:     dbType
-        //      SqlDbType.SmallDateTime:        dbType
-        //      SqlDbType.SmallInt:             dbType
-        //      SqlDbType.SmallMoney:           dbType
-        //      SqlDbType.Text:                 dbType, localeId, compareOptions
-        //      SqlDbType.Timestamp:            dbType
-        //      SqlDbType.TinyInt:              dbType
-        //      SqlDbType.VarBinary:            dbType, maxLength
-        //      SqlDbType.VarChar:              dbType, maxLength, localeId, compareOptions
-        //      SqlDbType.Variant:              dbType
-        //      PlaceHolder for value 24
-        //      SqlDbType.Xml:                  dbType
-        //      Placeholder for value 26
-        //      Placeholder for value 27
-        //      Placeholder for value 28
-        //      SqlDbType.Udt:                  dbType, userDefinedType
-        //
-
-        // SMI V100 (aka V3) constructor.  Superceded in V200.
-        internal SmiMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                false,
-                null,
-                null)
-        {
-        }
-
-        // SMI V200 ctor.
-        internal SmiMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldTypes,
-            SmiMetaDataPropertyCollection extendedProperties)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                null,
-                isMultiValued,
-                fieldTypes,
-                extendedProperties)
-        {
-        }
-
-        // SMI V220 ctor.
-        internal SmiMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string udtAssemblyQualifiedName,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldTypes,
-            SmiMetaDataPropertyCollection extendedProperties)
-        {
-            Debug.Assert(IsSupportedDbType(dbType), "Invalid SqlDbType: " + dbType);
-
-            SetDefaultsForType(dbType);
-
-            switch (dbType)
-            {
-                case SqlDbType.BigInt:
-                case SqlDbType.Bit:
-                case SqlDbType.DateTime:
-                case SqlDbType.Float:
-                case SqlDbType.Image:
-                case SqlDbType.Int:
-                case SqlDbType.Money:
-                case SqlDbType.Real:
-                case SqlDbType.SmallDateTime:
-                case SqlDbType.SmallInt:
-                case SqlDbType.SmallMoney:
-                case SqlDbType.Timestamp:
-                case SqlDbType.TinyInt:
-                case SqlDbType.UniqueIdentifier:
-                case SqlDbType.Variant:
-                case SqlDbType.Xml:
-                case SqlDbType.Date:
-                    break;
-                case SqlDbType.Binary:
-                case SqlDbType.VarBinary:
-                    _maxLength = maxLength;
-                    break;
-                case SqlDbType.Char:
-                case SqlDbType.NChar:
-                case SqlDbType.NVarChar:
-                case SqlDbType.VarChar:
-                    // locale and compare options are not validated until they get to the server
-                    _maxLength = maxLength;
-                    _localeId = localeId;
-                    _compareOptions = compareOptions;
-                    break;
-                case SqlDbType.NText:
-                case SqlDbType.Text:
-                    _localeId = localeId;
-                    _compareOptions = compareOptions;
-                    break;
-                case SqlDbType.Decimal:
-                    Debug.Assert(MinPrecision <= precision && SqlDecimal.MaxPrecision >= precision, "Invalid precision: " + precision);
-                    Debug.Assert(MinScale <= scale && SqlDecimal.MaxScale >= scale, "Invalid scale: " + scale);
-                    Debug.Assert(scale <= precision, "Precision: " + precision + " greater than scale: " + scale);
-                    _precision = precision;
-                    _scale = scale;
-                    _maxLength = s_maxLenFromPrecision[precision - 1];
-                    break;
-                case SqlDbType.Udt:
-                    // For SqlParameter, both userDefinedType and udtAssemblyQualifiedName can be NULL,
-                    // so we are checking only maxLength if it will be used (i.e. userDefinedType is NULL)
-                    Debug.Assert((null != userDefinedType) || (0 <= maxLength || UnlimitedMaxLengthIndicator == maxLength),
-                            $"SmiMetaData.ctor: Udt name={udtAssemblyQualifiedName}, maxLength={maxLength}");
-                    // Type not validated until matched to a server.  Could be null if extended metadata supplies three-part name!
-                    _clrType = userDefinedType;
-                    if (null != userDefinedType)
-                    {
-                        _maxLength = SerializationHelperSql9.GetUdtMaxLength(userDefinedType);
-                    }
-                    else
-                    {
-                        _maxLength = maxLength;
-                    }
-                    _udtAssemblyQualifiedName = udtAssemblyQualifiedName;
-                    break;
-                case SqlDbType.Structured:
-                    if (null != fieldTypes)
-                    {
-                        _fieldMetaData = (new List<SmiExtendedMetaData>(fieldTypes)).AsReadOnly();
-                    }
-                    _isMultiValued = isMultiValued;
-                    _maxLength = _fieldMetaData.Count;
-                    break;
-                case SqlDbType.Time:
-                    Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
-                    _scale = scale;
-                    _maxLength = 5 - s_maxVarTimeLenOffsetFromScale[scale];
-                    break;
-                case SqlDbType.DateTime2:
-                    Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
-                    _scale = scale;
-                    _maxLength = 8 - s_maxVarTimeLenOffsetFromScale[scale];
-                    break;
-                case SqlDbType.DateTimeOffset:
-                    Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
-                    _scale = scale;
-                    _maxLength = 10 - s_maxVarTimeLenOffsetFromScale[scale];
-                    break;
-                default:
-                    Debug.Fail("How in the world did we get here? :" + dbType);
-                    break;
-            }
-
-            if (null != extendedProperties)
-            {
-                extendedProperties.SetReadOnly();
-                _extendedProperties = extendedProperties;
-            }
-
-            // properties and fields must meet the following conditions at this point:
-            //  1) not null
-            //  2) read only
-            //  3) same number of columns in each list (0 count acceptable for properties that are "unused")
-            Debug.Assert(null != _extendedProperties && _extendedProperties.IsReadOnly, "SmiMetaData.ctor: _extendedProperties is " + (null != _extendedProperties ? "writable" : "null"));
-            Debug.Assert(null != _fieldMetaData && _fieldMetaData.IsReadOnly, "SmiMetaData.ctor: _fieldMetaData is " + (null != _fieldMetaData ? "writable" : "null"));
-#if DEBUG
-            ((SmiDefaultFieldsProperty)_extendedProperties[SmiPropertySelector.DefaultFields]).CheckCount(_fieldMetaData.Count);
-            ((SmiOrderProperty)_extendedProperties[SmiPropertySelector.SortOrder]).CheckCount(_fieldMetaData.Count);
-            ((SmiUniqueKeyProperty)_extendedProperties[SmiPropertySelector.UniqueKey]).CheckCount(_fieldMetaData.Count);
-#endif
-        }
-
-        internal bool IsValidMaxLengthForCtorGivenType(SqlDbType dbType, long maxLength)
-        {
-            bool result = true;
-            switch (dbType)
-            {
-                case SqlDbType.BigInt:
-                case SqlDbType.Bit:
-                case SqlDbType.DateTime:
-                case SqlDbType.Float:
-                case SqlDbType.Image:
-                case SqlDbType.Int:
-                case SqlDbType.Money:
-                case SqlDbType.Real:
-                case SqlDbType.SmallDateTime:
-                case SqlDbType.SmallInt:
-                case SqlDbType.SmallMoney:
-                case SqlDbType.Timestamp:
-                case SqlDbType.TinyInt:
-                case SqlDbType.UniqueIdentifier:
-                case SqlDbType.Variant:
-                case SqlDbType.Xml:
-                case SqlDbType.NText:
-                case SqlDbType.Text:
-                case SqlDbType.Decimal:
-                case SqlDbType.Udt:
-                case SqlDbType.Structured:
-                case SqlDbType.Date:
-                case SqlDbType.Time:
-                case SqlDbType.DateTime2:
-                case SqlDbType.DateTimeOffset:
-                    break;
-                case SqlDbType.Binary:
-                    result = 0 < maxLength && MaxBinaryLength >= maxLength;
-                    break;
-                case SqlDbType.VarBinary:
-                    result = UnlimitedMaxLengthIndicator == maxLength || (0 < maxLength && MaxBinaryLength >= maxLength);
-                    break;
-                case SqlDbType.Char:
-                    result = 0 < maxLength && MaxANSICharacters >= maxLength;
-                    break;
-                case SqlDbType.NChar:
-                    result = 0 < maxLength && MaxUnicodeCharacters >= maxLength;
-                    break;
-                case SqlDbType.NVarChar:
-                    result = UnlimitedMaxLengthIndicator == maxLength || (0 < maxLength && MaxUnicodeCharacters >= maxLength);
-                    break;
-                case SqlDbType.VarChar:
-                    result = UnlimitedMaxLengthIndicator == maxLength || (0 < maxLength && MaxANSICharacters >= maxLength);
-                    break;
-                default:
-                    Debug.Fail("How in the world did we get here? :" + dbType);
-                    break;
-            }
-
-            return result;
-        }
-
-        // Sql-style compare options for character types.
-        internal SqlCompareOptions CompareOptions => _compareOptions;
-
-        // LCID for type.  0 for non-character types.
-        internal long LocaleId => _localeId;
-
-        // Units of length depend on type.
-        //  NVarChar, NChar, NText: # of Unicode characters
-        //  Everything else: # of bytes
-        internal long MaxLength => _maxLength;
-
-        internal byte Precision => _precision;
-
-        internal byte Scale => _scale;
-
-        internal SqlDbType SqlDbType => _databaseType;
-
-        // Clr Type instance for user-defined types
-        internal Type Type
-        {
-            get
-            {
-                // Fault-in UDT clr types on access if have assembly-qualified name
-                if (null == _clrType && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null)
-                {
-                    _clrType = Type.GetType(_udtAssemblyQualifiedName, true);
-                }
-                return _clrType;
-            }
-        }
-
-        // Clr Type instance for user-defined types in cases where we don't want to throw if the assembly isn't available
-        internal Type TypeWithoutThrowing
-        {
-            get
-            {
-                // Fault-in UDT clr types on access if have assembly-qualified name
-                if (null == _clrType && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null)
-                {
-                    _clrType = Type.GetType(_udtAssemblyQualifiedName, false);
-                }
-                return _clrType;
-            }
-        }
-
-        internal string TypeName
-        {
-            get
-            {
-                string result = null;
-                if (SqlDbType.Udt == _databaseType)
-                {
-                    Debug.Assert(string.Empty == s_typeNameByDatabaseType[(int)_databaseType], "unexpected udt?");
-                    result = Type.FullName;
-                }
-                else
-                {
-                    result = s_typeNameByDatabaseType[(int)_databaseType];
-                    Debug.Assert(null != result, "unknown type name?");
-                }
-                return result;
-            }
-        }
-
-        internal string AssemblyQualifiedName
-        {
-            get
-            {
-                string result = null;
-                if (SqlDbType.Udt == _databaseType)
-                {
-                    // Fault-in assembly-qualified name if type is available
-                    if (_udtAssemblyQualifiedName == null && _clrType != null)
-                    {
-                        _udtAssemblyQualifiedName = _clrType.AssemblyQualifiedName;
-                    }
-                    result = _udtAssemblyQualifiedName;
-                }
-                return result;
-            }
-        }
-
-        internal bool IsMultiValued => _isMultiValued;
-
-        // Returns read-only list of field metadata
-        internal IList<SmiExtendedMetaData> FieldMetaData => _fieldMetaData;
-
-        // Returns read-only list of extended properties
-        internal SmiMetaDataPropertyCollection ExtendedProperties => _extendedProperties;
-
-        internal static bool IsSupportedDbType(SqlDbType dbType)
-        {
-            // Hole in SqlDbTypes between Xml and Udt for non-WinFS scenarios.
-            return (SqlDbType.BigInt <= dbType && SqlDbType.Xml >= dbType) ||
-                    (SqlDbType.Udt <= dbType && SqlDbType.DateTimeOffset >= dbType);
-        }
-
-        // Only correct access point for defaults per SqlDbType.
-        internal static SmiMetaData GetDefaultForType(SqlDbType dbType)
-        {
-            Debug.Assert(IsSupportedDbType(dbType), "Unsupported SqlDbtype: " + dbType);
-
-            return s_defaultValues[(int)dbType];
-        }
-
-        // Private constructor used only to initialize default instance array elements.
-        // DO NOT EXPOSE OUTSIDE THIS CLASS!
-        private SmiMetaData(
-            SqlDbType sqlDbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            SqlCompareOptions compareOptions)
-        {
-            _databaseType = sqlDbType;
-            _maxLength = maxLength;
-            _precision = precision;
-            _scale = scale;
-            _compareOptions = compareOptions;
-
-            // defaults are the same for all types for the following attributes.
-            _localeId = 0;
-            _clrType = null;
-            _isMultiValued = false;
-            _fieldMetaData = s_emptyFieldList;
-            _extendedProperties = SmiMetaDataPropertyCollection.EmptyInstance;
-        }
-
-        // static array of default-valued metadata ordered by corresponding SqlDbType.
-        // NOTE: INDEXED BY SqlDbType ENUM!  MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType!
-        //   ONLY ACCESS THIS GLOBAL FROM GetDefaultForType!
-        private static readonly SmiMetaData[] s_defaultValues =
-            {
-                DefaultBigInt,                 // SqlDbType.BigInt
-                DefaultBinary,                 // SqlDbType.Binary
-                DefaultBit,                    // SqlDbType.Bit
-                DefaultChar_NoCollation,       // SqlDbType.Char
-                DefaultDateTime,               // SqlDbType.DateTime
-                DefaultDecimal,                // SqlDbType.Decimal
-                DefaultFloat,                  // SqlDbType.Float
-                DefaultImage,                  // SqlDbType.Image
-                DefaultInt,                    // SqlDbType.Int
-                DefaultMoney,                  // SqlDbType.Money
-                DefaultNChar_NoCollation,      // SqlDbType.NChar
-                DefaultNText_NoCollation,      // SqlDbType.NText
-                DefaultNVarChar_NoCollation,   // SqlDbType.NVarChar
-                DefaultReal,                   // SqlDbType.Real
-                DefaultUniqueIdentifier,       // SqlDbType.UniqueIdentifier
-                DefaultSmallDateTime,          // SqlDbType.SmallDateTime
-                DefaultSmallInt,               // SqlDbType.SmallInt
-                DefaultSmallMoney,             // SqlDbType.SmallMoney
-                DefaultText_NoCollation,       // SqlDbType.Text
-                DefaultTimestamp,              // SqlDbType.Timestamp
-                DefaultTinyInt,                // SqlDbType.TinyInt
-                DefaultVarBinary,              // SqlDbType.VarBinary
-                DefaultVarChar_NoCollation,    // SqlDbType.VarChar
-                DefaultVariant,                // SqlDbType.Variant
-                DefaultNVarChar_NoCollation,   // Placeholder for value 24
-                DefaultXml,                    // SqlDbType.Xml
-                DefaultNVarChar_NoCollation,   // Placeholder for value 26
-                DefaultNVarChar_NoCollation,   // Placeholder for value 27
-                DefaultNVarChar_NoCollation,   // Placeholder for value 28
-                DefaultUdt_NoType,             // Generic Udt
-                DefaultStructured,             // Generic structured type
-                DefaultDate,                   // SqlDbType.Date
-                DefaultTime,                   // SqlDbType.Time
-                DefaultDateTime2,              // SqlDbType.DateTime2
-                DefaultDateTimeOffset,         // SqlDbType.DateTimeOffset
-            };
-
-        // static array of type names ordered by corresponding SqlDbType.
-        // NOTE: INDEXED BY SqlDbType ENUM!  MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType!
-        //   ONLY ACCESS THIS GLOBAL FROM get_TypeName!
-        private static readonly string[] s_typeNameByDatabaseType =
-            {
-                "bigint",               // SqlDbType.BigInt
-                "binary",               // SqlDbType.Binary
-                "bit",                  // SqlDbType.Bit
-                "char",                 // SqlDbType.Char
-                "datetime",             // SqlDbType.DateTime
-                "decimal",              // SqlDbType.Decimal
-                "float",                // SqlDbType.Float
-                "image",                // SqlDbType.Image
-                "int",                  // SqlDbType.Int
-                "money",                // SqlDbType.Money
-                "nchar",                // SqlDbType.NChar
-                "ntext",                // SqlDbType.NText
-                "nvarchar",             // SqlDbType.NVarChar
-                "real",                 // SqlDbType.Real
-                "uniqueidentifier",     // SqlDbType.UniqueIdentifier
-                "smalldatetime",        // SqlDbType.SmallDateTime
-                "smallint",             // SqlDbType.SmallInt
-                "smallmoney",           // SqlDbType.SmallMoney
-                "text",                 // SqlDbType.Text
-                "timestamp",            // SqlDbType.Timestamp
-                "tinyint",              // SqlDbType.TinyInt
-                "varbinary",            // SqlDbType.VarBinary
-                "varchar",              // SqlDbType.VarChar
-                "sql_variant",          // SqlDbType.Variant
-                null,                   // placeholder for 24
-                "xml",                  // SqlDbType.Xml
-                null,                   // placeholder for 26
-                null,                   // placeholder for 27
-                null,                   // placeholder for 28
-                string.Empty,           // SqlDbType.Udt  -- get type name from Type.FullName instead.
-                string.Empty,           // Structured types have user-defined type names.
-                "date",                 // SqlDbType.Date
-                "time",                 // SqlDbType.Time
-                "datetime2",            // SqlDbType.DateTime2
-                "datetimeoffset",       // SqlDbType.DateTimeOffset
-            };
-
-        // Internal setter to be used by constructors only!  Modifies state!
-        private void SetDefaultsForType(SqlDbType dbType)
-        {
-            SmiMetaData smdDflt = GetDefaultForType(dbType);
-            _databaseType = dbType;
-            _maxLength = smdDflt.MaxLength;
-            _precision = smdDflt.Precision;
-            _scale = smdDflt.Scale;
-            _localeId = smdDflt.LocaleId;
-            _compareOptions = smdDflt.CompareOptions;
-            _clrType = null;
-            _isMultiValued = smdDflt._isMultiValued;
-            _fieldMetaData = smdDflt._fieldMetaData;            // This is ok due to immutability
-            _extendedProperties = smdDflt._extendedProperties;  // This is ok due to immutability
-        }
-    }
-
-    // SmiExtendedMetaData
-    //
-    //  Adds server-specific type extension information to base metadata, but still portable across a specific server.
-    //
-    internal class SmiExtendedMetaData : SmiMetaData
-    {
-        private readonly string _name;           // context-dependent identifier, i.e. parameter name for parameters, column name for columns, etc.
-
-        // three-part name for typed xml schema and for udt names
-        private readonly string _typeSpecificNamePart1;
-        private readonly string _typeSpecificNamePart2;
-        private readonly string _typeSpecificNamePart3;
-
-        internal SmiExtendedMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                false,
-                null,
-                null,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3)
-        {
-        }
-
-        // SMI V200 ctor.
-        internal SmiExtendedMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                null,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3)
-        {
-        }
-
-        // SMI V220 ctor.
-        internal SmiExtendedMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string udtAssemblyQualifiedName,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3)
-            : base(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                udtAssemblyQualifiedName,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties)
-        {
-            Debug.Assert(null == name || MaxNameLength >= name.Length, "Name is too long");
-
-            _name = name;
-            _typeSpecificNamePart1 = typeSpecificNamePart1;
-            _typeSpecificNamePart2 = typeSpecificNamePart2;
-            _typeSpecificNamePart3 = typeSpecificNamePart3;
-        }
-
-        internal string Name => _name;
-
-        internal string TypeSpecificNamePart1 => _typeSpecificNamePart1;
-
-        internal string TypeSpecificNamePart2 => _typeSpecificNamePart2;
-
-        internal string TypeSpecificNamePart3 => _typeSpecificNamePart3;
-    }
-
-    // SmiParameterMetaData
-    //
-    //  MetaData class to send parameter definitions to server.
-    //  Sealed because we don't need to derive from it yet.
-    internal sealed class SmiParameterMetaData : SmiExtendedMetaData
-    {
-        private readonly ParameterDirection _direction;
-
-        // SMI V200 ctor.
-        internal SmiParameterMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            ParameterDirection direction)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                null,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3,
-                direction)
-        {
-        }
-
-        // SMI V220 ctor.
-        internal SmiParameterMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string udtAssemblyQualifiedName,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            ParameterDirection direction)
-            : base(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                udtAssemblyQualifiedName,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3)
-        {
-            Debug.Assert(ParameterDirection.Input == direction
-                       || ParameterDirection.Output == direction
-                       || ParameterDirection.InputOutput == direction
-                       || ParameterDirection.ReturnValue == direction, "Invalid direction: " + direction);
-            _direction = direction;
-        }
-
-        internal ParameterDirection Direction => _direction;
-    }
-
-    // SmiStorageMetaData
-    //
-    //  This class represents the addition of storage-level attributes to the hierarchy (i.e. attributes from
-    //  underlying table, source variables, or whatever).
-    //
-    //  Most values use Null (either IsNullable == true or CLR null) to indicate "Not specified" state.  Selection
-    //  of which values allow "not specified" determined by backward compatibility.
-    //
-    //  Maps approximately to TDS' COLMETADATA token with TABNAME and part of COLINFO thrown in.
-    internal class SmiStorageMetaData : SmiExtendedMetaData
-    {
-        // AllowsDBNull is the only value required to be specified.
-        private readonly bool _allowsDBNull;  // could the column return nulls? equivalent to TDS's IsNullable bit
-        private readonly string _serverName;  // underlying column's server
-        private readonly string _catalogName; // underlying column's database
-        private readonly string _schemaName;  // underlying column's schema
-        private readonly string _tableName;   // underlying column's table
-        private readonly string _columnName;  // underlying column's name
-        private SqlBoolean _isKey;   // Is this one of a set of key columns that uniquely identify an underlying table?
-        private readonly bool _isIdentity;    // Is this from an identity column
-        private readonly bool _isColumnSet;   // Is this column the XML representation of a columnset?
-
-        internal SmiStorageMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            bool allowsDBNull,
-            string serverName,
-            string catalogName,
-            string schemaName,
-            string tableName,
-            string columnName,
-            SqlBoolean isKey,
-            bool isIdentity)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                false,
-                null,
-                null,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3,
-                allowsDBNull,
-                serverName,
-                catalogName,
-                schemaName,
-                tableName,
-                columnName,
-                isKey,
-                isIdentity)
-        {
-        }
-
-        // SMI V200 ctor.
-        internal SmiStorageMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            bool allowsDBNull,
-            string serverName,
-            string catalogName,
-            string schemaName,
-            string tableName,
-            string columnName,
-            SqlBoolean isKey,
-            bool isIdentity)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                null,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3,
-                allowsDBNull,
-                serverName,
-                catalogName,
-                schemaName,
-                tableName,
-                columnName,
-                isKey,
-                isIdentity,
-                false)
-        {
-        }
-
-        // SMI V220 ctor.
-        internal SmiStorageMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string udtAssemblyQualifiedName,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            bool allowsDBNull,
-            string serverName,
-            string catalogName,
-            string schemaName,
-            string tableName,
-            string columnName,
-            SqlBoolean isKey,
-            bool isIdentity,
-            bool isColumnSet)
-            : base(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                udtAssemblyQualifiedName,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3)
-        {
-            _allowsDBNull = allowsDBNull;
-            _serverName = serverName;
-            _catalogName = catalogName;
-            _schemaName = schemaName;
-            _tableName = tableName;
-            _columnName = columnName;
-            _isKey = isKey;
-            _isIdentity = isIdentity;
-            _isColumnSet = isColumnSet;
-        }
-
-        internal bool AllowsDBNull => _allowsDBNull;
-
-        internal string ServerName => _serverName;
-
-        internal string CatalogName => _catalogName;
-
-        internal string SchemaName => _schemaName;
-
-        internal string TableName => _tableName;
-
-        internal string ColumnName => _columnName;
-
-        internal SqlBoolean IsKey => _isKey;
-
-        internal bool IsIdentity => _isIdentity;
-
-        internal bool IsColumnSet => _isColumnSet;
-    }
-
-    // SmiQueryMetaData
-    //
-    //  Adds Query-specific attributes.
-    //  Sealed since we don't need to extend it for now.
-    //  Maps to full COLMETADATA + COLINFO + TABNAME tokens on TDS.
-    internal class SmiQueryMetaData : SmiStorageMetaData
-    {
-        private readonly bool _isReadOnly;
-        private SqlBoolean _isExpression;
-        private SqlBoolean _isAliased;
-        private SqlBoolean _isHidden;
-
-        internal SmiQueryMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            bool allowsDBNull,
-            string serverName,
-            string catalogName,
-            string schemaName,
-            string tableName,
-            string columnName,
-            SqlBoolean isKey,
-            bool isIdentity,
-            bool isReadOnly,
-            SqlBoolean isExpression,
-            SqlBoolean isAliased,
-            SqlBoolean isHidden)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                false,
-                null,
-                null,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3,
-                allowsDBNull,
-                serverName,
-                catalogName,
-                schemaName,
-                tableName,
-                columnName,
-                isKey,
-                isIdentity,
-                isReadOnly,
-                isExpression,
-                isAliased,
-                isHidden)
-        {
-        }
-
-        // SMI V200 ctor.
-        internal SmiQueryMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            bool allowsDBNull,
-            string serverName,
-            string catalogName,
-            string schemaName,
-            string tableName,
-            string columnName,
-            SqlBoolean isKey,
-            bool isIdentity,
-            bool isReadOnly,
-            SqlBoolean isExpression,
-            SqlBoolean isAliased,
-            SqlBoolean isHidden)
-            : this(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                null,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3,
-                allowsDBNull,
-                serverName,
-                catalogName,
-                schemaName,
-                tableName,
-                columnName,
-                isKey,
-                isIdentity,
-                false,
-                isReadOnly,
-                isExpression,
-                isAliased,
-                isHidden)
-        {
-        }
-
-        // SMI V220 ctor.
-        internal SmiQueryMetaData(
-            SqlDbType dbType,
-            long maxLength,
-            byte precision,
-            byte scale,
-            long localeId,
-            SqlCompareOptions compareOptions,
-            Type userDefinedType,
-            string udtAssemblyQualifiedName,
-            bool isMultiValued,
-            IList<SmiExtendedMetaData> fieldMetaData,
-            SmiMetaDataPropertyCollection extendedProperties,
-            string name,
-            string typeSpecificNamePart1,
-            string typeSpecificNamePart2,
-            string typeSpecificNamePart3,
-            bool allowsDBNull,
-            string serverName,
-            string catalogName,
-            string schemaName,
-            string tableName,
-            string columnName,
-            SqlBoolean isKey,
-            bool isIdentity,
-            bool isColumnSet,
-            bool isReadOnly,
-            SqlBoolean isExpression,
-            SqlBoolean isAliased,
-            SqlBoolean isHidden)
-            : base(
-                dbType,
-                maxLength,
-                precision,
-                scale,
-                localeId,
-                compareOptions,
-                userDefinedType,
-                udtAssemblyQualifiedName,
-                isMultiValued,
-                fieldMetaData,
-                extendedProperties,
-                name,
-                typeSpecificNamePart1,
-                typeSpecificNamePart2,
-                typeSpecificNamePart3,
-                allowsDBNull,
-                serverName,
-                catalogName,
-                schemaName,
-                tableName,
-                columnName,
-                isKey,
-                isIdentity,
-                isColumnSet)
-        {
-            _isReadOnly = isReadOnly;
-            _isExpression = isExpression;
-            _isAliased = isAliased;
-            _isHidden = isHidden;
-        }
-
-        internal bool IsReadOnly => _isReadOnly;
-
-        internal SqlBoolean IsExpression => _isExpression;
-
-        internal SqlBoolean IsAliased => _isAliased;
-
-        internal SqlBoolean IsHidden => _isHidden;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiMetaDataProperty.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiMetaDataProperty.cs
deleted file mode 100644 (file)
index 6c778ba..0000000
+++ /dev/null
@@ -1,229 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.Globalization;
-
-namespace Microsoft.SqlServer.Server
-{
-    // SmiMetaDataProperty defines an extended, optional property to be used on the SmiMetaData class
-    //  This approach to adding properties is added combat the growing number of sparsely-used properties
-    //  that are specially handled on the base classes
-
-    internal enum SmiPropertySelector
-    {
-        DefaultFields = 0x0,
-        SortOrder = 0x1,
-        UniqueKey = 0x2,
-    }
-
-    // Simple collection for properties.  Could extend to IDictionary support if needed in future.
-    internal class SmiMetaDataPropertyCollection
-    {
-        private const int SelectorCount = 3;  // number of elements in SmiPropertySelector
-
-        private readonly SmiMetaDataProperty[] _properties;
-        private bool _isReadOnly;
-
-        // Singleton empty instances to ensure each property is always non-null
-        private static readonly SmiDefaultFieldsProperty s_emptyDefaultFields = new SmiDefaultFieldsProperty(new List<bool>());
-        private static readonly SmiOrderProperty s_emptySortOrder = new SmiOrderProperty(new List<SmiOrderProperty.SmiColumnOrder>());
-        private static readonly SmiUniqueKeyProperty s_emptyUniqueKey = new SmiUniqueKeyProperty(new List<bool>());
-
-        internal static readonly SmiMetaDataPropertyCollection EmptyInstance = CreateEmptyInstance();
-
-        private static SmiMetaDataPropertyCollection CreateEmptyInstance()
-        {
-            var emptyInstance = new SmiMetaDataPropertyCollection();
-            emptyInstance.SetReadOnly();
-            return emptyInstance;
-        }
-
-        internal SmiMetaDataPropertyCollection()
-        {
-            _properties = new SmiMetaDataProperty[SelectorCount];
-            _isReadOnly = false;
-            _properties[(int)SmiPropertySelector.DefaultFields] = s_emptyDefaultFields;
-            _properties[(int)SmiPropertySelector.SortOrder] = s_emptySortOrder;
-            _properties[(int)SmiPropertySelector.UniqueKey] = s_emptyUniqueKey;
-        }
-
-        internal SmiMetaDataProperty this[SmiPropertySelector key]
-        {
-            get
-            {
-                return _properties[(int)key];
-            }
-            set
-            {
-                if (null == value)
-                {
-                    throw ADP.InternalError(ADP.InternalErrorCode.InvalidSmiCall);
-                }
-                EnsureWritable();
-                _properties[(int)key] = value;
-            }
-        }
-
-        internal bool IsReadOnly
-        {
-            get
-            {
-                return _isReadOnly;
-            }
-        }
-
-
-        // Allow switching to read only, but not back.
-        internal void SetReadOnly()
-        {
-            _isReadOnly = true;
-        }
-
-        private void EnsureWritable()
-        {
-            if (IsReadOnly)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-        }
-    }
-
-    // Base class for properties
-    internal abstract class SmiMetaDataProperty
-    {
-    }
-
-    // Property defining a list of column ordinals that define a unique key
-    internal class SmiUniqueKeyProperty : SmiMetaDataProperty
-    {
-        private readonly IList<bool> _columns;
-
-        internal SmiUniqueKeyProperty(IList<bool> columnIsKey)
-        {
-            _columns = new System.Collections.ObjectModel.ReadOnlyCollection<bool>(columnIsKey);
-        }
-
-        // indexed by column ordinal indicating for each column whether it is key or not
-        internal bool this[int ordinal]
-        {
-            get
-            {
-                if (_columns.Count <= ordinal)
-                {
-                    return false;
-                }
-                else
-                {
-                    return _columns[ordinal];
-                }
-            }
-        }
-
-        [Conditional("DEBUG")]
-        internal void CheckCount(int countToMatch)
-        {
-            Debug.Assert(0 == _columns.Count || countToMatch == _columns.Count,
-                    "SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _columns.Count +
-                    ") not equal to checked size (" + countToMatch + ")");
-        }
-    }
-
-    // Property defining a sort order for a set of columns (by ordinal and ASC/DESC).
-    internal class SmiOrderProperty : SmiMetaDataProperty
-    {
-        internal struct SmiColumnOrder
-        {
-            internal int SortOrdinal;
-            internal SortOrder Order;
-        }
-
-        private readonly IList<SmiColumnOrder> _columns;
-
-        internal SmiOrderProperty(IList<SmiColumnOrder> columnOrders)
-        {
-            _columns = new System.Collections.ObjectModel.ReadOnlyCollection<SmiColumnOrder>(columnOrders);
-        }
-
-        // Readonly list of the columnorder instances making up the sort order
-        //  order in list indicates precedence
-        internal SmiColumnOrder this[int ordinal]
-        {
-            get
-            {
-                if (_columns.Count <= ordinal)
-                {
-                    SmiColumnOrder order = default;
-                    order.Order = SortOrder.Unspecified;
-                    order.SortOrdinal = -1;
-                    return order;
-                }
-                else
-                {
-                    return _columns[ordinal];
-                }
-            }
-        }
-
-
-        [Conditional("DEBUG")]
-        internal void CheckCount(int countToMatch)
-        {
-            Debug.Assert(0 == _columns.Count || countToMatch == _columns.Count,
-                    "SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _columns.Count +
-                    ") not equal to checked size (" + countToMatch + ")");
-        }
-    }
-
-    // property defining inheritance relationship(s)
-    internal class SmiDefaultFieldsProperty : SmiMetaDataProperty
-    {
-        #region private fields
-
-        private readonly IList<bool> _defaults;
-
-        #endregion
-
-        #region internal interface
-
-        internal SmiDefaultFieldsProperty(IList<bool> defaultFields)
-        {
-            _defaults = new System.Collections.ObjectModel.ReadOnlyCollection<bool>(defaultFields);
-        }
-
-        internal bool this[int ordinal]
-        {
-            get
-            {
-                if (_defaults.Count <= ordinal)
-                {
-                    return false;
-                }
-                else
-                {
-                    return _defaults[ordinal];
-                }
-            }
-        }
-
-        [Conditional("DEBUG")]
-        internal void CheckCount(int countToMatch)
-        {
-            Debug.Assert(0 == _defaults.Count || countToMatch == _defaults.Count,
-                    "SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _defaults.Count +
-                    ") not equal to checked size (" + countToMatch + ")");
-        }
-
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiRecordBuffer.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiRecordBuffer.cs
deleted file mode 100644 (file)
index 8f9381f..0000000
+++ /dev/null
@@ -1,864 +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.Data;
-using System.Data.SqlTypes;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Class for implementing a record object that could take advantage of the
-    // environment available to a particular protocol level (such as storing data
-    // in native structures for in-proc data access).  Includes methods to send
-    // the record to a context pipe (useful for in-proc scenarios).
-    internal abstract class SmiRecordBuffer : SmiTypedGetterSetter, ITypedGettersV3, ITypedSettersV3, ITypedGetters, ITypedSetters, IDisposable
-    {
-        #region SMI active methods as of V200
-
-
-        #region Supported access method types (Get] vs. Set)
-
-        // SmiRecordBuffer defaults both CanGet and CanSet to true to support
-        //  already-shipped SMIV3 record buffer classes.  Sub-classes are free to override.
-        internal override bool CanGet
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        internal override bool CanSet
-        {
-            get
-            {
-                return true;
-            }
-        }
-        #endregion
-
-
-
-        #region Value getters
-
-        //  SmiRecordBuffer subclasses that expose CanGet == true must implement all Getters from SmiTypedGetterSetter
-        //  SmiRecordBuffer itself does not need to implement these, since it inherits the default implementation from
-        //      SmiTypedGetterSetter
-
-        #endregion
-
-        #region Value setters
-
-        // SmiRecordBuffer subclasses that expose CanSet == true must implement all Setters from SmiTypedGetterSetter
-        //  SmiRecordBuffer itself does not need to implement these, since it inherits the default implementation from
-        //      SmiTypedGetterSetter
-
-        #endregion
-
-        #endregion
-
-        #region OBSOLETE STUFF than never shipped without obsolete attribute
-
-        //
-        //  IDisposable
-        //
-        public virtual void Dispose()
-        {
-            // ******** OBSOLETING from SMI -- use Close instead
-            //  Intended to be removed (along with inheriting IDisposable) prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        //
-        //  ITypedGetters methods
-        //
-        public virtual bool IsDBNull(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlDbType GetVariantType(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual bool GetBoolean(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual byte GetByte(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual char GetChar(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual short GetInt16(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual int GetInt32(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual long GetInt64(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual float GetFloat(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual double GetDouble(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual string GetString(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual decimal GetDecimal(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual DateTime GetDateTime(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual Guid GetGuid(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlBoolean GetSqlBoolean(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlByte GetSqlByte(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlInt16 GetSqlInt16(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlInt32 GetSqlInt32(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlInt64 GetSqlInt64(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlSingle GetSqlSingle(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlDouble GetSqlDouble(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlMoney GetSqlMoney(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlDateTime GetSqlDateTime(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlDecimal GetSqlDecimal(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlString GetSqlString(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlBinary GetSqlBinary(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlGuid GetSqlGuid(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlChars GetSqlChars(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlBytes GetSqlBytes(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlXml GetSqlXml(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlXml GetSqlXmlRef(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlBytes GetSqlBytesRef(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual SqlChars GetSqlCharsRef(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use corresponding ITypedGettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        //
-        //  ITypedSetters methods
-        //
-        public virtual void SetDBNull(int ordinal)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetBoolean(int ordinal, bool value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetByte(int ordinal, byte value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetChar(int ordinal, char value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetInt16(int ordinal, short value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetInt32(int ordinal, int value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetInt64(int ordinal, long value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetFloat(int ordinal, float value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetDouble(int ordinal, double value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetString(int ordinal, string value)
-        {
-            // Implemented as empty virtual method to allow transport to remove it's implementation
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V2 and dropped support for V1.
-            //  2) Server didn't implement V1 on some interface and negotiated V1.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetString(int ordinal, string value, int offset)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetDecimal(int ordinal, decimal value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetDateTime(int ordinal, DateTime value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetGuid(int ordinal, Guid value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlBoolean(int ordinal, SqlBoolean value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlByte(int ordinal, SqlByte value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlInt16(int ordinal, SqlInt16 value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlInt32(int ordinal, SqlInt32 value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlInt64(int ordinal, SqlInt64 value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlSingle(int ordinal, SqlSingle value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlDouble(int ordinal, SqlDouble value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlMoney(int ordinal, SqlMoney value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlDateTime(int ordinal, SqlDateTime value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlDecimal(int ordinal, SqlDecimal value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlString(int ordinal, SqlString value)
-        {
-            // Implemented as empty virtual method to allow transport to remove it's implementation
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V2 and dropped support for V1.
-            //  2) Server didn't implement V1 on some interface and negotiated V1.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlString(int ordinal, SqlString value, int offset)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlBinary(int ordinal, SqlBinary value)
-        {
-            // Implemented as empty virtual method to allow transport to remove it's implementation
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V2 and dropped support for V1.
-            //  2) Server didn't implement V1 on some interface and negotiated V1.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlBinary(int ordinal, SqlBinary value, int offset)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlGuid(int ordinal, SqlGuid value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlChars(int ordinal, SqlChars value)
-        {
-            // Implemented as empty virtual method to allow transport to remove it's implementation
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V2 and dropped support for V1.
-            //  2) Server didn't implement V1 on some interface and negotiated V1.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlChars(int ordinal, SqlChars value, int offset)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlBytes(int ordinal, SqlBytes value)
-        {
-            // Implemented as empty virtual method to allow transport to remove it's implementation
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V2 and dropped support for V1.
-            //  2) Server didn't implement V1 on some interface and negotiated V1.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlBytes(int ordinal, SqlBytes value, int offset)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        public virtual void SetSqlXml(int ordinal, SqlXml value)
-        {
-            // ******** OBSOLETING from SMI -- use ITypedSettersV3 method instead
-            //  Intended to be removed prior to RTM.
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiSettersStream.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiSettersStream.cs
deleted file mode 100644 (file)
index dee4e3e..0000000
+++ /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.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.IO;
-
-namespace Microsoft.SqlServer.Server
-{
-    internal class SmiSettersStream : Stream
-    {
-        private readonly SmiEventSink_Default _sink;
-        private readonly ITypedSettersV3 _setters;
-        private readonly int _ordinal;
-        private long _lengthWritten;
-        private readonly SmiMetaData _metaData;
-
-        internal SmiSettersStream(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData)
-        {
-            Debug.Assert(null != sink);
-            Debug.Assert(null != setters);
-            Debug.Assert(0 <= ordinal);
-            Debug.Assert(null != metaData);
-
-            _sink = sink;
-            _setters = setters;
-            _ordinal = ordinal;
-            _lengthWritten = 0;
-            _metaData = metaData;
-        }
-
-        public override bool CanRead
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        // If CanSeek is false, Position, Seek, Length, and SetLength should throw.
-        public override bool CanSeek
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public override bool CanWrite
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        public override long Length
-        {
-            get
-            {
-                return _lengthWritten;
-            }
-        }
-
-        public override long Position
-        {
-            get
-            {
-                return _lengthWritten;
-            }
-            set
-            {
-                throw SQL.StreamSeekNotSupported();
-            }
-        }
-
-        public override void Flush()
-        {
-            _lengthWritten = ValueUtilsSmi.SetBytesLength(_sink, _setters, _ordinal, _metaData, _lengthWritten);
-        }
-
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            throw SQL.StreamSeekNotSupported();
-        }
-
-        public override void SetLength(long value)
-        {
-            if (value < 0)
-            {
-                throw ADP.ArgumentOutOfRange(nameof(value));
-            }
-            ValueUtilsSmi.SetBytesLength(_sink, _setters, _ordinal, _metaData, value);
-        }
-
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            throw SQL.StreamReadNotSupported();
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            _lengthWritten += ValueUtilsSmi.SetBytes(_sink, _setters, _ordinal, _metaData, _lengthWritten, buffer, offset, count);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiTypedGetterSetter.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiTypedGetterSetter.cs
deleted file mode 100644 (file)
index cf4e150..0000000
+++ /dev/null
@@ -1,565 +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.Data;
-using System.Data.SqlTypes;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Central interface for getting/setting data values from/to a set of values indexed by ordinal
-    //  (record, row, array, etc)
-    //  Which methods are allowed to be called depends on SmiMetaData type of data offset.
-    internal abstract class SmiTypedGetterSetter : ITypedGettersV3, ITypedSettersV3
-    {
-        #region Read/Write
-        // Are calls to Get methods allowed?
-        internal abstract bool CanGet
-        {
-            get;
-        }
-
-        // Are calls to Set methods allowed?
-        internal abstract bool CanSet
-        {
-            get;
-        }
-        #endregion
-
-        #region Getters
-        // Null test
-        //      valid for all types
-        public virtual bool IsDBNull(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // Check what type current sql_variant value is
-        //      valid for SqlDbType.Variant
-        public virtual SmiMetaData GetVariantType(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        //  valid for SqlDbType.Bit
-        public virtual bool GetBoolean(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        //  valid for SqlDbType.TinyInt
-        public virtual byte GetByte(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml, Char, VarChar, Text, NChar, NVarChar, NText
-        //  (Character type support needed for ExecuteXmlReader handling)
-        public virtual long GetBytesLength(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-        public virtual int GetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        public virtual long GetCharsLength(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-        public virtual int GetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-        public virtual string GetString(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.SmallInt
-        public virtual short GetInt16(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Int
-        public virtual int GetInt32(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        public virtual long GetInt64(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Real
-        public virtual float GetSingle(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Float
-        public virtual double GetDouble(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        public virtual SqlDecimal GetSqlDecimal(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for DateTime, SmallDateTime, Date, and DateTime2
-        public virtual DateTime GetDateTime(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for UniqueIdentifier
-        public virtual Guid GetGuid(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Time
-        public virtual TimeSpan GetTimeSpan(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for DateTimeOffset
-        public virtual DateTimeOffset GetDateTimeOffset(SmiEventSink sink, int ordinal)
-        {
-            if (!CanGet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for structured types
-        //  This method called for both get and set.
-        internal virtual SmiTypedGetterSetter GetTypedGetterSetter(SmiEventSink sink, int ordinal)
-        {
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        #endregion
-
-        #region Setters
-
-        // Set value to null
-        //  valid for all types
-        public virtual void SetDBNull(SmiEventSink sink, int ordinal)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        //  valid for SqlDbType.Bit
-        public virtual void SetBoolean(SmiEventSink sink, int ordinal, bool value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        //  valid for SqlDbType.TinyInt
-        public virtual void SetByte(SmiEventSink sink, int ordinal, byte value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // Semantics for SetBytes are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
-        //      (VarBinary assumed for variants)
-        public virtual int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-        public virtual void SetBytesLength(SmiEventSink sink, int ordinal, long length)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // Semantics for SetChars are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        //      (NVarChar and global clr collation assumed for variants)
-        public virtual int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-        public virtual void SetCharsLength(SmiEventSink sink, int ordinal, long length)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        public virtual void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.SmallInt
-        public virtual void SetInt16(SmiEventSink sink, int ordinal, short value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Int
-        public virtual void SetInt32(SmiEventSink sink, int ordinal, int value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        public virtual void SetInt64(SmiEventSink sink, int ordinal, long value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Real
-        public virtual void SetSingle(SmiEventSink sink, int ordinal, float value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Float
-        public virtual void SetDouble(SmiEventSink sink, int ordinal, double value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        public virtual void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for DateTime, SmallDateTime, Date, and DateTime2
-        public virtual void SetDateTime(SmiEventSink sink, int ordinal, DateTime value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for UniqueIdentifier
-        public virtual void SetGuid(SmiEventSink sink, int ordinal, Guid value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for SqlDbType.Time
-        public virtual void SetTimeSpan(SmiEventSink sink, int ordinal, TimeSpan value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        // valid for DateTimeOffset
-        public virtual void SetDateTimeOffset(SmiEventSink sink, int ordinal, DateTimeOffset value)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        public virtual void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData)
-        {
-            // ******** OBSOLETING from SMI -- this should have been removed from ITypedSettersV3
-            //  Intended to be removed prior to RTM.  Sub-classes need not implement
-
-            // Implement body with throw because there are only a couple of ways to get to this code:
-            //  1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
-            //  2) Server didn't implement V2- on some interface and negotiated V2-.
-            throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-        }
-
-        // valid for multi-valued types only
-        internal virtual void NewElement(SmiEventSink sink)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-
-        internal virtual void EndElements(SmiEventSink sink)
-        {
-            if (!CanSet)
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
-            }
-            else
-            {
-                throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
-            }
-        }
-        #endregion
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiXetterAccessMap.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiXetterAccessMap.cs
deleted file mode 100644 (file)
index 3bb1e27..0000000
+++ /dev/null
@@ -1,110 +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;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Formal encoding of SMI's metadata-to-ITypedSetter/-from-ITypedGetter validity rules
-    internal class SmiXetterAccessMap
-    {
-        // A couple of private constants to make the getter/setter access tables more readable
-        private const bool X = true;
-        private const bool _ = false;
-
-
-        private static readonly bool[,] s_isSetterAccessValid = {
-            // Setters as columns (abbreviated from XetterTypeCode names)
-            // SqlDbTypes as rows
-            //      Current difference between setters and getters is that character setters do
-            //      not need to support SetBytes
-            //   bool, byte, bytes, chars, strng, int16, int32, int64, singl, doubl, sqldec, date,  guid, varmd, Xetr, time, dtost
-            /*BigInt*/
-            { _,  _,  _,  _,   _,   _,  _,  X,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Binary*/
-            { _,  _,  X,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Bit*/
-            { X,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Char*/
-            { _,  _,  _,  X,   X,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*DTime*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  X,   _,  _,  _,  _,  _, },
-            /*Decimal*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  X,  _,   _,  _,  _,  _,  _, },
-            /*Float*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  X,  _,  _,   _,  _,  _,  _,  _, },
-            /*Image*/
-            { _,  _,  X,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Int*/
-            { _,  _,  _,  _,   _,   _,  X,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Money*/
-            { _,  _,  _,  _,   _,   _,  _,  X,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*NChar*/
-            { _,  _,  _,  X,   X,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*NText*/
-            { _,  _,  _,  X,   X,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*NVarChar*/
-            { _,  _,  _,  X,   X,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Real*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  X,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*UniqueId*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   X,  _,  _,  _,  _, },
-            /*SmDTime*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  X,   _,  _,  _,  _,  _, },
-            /*SmInt*/
-            { _,  _,  _,  _,   _,   X,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*SmMoney*/
-            { _,  _,  _,  _,   _,   _,  _,  X,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Text*/
-            { _,  _,  _,  X,   X,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Tstamp*/
-            { _,  _,  X,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*TinyInt*/
-            { _,  X,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*VarBin*/
-            { _,  _,  X,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*VarChar*/
-            { _,  _,  _,  X,   X,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Variant*/
-            { X,  X,  X,  X,   X,   X,  X,  X,  X,  X,  X,  X,   X,  X,  _,  X,  X, },
-            /* 24 */
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Xml*/
-            { _,  _,  X,  _,   X,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /* 26 */
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /* 27 */
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /* 28 */
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Udt*/
-            { _,  _,  X,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  _, },
-            /*Struct*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  X,  _,  _, },
-            /*Date*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  X,   _,  _,  _,  _,  _, },
-            /*Time*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  X,  _, },
-            /*DTime2*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  X,   _,  _,  _,  _,  _, },
-            /*DTOffset*/
-            { _,  _,  _,  _,   _,   _,  _,  _,  _,  _,  _,  _,   _,  _,  _,  _,  X, },
-        };
-
-
-        internal static bool IsSetterAccessValid(SmiMetaData metaData, SmiXetterTypeCode xetterType)
-        {
-            // Make sure no-one adds a new xetter type without updating this file!
-            Debug.Assert(SmiXetterTypeCode.XetBoolean <= xetterType && SmiXetterTypeCode.XetDateTimeOffset >= xetterType &&
-                    SmiXetterTypeCode.GetVariantMetaData != xetterType);
-
-            return s_isSetterAccessValid[(int)metaData.SqlDbType, (int)xetterType];
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiXetterTypeCode.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SmiXetterTypeCode.cs
deleted file mode 100644 (file)
index 93663d0..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Types should match Getter/Setter names
-    internal enum SmiXetterTypeCode
-    {
-        XetBoolean,
-        XetByte,
-        XetBytes,
-        XetChars,
-        XetString,
-        XetInt16,
-        XetInt32,
-        XetInt64,
-        XetSingle,
-        XetDouble,
-        XetSqlDecimal,
-        XetDateTime,
-        XetGuid,
-        GetVariantMetaData,     // no set call, just get
-        GetXet,
-        XetTime,                // XetTime mistakenly named, does not match getter/setter method name
-        XetTimeSpan = XetTime,  // prefer using XetTimeSpan instead of XetTime.  Both mean the same thing for now.
-        XetDateTimeOffset,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlDataRecord.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlDataRecord.cs
deleted file mode 100644 (file)
index 96c57e4..0000000
+++ /dev/null
@@ -1,737 +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.Data;
-using System.Data.Common;
-using System.Data.ProviderBase;
-using System.Data.SqlTypes;
-using System.Data.SqlClient;
-using System.Diagnostics;
-
-namespace Microsoft.SqlServer.Server
-{
-    public class SqlDataRecord : IDataRecord
-    {
-        private readonly SmiRecordBuffer _recordBuffer;
-        private readonly SmiExtendedMetaData[] _columnSmiMetaData;
-        private readonly SmiEventSink_Default _eventSink;
-        private readonly SqlMetaData[] _columnMetaData;
-        private FieldNameLookup _fieldNameLookup;
-        private readonly bool _usesStringStorageForXml;
-
-        private static readonly SmiMetaData s_maxNVarCharForXml = new SmiMetaData(SqlDbType.NVarChar, SmiMetaData.UnlimitedMaxLengthIndicator,
-                                        SmiMetaData.DefaultNVarChar_NoCollation.Precision,
-                                        SmiMetaData.DefaultNVarChar_NoCollation.Scale,
-                                        SmiMetaData.DefaultNVarChar.LocaleId,
-                                        SmiMetaData.DefaultNVarChar.CompareOptions,
-                                        null);
-
-        public virtual int FieldCount
-        {
-            get
-            {
-                EnsureSubclassOverride();
-                return _columnMetaData.Length;
-            }
-        }
-
-        public virtual string GetName(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return GetSqlMetaData(ordinal).Name;
-        }
-
-        public virtual string GetDataTypeName(int ordinal)
-        {
-            EnsureSubclassOverride();
-            SqlMetaData metaData = GetSqlMetaData(ordinal);
-            if (SqlDbType.Udt == metaData.SqlDbType)
-            {
-                return metaData.UdtTypeName;
-            }
-            else
-            {
-                return MetaType.GetMetaTypeFromSqlDbType(metaData.SqlDbType, false).TypeName;
-            }
-        }
-
-        public virtual Type GetFieldType(int ordinal)
-        {
-            EnsureSubclassOverride();
-            {
-                SqlMetaData md = GetSqlMetaData(ordinal);
-                return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).ClassType;
-            }
-        }
-
-        public virtual object GetValue(int ordinal)
-        {
-            EnsureSubclassOverride();
-            SmiMetaData metaData = GetSmiMetaData(ordinal);
-
-            return ValueUtilsSmi.GetValue200(
-                            _eventSink,
-                            _recordBuffer,
-                            ordinal,
-                            metaData
-                                );
-        }
-
-        public virtual int GetValues(object[] values)
-        {
-            EnsureSubclassOverride();
-            if (null == values)
-            {
-                throw ADP.ArgumentNull(nameof(values));
-            }
-
-            int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount;
-            for (int i = 0; i < copyLength; i++)
-            {
-                values[i] = GetValue(i);
-            }
-
-            return copyLength;
-        }
-
-        public virtual int GetOrdinal(string name)
-        {
-            EnsureSubclassOverride();
-            if (null == _fieldNameLookup)
-            {
-                string[] names = new string[FieldCount];
-                for (int i = 0; i < names.Length; i++)
-                {
-                    names[i] = GetSqlMetaData(i).Name;
-                }
-
-                _fieldNameLookup = new FieldNameLookup(names, -1);
-            }
-
-            return _fieldNameLookup.GetOrdinal(name);
-        }
-
-        public virtual object this[int ordinal]
-        {
-            get
-            {
-                EnsureSubclassOverride();
-                return GetValue(ordinal);
-            }
-        }
-
-        public virtual object this[string name]
-        {
-            get
-            {
-                EnsureSubclassOverride();
-                return GetValue(GetOrdinal(name));
-            }
-        }
-
-        public virtual bool GetBoolean(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual byte GetByte(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length, true);
-        }
-
-        public virtual char GetChar(int ordinal)
-        {
-            EnsureSubclassOverride();
-            throw ADP.NotSupported();
-        }
-
-        public virtual long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length);
-        }
-
-        public virtual Guid GetGuid(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual short GetInt16(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual int GetInt32(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual long GetInt64(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual float GetFloat(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual double GetDouble(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual string GetString(int ordinal)
-        {
-            EnsureSubclassOverride();
-            SmiMetaData colMeta = GetSmiMetaData(ordinal);
-            if (_usesStringStorageForXml && SqlDbType.Xml == colMeta.SqlDbType)
-            {
-                return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, s_maxNVarCharForXml);
-            }
-            else
-            {
-                return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-            }
-        }
-
-        public virtual decimal GetDecimal(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual DateTime GetDateTime(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual DateTimeOffset GetDateTimeOffset(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual TimeSpan GetTimeSpan(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-
-        public virtual bool IsDBNull(int ordinal)
-        {
-            EnsureSubclassOverride();
-            ThrowIfInvalidOrdinal(ordinal);
-            return ValueUtilsSmi.IsDBNull(_eventSink, _recordBuffer, ordinal);
-        }
-
-        //
-        //  ISqlRecord implementation
-        //
-        public virtual SqlMetaData GetSqlMetaData(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return _columnMetaData[ordinal];
-        }
-
-        public virtual Type GetSqlFieldType(int ordinal)
-        {
-            EnsureSubclassOverride();
-            SqlMetaData md = GetSqlMetaData(ordinal);
-            return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).SqlType;
-        }
-
-        public virtual object GetSqlValue(int ordinal)
-        {
-            EnsureSubclassOverride();
-            SmiMetaData metaData = GetSmiMetaData(ordinal);
-            return ValueUtilsSmi.GetSqlValue200(_eventSink, _recordBuffer, ordinal, metaData);
-        }
-
-        public virtual int GetSqlValues(object[] values)
-        {
-            EnsureSubclassOverride();
-            if (null == values)
-            {
-                throw ADP.ArgumentNull(nameof(values));
-            }
-
-
-            int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount;
-            for (int i = 0; i < copyLength; i++)
-            {
-                values[i] = GetSqlValue(i);
-            }
-
-            return copyLength;
-        }
-
-        public virtual SqlBinary GetSqlBinary(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlBytes GetSqlBytes(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlXml GetSqlXml(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlBoolean GetSqlBoolean(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlByte GetSqlByte(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlChars GetSqlChars(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlInt16 GetSqlInt16(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlInt32 GetSqlInt32(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlInt64 GetSqlInt64(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlSingle GetSqlSingle(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlDouble GetSqlDouble(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlMoney GetSqlMoney(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlDateTime GetSqlDateTime(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlDecimal GetSqlDecimal(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlString GetSqlString(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        public virtual SqlGuid GetSqlGuid(int ordinal)
-        {
-            EnsureSubclassOverride();
-            return ValueUtilsSmi.GetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal));
-        }
-
-        //
-        // ISqlUpdateableRecord Implementation
-        //
-        public virtual int SetValues(params object[] values)
-        {
-            EnsureSubclassOverride();
-            if (null == values)
-            {
-                throw ADP.ArgumentNull(nameof(values));
-            }
-
-            // Allow values array longer than FieldCount, just ignore the extra cells.
-            int copyLength = (values.Length > FieldCount) ? FieldCount : values.Length;
-
-            ExtendedClrTypeCode[] typeCodes = new ExtendedClrTypeCode[copyLength];
-
-            // Verify all data values as acceptable before changing current state.
-            for (int i = 0; i < copyLength; i++)
-            {
-                SqlMetaData metaData = GetSqlMetaData(i);
-                typeCodes[i] = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(
-                    metaData.SqlDbType, false /* isMultiValued */, values[i], metaData.Type);
-                if (ExtendedClrTypeCode.Invalid == typeCodes[i])
-                {
-                    throw ADP.InvalidCast();
-                }
-            }
-
-            // Now move the data (it'll only throw if someone plays with the values array between
-            //      the validation loop and here, or if an invalid UDT was sent).
-            for (int i = 0; i < copyLength; i++)
-            {
-                ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, i, GetSmiMetaData(i), values[i], typeCodes[i], 0, 0, null);
-            }
-
-            return copyLength;
-        }
-
-        public virtual void SetValue(int ordinal, object value)
-        {
-            EnsureSubclassOverride();
-            SqlMetaData metaData = GetSqlMetaData(ordinal);
-            ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(
-                        metaData.SqlDbType, false /* isMultiValued */, value, metaData.Type);
-            if (ExtendedClrTypeCode.Invalid == typeCode)
-            {
-                throw ADP.InvalidCast();
-            }
-
-            ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value, typeCode, 0, 0, null);
-        }
-
-        public virtual void SetBoolean(int ordinal, bool value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetByte(int ordinal, byte value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length);
-        }
-
-        public virtual void SetChar(int ordinal, char value)
-        {
-            EnsureSubclassOverride();
-            throw ADP.NotSupported();
-        }
-
-        public virtual void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length);
-        }
-
-        public virtual void SetInt16(int ordinal, short value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetInt32(int ordinal, int value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetInt64(int ordinal, long value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetFloat(int ordinal, float value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetDouble(int ordinal, double value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetString(int ordinal, string value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetDecimal(int ordinal, decimal value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetDateTime(int ordinal, DateTime value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetTimeSpan(int ordinal, TimeSpan value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetDateTimeOffset(int ordinal, DateTimeOffset value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetDBNull(int ordinal)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetDBNull(_eventSink, _recordBuffer, ordinal, true);
-        }
-
-        public virtual void SetGuid(int ordinal, Guid value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlBoolean(int ordinal, SqlBoolean value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlByte(int ordinal, SqlByte value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlInt16(int ordinal, SqlInt16 value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlInt32(int ordinal, SqlInt32 value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlInt64(int ordinal, SqlInt64 value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlSingle(int ordinal, SqlSingle value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlDouble(int ordinal, SqlDouble value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlMoney(int ordinal, SqlMoney value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlDateTime(int ordinal, SqlDateTime value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlXml(int ordinal, SqlXml value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlDecimal(int ordinal, SqlDecimal value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlString(int ordinal, SqlString value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlBinary(int ordinal, SqlBinary value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlGuid(int ordinal, SqlGuid value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlChars(int ordinal, SqlChars value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-        public virtual void SetSqlBytes(int ordinal, SqlBytes value)
-        {
-            EnsureSubclassOverride();
-            ValueUtilsSmi.SetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
-        }
-
-
-        //
-        //  SqlDataRecord public API
-        //
-
-        public SqlDataRecord(params SqlMetaData[] metaData)
-        {
-            // Initial consistency check
-            if (null == metaData)
-            {
-                throw ADP.ArgumentNull(nameof(metaData));
-            }
-
-            _columnMetaData = new SqlMetaData[metaData.Length];
-            _columnSmiMetaData = new SmiExtendedMetaData[metaData.Length];
-            for (int i = 0; i < _columnSmiMetaData.Length; i++)
-            {
-                if (null == metaData[i])
-                {
-                    throw ADP.ArgumentNull($"{nameof(metaData)}[{i}]");
-                }
-                _columnMetaData[i] = metaData[i];
-                _columnSmiMetaData[i] = MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(_columnMetaData[i]);
-            }
-
-            _eventSink = new SmiEventSink_Default();
-
-            _recordBuffer = new MemoryRecordBuffer(_columnSmiMetaData);
-            _usesStringStorageForXml = true;
-            _eventSink.ProcessMessagesAndThrow();
-        }
-
-        internal SqlDataRecord(SmiRecordBuffer recordBuffer, params SmiExtendedMetaData[] metaData)
-        {
-            Debug.Assert(null != recordBuffer, "invalid attempt to instantiate SqlDataRecord with null SmiRecordBuffer");
-            Debug.Assert(null != metaData, "invalid attempt to instantiate SqlDataRecord with null SmiExtendedMetaData[]");
-
-            _columnMetaData = new SqlMetaData[metaData.Length];
-            _columnSmiMetaData = new SmiExtendedMetaData[metaData.Length];
-            for (int i = 0; i < _columnSmiMetaData.Length; i++)
-            {
-                _columnSmiMetaData[i] = metaData[i];
-                _columnMetaData[i] = MetaDataUtilsSmi.SmiExtendedMetaDataToSqlMetaData(_columnSmiMetaData[i]);
-            }
-
-            _eventSink = new SmiEventSink_Default();
-
-            _recordBuffer = recordBuffer;
-            _eventSink.ProcessMessagesAndThrow();
-        }
-
-        //
-        //  SqlDataRecord private members
-        //
-        internal SmiRecordBuffer RecordBuffer
-        {  // used by SqlPipe
-            get
-            {
-                return _recordBuffer;
-            }
-        }
-
-
-        internal SqlMetaData[] InternalGetMetaData()
-        {
-            return _columnMetaData;
-        }
-
-        internal SmiExtendedMetaData[] InternalGetSmiMetaData()
-        {
-            return _columnSmiMetaData;
-        }
-
-        internal SmiExtendedMetaData GetSmiMetaData(int ordinal)
-        {
-            return _columnSmiMetaData[ordinal];
-        }
-
-        internal void ThrowIfInvalidOrdinal(int ordinal)
-        {
-            if (0 > ordinal || FieldCount <= ordinal)
-            {
-                throw ADP.IndexOutOfRange(ordinal);
-            }
-        }
-        private void EnsureSubclassOverride()
-        {
-            if (null == _recordBuffer)
-            {
-                throw SQL.SubclassMustOverride();
-            }
-        }
-
-        IDataReader System.Data.IDataRecord.GetData(int ordinal)
-        {
-            throw ADP.NotSupported();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlFacetAttribute.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlFacetAttribute.cs
deleted file mode 100644 (file)
index da704cd..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.Server
-{
-    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
-    public class SqlFacetAttribute : Attribute
-    {
-        /// <summary>
-        /// Is this a fixed size field?
-        /// </summary>
-        public bool IsFixedLength
-        {
-            get;
-            set;
-        }
-
-        /// <summary>
-        /// The maximum size of the field (in bytes or characters depending on the field type)
-        /// or -1 if the size can be unlimited.
-        /// </summary>
-        public int MaxSize
-        {
-            get;
-            set;
-        }
-
-        /// <summary>
-        /// Precision, only valid for numeric types.
-        /// </summary>
-        public int Precision
-        {
-            get;
-            set;
-        }
-
-        /// <summary>
-        /// Scale, only valid for numeric types.
-        /// </summary>
-        public int Scale
-        {
-            get;
-            set;
-        }
-
-        /// <summary>
-        /// Is this field nullable?
-        /// </summary>
-        public bool IsNullable
-        {
-            get;
-            set;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlRecordBuffer.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/SqlRecordBuffer.cs
deleted file mode 100644 (file)
index 1b8dccd..0000000
+++ /dev/null
@@ -1,615 +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.Data;
-using System.Data.Common;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.SqlServer.Server
-{
-    internal sealed class SqlRecordBuffer
-    {
-        internal enum StorageType
-        {
-            Boolean,
-            Byte,
-            ByteArray,
-            CharArray,
-            DateTime,
-            DateTimeOffset,
-            Double,
-            Guid,
-            Int16,
-            Int32,
-            Int64,
-            Single,
-            String,
-            SqlDecimal,
-            TimeSpan,
-        }
-
-        [StructLayout(LayoutKind.Explicit)]
-        internal struct Storage
-        {
-            [FieldOffset(0)]
-            internal bool _boolean;
-            [FieldOffset(0)]
-            internal byte _byte;
-            [FieldOffset(0)]
-            internal DateTime _dateTime;
-            [FieldOffset(0)]
-            internal DateTimeOffset _dateTimeOffset;
-            [FieldOffset(0)]
-            internal double _double;
-            [FieldOffset(0)]
-            internal Guid _guid;
-            [FieldOffset(0)]
-            internal short _int16;
-            [FieldOffset(0)]
-            internal int _int32;
-            [FieldOffset(0)]
-            internal long _int64;    // also used to BytesLength and CharsLength
-            [FieldOffset(0)]
-            internal float _single;
-            [FieldOffset(0)]
-            internal TimeSpan _timeSpan;
-        }
-
-        private bool _isNull;
-        private StorageType _type;
-        private Storage _value;
-        private object _object;    // String, SqlDecimal
-        private SmiMetaData _metadata;  // for variant
-        private bool _isMetaSet; // flag to indicate whether we have set the variant metadata
-
-        internal SqlRecordBuffer(SmiMetaData metaData)
-        {
-            _isNull = true;
-        }
-
-        internal bool IsNull
-        {
-            get
-            {
-                return _isNull;
-            }
-        }
-
-        internal bool Boolean
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Boolean == _type, "Wrong storage type: " + _type);
-
-                return _value._boolean;
-            }
-            set
-            {
-                _value._boolean = value;
-                _type = StorageType.Boolean;
-                _isNull = false;
-            }
-        }
-
-        internal byte Byte
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Byte == _type, "Wrong storage type: " + _type);
-
-                return _value._byte;
-            }
-            set
-            {
-                _value._byte = value;
-                _type = StorageType.Byte;
-                _isNull = false;
-            }
-        }
-
-        internal DateTime DateTime
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.DateTime == _type, "Wrong storage type: " + _type);
-
-                return _value._dateTime;
-            }
-            set
-            {
-                _value._dateTime = value;
-                _type = StorageType.DateTime;
-                _isNull = false;
-                // in case of variant types, the caller first sets metadata and than the value. we need to keep metadata after first value set
-                // if value is set second time without variant metadata, reset the metadata since it is not variant anymore
-                if (_isMetaSet)
-                {
-                    _isMetaSet = false;
-                }
-                else
-                {
-                    _metadata = null; // need to clear the variant metadata
-                }
-            }
-        }
-
-        internal DateTimeOffset DateTimeOffset
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.DateTimeOffset == _type, "Wrong storage type: " + _type);
-
-                return _value._dateTimeOffset;
-            }
-            set
-            {
-                _value._dateTimeOffset = value;
-                _type = StorageType.DateTimeOffset;
-                _isNull = false;
-            }
-        }
-
-        internal double Double
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Double == _type, "Wrong storage type: " + _type);
-
-                return _value._double;
-            }
-            set
-            {
-                _value._double = value;
-                _type = StorageType.Double;
-                _isNull = false;
-            }
-        }
-
-        internal Guid Guid
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Guid == _type, "Wrong storage type: " + _type);
-
-                return _value._guid;
-            }
-            set
-            {
-                _value._guid = value;
-                _type = StorageType.Guid;
-                _isNull = false;
-            }
-        }
-
-        internal short Int16
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Int16 == _type, "Wrong storage type: " + _type);
-
-                return _value._int16;
-            }
-            set
-            {
-                _value._int16 = value;
-                _type = StorageType.Int16;
-                _isNull = false;
-            }
-        }
-
-        internal int Int32
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Int32 == _type, "Wrong storage type: " + _type);
-
-                return _value._int32;
-            }
-            set
-            {
-                _value._int32 = value;
-                _type = StorageType.Int32;
-                _isNull = false;
-            }
-        }
-
-        internal long Int64
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Int64 == _type, "Wrong storage type: " + _type);
-
-                return _value._int64;
-            }
-            set
-            {
-                _value._int64 = value;
-                _type = StorageType.Int64;
-                _isNull = false;
-                if (_isMetaSet)
-                {
-                    _isMetaSet = false;
-                }
-                else
-                {
-                    _metadata = null; // need to clear the variant metadata
-                }
-            }
-        }
-
-        internal float Single
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.Single == _type, "Wrong storage type: " + _type);
-
-                return _value._single;
-            }
-            set
-            {
-                _value._single = value;
-                _type = StorageType.Single;
-                _isNull = false;
-            }
-        }
-
-        internal string String
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-
-                if (StorageType.String == _type)
-                {
-                    return (string)_object;
-                }
-                else if (StorageType.CharArray == _type)
-                {
-                    return new string((char[])_object, 0, (int)CharsLength);
-                }
-                else
-                {
-                    // Xml may be stored as byte array, yet have GetString called against it.
-                    Debug.Assert(StorageType.ByteArray == _type, "Wrong storage type: " + _type);
-                    System.IO.Stream byteStream = new System.IO.MemoryStream((byte[])_object, false);
-                    return (new SqlXml(byteStream)).Value;
-                }
-            }
-            set
-            {
-                Debug.Assert(null != value, "");
-
-                _object = value;
-                _value._int64 = ((string)value).Length;
-                _type = StorageType.String;
-                _isNull = false;
-                if (_isMetaSet)
-                {
-                    _isMetaSet = false;
-                }
-                else
-                {
-                    _metadata = null; // need to clear the variant metadata
-                }
-            }
-        }
-
-        internal SqlDecimal SqlDecimal
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.SqlDecimal == _type, "Wrong storage type: " + _type);
-
-                return (SqlDecimal)_object;
-            }
-            set
-            {
-                Debug.Assert(!value.IsNull, "Null input");
-
-                _object = value;
-                _type = StorageType.SqlDecimal;
-                _isNull = false;
-            }
-        }
-
-        internal TimeSpan TimeSpan
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.TimeSpan == _type, "Wrong storage type: " + _type);
-
-                return _value._timeSpan;
-            }
-            set
-            {
-                _value._timeSpan = value;
-                _type = StorageType.TimeSpan;
-                _isNull = false;
-            }
-        }
-
-        internal long BytesLength
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-
-                // sometimes Xml is stored as string, but must support byte access
-                if (StorageType.String == _type)
-                {
-                    ConvertXmlStringToByteArray();
-                }
-                else
-                {
-                    Debug.Assert(StorageType.ByteArray == _type, "Wrong storage type: " + _type);
-                }
-
-                return _value._int64;
-            }
-            set
-            {
-                if (0 == value)
-                {
-                    _value._int64 = value;
-                    _object = Array.Empty<byte>();
-                    _type = StorageType.ByteArray;
-                    _isNull = false;
-                }
-                else
-                {
-                    Debug.Assert(!_isNull, "Null data type");
-                    Debug.Assert(StorageType.ByteArray == _type, "Wrong storage type: " + _type);
-                    Debug.Assert(value > 0 && value <= ((byte[])_object).Length, "Invalid BytesLength");
-
-                    _value._int64 = value;
-                }
-            }
-        }
-
-        internal long CharsLength
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(StorageType.CharArray == _type || StorageType.String == _type, "Wrong storage type: " + _type);
-
-                return _value._int64;
-            }
-            set
-            {
-                if (0 == value)
-                {
-                    _value._int64 = value;
-                    _object = Array.Empty<char>();
-                    _type = StorageType.CharArray;
-                    _isNull = false;
-                }
-                else
-                {
-                    Debug.Assert(!_isNull, "Null data type");
-                    Debug.Assert(StorageType.CharArray == _type || StorageType.String == _type, "Wrong storage type: " + _type);
-                    Debug.Assert(value > 0 &&
-                        ((StorageType.CharArray == _type && value <= ((char[])_object).Length) || (StorageType.String == _type && value <= ((string)_object).Length)),
-                        "Invalid CharsLength");
-
-                    _value._int64 = value;
-                }
-            }
-        }
-
-        internal SmiMetaData VariantType
-        {
-            get
-            {
-                Debug.Assert(!_isNull, "Null data type");
-                Debug.Assert(_metadata == null
-                    || _metadata.SqlDbType == SqlDbType.Money
-                    || _metadata.SqlDbType == SqlDbType.NVarChar
-                    || _metadata.SqlDbType == SqlDbType.DateTime
-                    || _metadata.SqlDbType == SqlDbType.Date
-                    || _metadata.SqlDbType == SqlDbType.DateTime2,
-                    "Invalid metadata");
-
-                return _type switch
-                {
-                    StorageType.Boolean => SmiMetaData.DefaultBit,
-                    StorageType.Byte => SmiMetaData.DefaultTinyInt,
-                    StorageType.ByteArray => SmiMetaData.DefaultVarBinary,
-                    StorageType.CharArray => SmiMetaData.DefaultNVarChar,
-                    StorageType.DateTime => _metadata ?? SmiMetaData.DefaultDateTime,
-                    StorageType.DateTimeOffset => SmiMetaData.DefaultDateTimeOffset,
-                    StorageType.Double => SmiMetaData.DefaultFloat,
-                    StorageType.Guid => SmiMetaData.DefaultUniqueIdentifier,
-                    StorageType.Int16 => SmiMetaData.DefaultSmallInt,
-                    StorageType.Int32 => SmiMetaData.DefaultInt,
-                    StorageType.Int64 => _metadata ?? SmiMetaData.DefaultBigInt,
-                    StorageType.Single => SmiMetaData.DefaultReal,
-                    StorageType.String => _metadata ?? SmiMetaData.DefaultNVarChar,
-                    StorageType.SqlDecimal => new SmiMetaData(SqlDbType.Decimal, 17, ((SqlDecimal)_object).Precision, ((SqlDecimal)_object).Scale, 0, SqlCompareOptions.None, null),
-                    StorageType.TimeSpan => SmiMetaData.DefaultTime,
-                    _ => null,
-                };
-            }
-            set
-            {
-                Debug.Assert(value != null && (value.SqlDbType == SqlDbType.Money || value.SqlDbType == SqlDbType.NVarChar),
-                    "Invalid metadata");
-
-                _metadata = value;
-                _isMetaSet = true;
-            }
-        }
-
-        internal int GetBytes(long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            int ndataIndex = (int)fieldOffset;
-
-            Debug.Assert(!_isNull, "Null data type");
-            // sometimes Xml is stored as string, but must support byte access
-            if (StorageType.String == _type)
-            {
-                ConvertXmlStringToByteArray();
-            }
-            else
-            {
-                Debug.Assert(StorageType.ByteArray == _type, "Wrong storage type: " + _type);
-            }
-            Debug.Assert(null != buffer, "Null buffer");
-            Debug.Assert(ndataIndex + length <= BytesLength, "Invalid fieldOffset or length");
-
-            Buffer.BlockCopy((byte[])_object, ndataIndex, buffer, bufferOffset, length);
-
-            return length;
-        }
-
-        internal int GetChars(long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            int ndataIndex = (int)fieldOffset;
-
-            Debug.Assert(!_isNull, "Null data type");
-            Debug.Assert(StorageType.CharArray == _type || StorageType.String == _type, "Wrong storage type: " + _type);
-            Debug.Assert(null != buffer, "Null buffer");
-            Debug.Assert(ndataIndex + length <= CharsLength, "Invalid fieldOffset or length");
-
-            if (StorageType.CharArray == _type)
-            {
-                Array.Copy((char[])_object, ndataIndex, buffer, bufferOffset, length);
-            }
-            else
-            {    // String type
-                ((string)_object).CopyTo(ndataIndex, buffer, bufferOffset, length);
-            }
-
-            return length;
-        }
-
-        internal int SetBytes(long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            int ndataIndex = (int)fieldOffset;
-
-            if (IsNull || StorageType.ByteArray != _type)
-            {
-                if (ndataIndex != 0)
-                {    // set the first time: should start from the beginning
-                    throw ADP.ArgumentOutOfRange(nameof(fieldOffset));
-                }
-                _object = new byte[length];
-                _type = StorageType.ByteArray;
-                _isNull = false;
-                BytesLength = length;
-            }
-            else
-            {
-                if (ndataIndex > BytesLength)
-                {    // no gap is allowed
-                    throw ADP.ArgumentOutOfRange(nameof(fieldOffset));
-                }
-                if (ndataIndex + length > BytesLength)
-                {    // beyond the current length
-                    int cbytes = ((byte[])_object).Length;
-
-                    if (ndataIndex + length > cbytes)
-                    {    // dynamic expansion
-                        byte[] data = new byte[Math.Max(ndataIndex + length, 2 * cbytes)];
-                        Buffer.BlockCopy((byte[])_object, 0, data, 0, (int)BytesLength);
-                        _object = data;
-                    }
-                    BytesLength = ndataIndex + length;
-                }
-            }
-
-            Buffer.BlockCopy(buffer, bufferOffset, (byte[])_object, ndataIndex, length);
-
-            return length;
-        }
-
-        internal int SetChars(long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            int ndataIndex = (int)fieldOffset;
-
-            if (IsNull || (StorageType.CharArray != _type && StorageType.String != _type))
-            {
-                if (ndataIndex != 0)
-                {    // set the first time: should start from the beginning
-                    throw ADP.ArgumentOutOfRange(nameof(fieldOffset));
-                }
-                _object = new char[length];
-                _type = StorageType.CharArray;
-                _isNull = false;
-                CharsLength = length;
-            }
-            else
-            {
-                if (ndataIndex > CharsLength)
-                {    // no gap is allowed
-                    throw ADP.ArgumentOutOfRange(nameof(fieldOffset));
-                }
-                if (StorageType.String == _type)
-                {    // convert string to char[]
-                    _object = ((string)_object).ToCharArray();
-                    _type = StorageType.CharArray;
-                }
-                if (ndataIndex + length > CharsLength)
-                {    // beyond the current length
-                    int cchars = ((char[])_object).Length;
-
-                    if (ndataIndex + length > cchars)
-                    {    // dynamic expansion
-                        char[] data = new char[Math.Max(ndataIndex + length, 2 * cchars)];
-                        Debug.Assert(CharsLength < int.MaxValue);
-                        Array.Copy((char[])_object, data, (int)CharsLength);
-                        _object = data;
-                    }
-                    CharsLength = ndataIndex + length;
-                }
-            }
-
-            Array.Copy(buffer, bufferOffset, (char[])_object, ndataIndex, length);
-
-            return length;
-        }
-
-        internal void SetNull()
-        {
-            _isNull = true;
-        }
-
-        // Handle case for Xml where SetString() was called, followed by GetBytes()
-        private void ConvertXmlStringToByteArray()
-        {
-            Debug.Assert(StorageType.String == _type, "ConvertXmlStringToByteArray: Invalid storage type for conversion: " + _type.ToString());
-
-            // Grab the unicode bytes, but prepend the XML unicode BOM
-            string value = (string)_object;
-            byte[] bytes = new byte[2 + System.Text.Encoding.Unicode.GetByteCount(value)];
-            bytes[0] = 0xff;
-            bytes[1] = 0xfe;
-            System.Text.Encoding.Unicode.GetBytes(value, 0, value.Length, bytes, 2);
-
-            _object = bytes;
-            _value._int64 = bytes.Length;
-            _type = StorageType.ByteArray;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ValueUtilsSmi.cs b/src/libraries/System.Data.SqlClient/src/Microsoft/SqlServer/Server/ValueUtilsSmi.cs
deleted file mode 100644 (file)
index 1d61e16..0000000
+++ /dev/null
@@ -1,3863 +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;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Xml;
-
-namespace Microsoft.SqlServer.Server
-{
-    // Utilities for manipulating values with the Smi interface.
-    //
-    //  THIS CLASS IS BUILT ON TOP OF THE SMI INTERFACE -- SMI SHOULD NOT DEPEND ON IT!
-    //
-    //  These are all based off of knowing the clr type of the value
-    //  as an ExtendedClrTypeCode enum for rapid access (lookup in static array is best, if possible).
-    internal static class ValueUtilsSmi
-    {
-        private const int __maxByteChunkSize = TdsEnums.MAXSIZE;
-        private const int __maxCharChunkSize = TdsEnums.MAXSIZE / sizeof(char);
-        private const int NoLengthLimit = (int)SmiMetaData.UnlimitedMaxLengthIndicator;  // make sure we use the same constant
-
-        // Constants
-        private const int constBinBufferSize = 4096;  // Size of the buffer used to read input parameter of type Stream
-        private const int constTextBufferSize = 4096; // Size of the buffer (in chars) user to read input parameter of type TextReader
-
-        //
-        //  User-visible semantics-laden Getter/Setter support methods
-        //      These methods implement common semantics for getters & setters
-        //      All access to underlying Smi getters/setters must validate parameters
-        //      in these methods
-        //
-
-        //  The idea for the getters is that there are two types associated with the field/column,
-        //  the one the user asks for (implicitly via a strongly-typed getter) and the one the data
-        //  is stored in (SmiMetaData).
-        //  When a strong getter is invoked, we try one of two ways to get the value
-        //      1) go directly to the source for the requested type if possible
-        //      2) instantiate the value based on the stored type (GetValue), then ask the Clr
-        //          to convert.
-        internal static bool IsDBNull(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            return IsDBNull_Unchecked(sink, getters, ordinal);
-        }
-
-        internal static bool GetBoolean(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Boolean))
-            {
-                return GetBoolean_Unchecked(sink, getters, ordinal);
-            }
-
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (bool)result;
-        }
-
-        internal static byte GetByte(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Byte))
-            {
-                return GetByte_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (byte)result;
-        }
-
-        private static long GetBytesConversion(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData, long fieldOffset, byte[] buffer, int bufferOffset, int length, bool throwOnNull)
-        {
-            object obj = GetSqlValue(sink, getters, ordinal, metaData);
-            if (null == obj)
-            {
-                throw ADP.InvalidCast();
-            }
-            SqlBinary value = (SqlBinary)obj;
-
-            if (value.IsNull)
-            {
-                if (throwOnNull)
-                {
-                    throw SQL.SqlNullValue();
-                }
-                else
-                {
-                    // return zero length in any case
-                    return 0;
-                }
-            }
-
-            if (null == buffer)
-            {
-                return value.Length;
-            }
-
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength * sizeof(char), value.Length,
-                        fieldOffset, buffer.Length, bufferOffset, length);
-            Array.Copy(value.Value, checked((int)fieldOffset), buffer, bufferOffset, length);
-            return length;
-        }
-
-        internal static long GetBytes(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiExtendedMetaData metaData, long fieldOffset, byte[] buffer, int bufferOffset, int length, bool throwOnNull)
-        {
-            // Additional exclusions not caught by GetBytesInternal
-            if ((SmiMetaData.UnlimitedMaxLengthIndicator != metaData.MaxLength &&
-                    (SqlDbType.VarChar == metaData.SqlDbType ||
-                     SqlDbType.NVarChar == metaData.SqlDbType ||
-                     SqlDbType.Char == metaData.SqlDbType ||
-                     SqlDbType.NChar == metaData.SqlDbType)) ||
-                    SqlDbType.Xml == metaData.SqlDbType)
-            {
-                throw SQL.NonBlobColumn(metaData.Name);
-            }
-            else
-            {
-                return GetBytesInternal(sink, getters, ordinal, metaData, fieldOffset, buffer, bufferOffset, length, throwOnNull);
-            }
-        }
-
-        internal static long GetBytesInternal(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData, long fieldOffset, byte[] buffer, int bufferOffset, int length, bool throwOnNull)
-        {
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.ByteArray))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    if (throwOnNull)
-                    {
-                        throw SQL.SqlNullValue();
-                    }
-                    else
-                    {
-                        // check user's parameters for validity against a zero-length value
-                        CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, 0, fieldOffset, buffer.Length, bufferOffset, length);
-
-                        // return zero length in any case
-                        return 0;
-                    }
-                }
-                long actualLength = GetBytesLength_Unchecked(sink, getters, ordinal);
-                if (null == buffer)
-                {
-                    return actualLength;
-                }
-                if (MetaDataUtilsSmi.IsCharOrXmlType(metaData.SqlDbType))
-                {
-                    length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength * sizeof(char), actualLength,
-                                fieldOffset, buffer.Length, bufferOffset, length);
-                }
-                else
-                {
-                    length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, actualLength, fieldOffset, buffer.Length, bufferOffset, length);
-                }
-                Debug.Assert(length >= 0, "Invalid CheckXetParameters return length!");
-                if (length > 0)
-                {
-                    length = GetBytes_Unchecked(sink, getters, ordinal, fieldOffset, buffer, bufferOffset, length);
-                }
-                return length;
-            }
-
-            return GetBytesConversion(sink, getters, ordinal, metaData, fieldOffset, buffer, bufferOffset, length, throwOnNull);
-        }
-
-        internal static long GetChars(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.CharArray))
-            {
-                long actualLength = GetCharsLength_Unchecked(sink, getters, ordinal);
-                if (null == buffer)
-                {
-                    return actualLength;
-                }
-                length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, actualLength, fieldOffset, buffer.Length, bufferOffset, length);
-                Debug.Assert(length >= 0, "Buffer.Length was invalid!");
-                if (length > 0)
-                {
-                    length = GetChars_Unchecked(sink, getters, ordinal, fieldOffset, buffer, bufferOffset, length);
-                }
-                return length;
-            }
-
-            string value = ((string)GetValue(sink, getters, ordinal, metaData));
-            if (null == value)
-            {
-                throw ADP.InvalidCast();
-            }
-            if (null == buffer)
-            {
-                return value.Length;
-            }
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength * sizeof(char), value.Length,
-                        fieldOffset, buffer.Length, bufferOffset, length);
-            value.CopyTo(checked((int)fieldOffset), buffer, bufferOffset, length);
-            return length;
-        }
-
-        internal static DateTime GetDateTime(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.DateTime))
-            {
-                return GetDateTime_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (DateTime)result;
-        }
-
-        // calling GetDateTimeOffset on possibly v100 SMI
-        internal static DateTimeOffset GetDateTimeOffset(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData, bool gettersSupportKatmaiDateTime)
-        {
-            if (gettersSupportKatmaiDateTime)
-            {
-                return GetDateTimeOffset(sink, (SmiTypedGetterSetter)getters, ordinal, metaData);
-            }
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (DateTimeOffset)result;
-        }
-
-        // dealing with v200 SMI
-        internal static DateTimeOffset GetDateTimeOffset(SmiEventSink_Default sink, SmiTypedGetterSetter getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.DateTimeOffset))
-            {
-                return GetDateTimeOffset_Unchecked(sink, getters, ordinal);
-            }
-            return (DateTimeOffset)GetValue200(sink, getters, ordinal, metaData);
-        }
-
-        internal static decimal GetDecimal(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Decimal))
-            {
-                return GetDecimal_PossiblyMoney(sink, getters, ordinal, metaData);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (decimal)result;
-        }
-
-        internal static double GetDouble(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Double))
-            {
-                return GetDouble_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (double)result;
-        }
-
-        internal static Guid GetGuid(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Guid))
-            {
-                return GetGuid_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (Guid)result;
-        }
-
-        internal static short GetInt16(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Int16))
-            {
-                return GetInt16_Unchecked(sink, getters, ordinal);
-            }
-            object obj = GetValue(sink, getters, ordinal, metaData);
-            if (null == obj)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (short)obj;
-        }
-
-        internal static int GetInt32(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Int32))
-            {
-                return GetInt32_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (int)result;
-        }
-
-        internal static long GetInt64(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Int64))
-            {
-                return GetInt64_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (long)result;
-        }
-
-        internal static float GetSingle(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.Single))
-            {
-                return GetSingle_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (float)result;
-        }
-
-        internal static SqlBinary GetSqlBinary(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlBinary))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    return SqlBinary.Null;
-                }
-                return GetSqlBinary_Unchecked(sink, getters, ordinal);
-            }
-            object result = GetSqlValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (SqlBinary)result;
-        }
-
-        internal static SqlBoolean GetSqlBoolean(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlBoolean))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    return SqlBoolean.Null;
-                }
-                return new SqlBoolean(GetBoolean_Unchecked(sink, getters, ordinal));
-            }
-            object result = GetSqlValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (SqlBoolean)result;
-        }
-
-        internal static SqlByte GetSqlByte(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlByte))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    return SqlByte.Null;
-                }
-                return new SqlByte(GetByte_Unchecked(sink, getters, ordinal));
-            }
-            object result = GetSqlValue(sink, getters, ordinal, metaData);
-            if (null == result)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (SqlByte)result;
-        }
-
-        internal static SqlBytes GetSqlBytes(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlBytes result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlBytes))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlBytes.Null;
-                }
-                else
-                {
-                    long length = GetBytesLength_Unchecked(sink, getters, ordinal);
-                    if (0 <= length && length < __maxByteChunkSize)
-                    {
-                        byte[] byteBuffer = GetByteArray_Unchecked(sink, getters, ordinal);
-                        result = new SqlBytes(byteBuffer);
-                    }
-                    else
-                    {
-                        Stream s = new SmiGettersStream(sink, getters, ordinal, metaData);
-                        s = CopyIntoNewSmiScratchStream(s, sink);
-                        result = new SqlBytes(s);
-                    }
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                SqlBinary binaryVal = (SqlBinary)obj;
-                if (binaryVal.IsNull)
-                {
-                    result = SqlBytes.Null;
-                }
-                else
-                {
-                    result = new SqlBytes(binaryVal.Value);
-                }
-            }
-
-            return result;
-        }
-
-        internal static SqlChars GetSqlChars(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlChars result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlChars))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlChars.Null;
-                }
-                else
-                {
-                    char[] charBuffer = GetCharArray_Unchecked(sink, getters, ordinal);
-                    result = new SqlChars(charBuffer);
-                }
-            }
-            else
-            {
-                SqlString stringValue;
-                if (SqlDbType.Xml == metaData.SqlDbType)
-                {
-                    SqlXml xmlValue = GetSqlXml_Unchecked(sink, getters, ordinal);
-
-                    if (xmlValue.IsNull)
-                    {
-                        result = SqlChars.Null;
-                    }
-                    else
-                    {
-                        result = new SqlChars(xmlValue.Value.ToCharArray());
-                    }
-                }
-                else
-                {
-                    object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                    if (null == obj)
-                    {
-                        throw ADP.InvalidCast();
-                    }
-                    stringValue = (SqlString)obj;
-
-                    if (stringValue.IsNull)
-                    {
-                        result = SqlChars.Null;
-                    }
-                    else
-                    {
-                        result = new SqlChars(stringValue.Value.ToCharArray());
-                    }
-                }
-            }
-
-            return result;
-        }
-
-        internal static SqlDateTime GetSqlDateTime(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlDateTime result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlDateTime))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlDateTime.Null;
-                }
-                else
-                {
-                    DateTime temp = GetDateTime_Unchecked(sink, getters, ordinal);
-                    result = new SqlDateTime(temp);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlDateTime)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlDecimal GetSqlDecimal(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlDecimal result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlDecimal))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlDecimal.Null;
-                }
-                else
-                {
-                    result = GetSqlDecimal_Unchecked(sink, getters, ordinal);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlDecimal)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlDouble GetSqlDouble(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlDouble result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlDouble))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlDouble.Null;
-                }
-                else
-                {
-                    double temp = GetDouble_Unchecked(sink, getters, ordinal);
-                    result = new SqlDouble(temp);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlDouble)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlGuid GetSqlGuid(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlGuid result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlGuid))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlGuid.Null;
-                }
-                else
-                {
-                    Guid temp = GetGuid_Unchecked(sink, getters, ordinal);
-                    result = new SqlGuid(temp);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlGuid)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlInt16 GetSqlInt16(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlInt16 result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlInt16))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlInt16.Null;
-                }
-                else
-                {
-                    short temp = GetInt16_Unchecked(sink, getters, ordinal);
-                    result = new SqlInt16(temp);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlInt16)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlInt32 GetSqlInt32(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlInt32 result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlInt32))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlInt32.Null;
-                }
-                else
-                {
-                    int temp = GetInt32_Unchecked(sink, getters, ordinal);
-                    result = new SqlInt32(temp);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlInt32)obj;
-            }
-            return result;
-        }
-
-        internal static SqlInt64 GetSqlInt64(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlInt64 result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlInt64))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlInt64.Null;
-                }
-                else
-                {
-                    long temp = GetInt64_Unchecked(sink, getters, ordinal);
-                    result = new SqlInt64(temp);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlInt64)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlMoney GetSqlMoney(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlMoney result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlMoney))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlMoney.Null;
-                }
-                else
-                {
-                    result = GetSqlMoney_Unchecked(sink, getters, ordinal);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlMoney)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlSingle GetSqlSingle(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlSingle result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlSingle))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlSingle.Null;
-                }
-                else
-                {
-                    float temp = GetSingle_Unchecked(sink, getters, ordinal);
-                    result = new SqlSingle(temp);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlSingle)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlString GetSqlString(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlString result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlString))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlString.Null;
-                }
-                else
-                {
-                    string temp = GetString_Unchecked(sink, getters, ordinal);
-                    result = new SqlString(temp);
-                }
-            }
-            else if (SqlDbType.Xml == metaData.SqlDbType)
-            {
-                SqlXml xmlValue = GetSqlXml_Unchecked(sink, getters, ordinal);
-
-                if (xmlValue.IsNull)
-                {
-                    result = SqlString.Null;
-                }
-                else
-                {
-                    result = new SqlString(xmlValue.Value);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlString)obj;
-            }
-
-            return result;
-        }
-
-        internal static SqlXml GetSqlXml(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            SqlXml result;
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.SqlXml))
-            {
-                if (IsDBNull_Unchecked(sink, getters, ordinal))
-                {
-                    result = SqlXml.Null;
-                }
-                else
-                {
-                    result = GetSqlXml_Unchecked(sink, getters, ordinal);
-                }
-            }
-            else
-            {
-                object obj = GetSqlValue(sink, getters, ordinal, metaData);
-                if (null == obj)
-                {
-                    throw ADP.InvalidCast();
-                }
-                result = (SqlXml)obj;
-            }
-
-            return result;
-        }
-
-        internal static string GetString(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.String))
-            {
-                return GetString_Unchecked(sink, getters, ordinal);
-            }
-            object obj = GetValue(sink, getters, ordinal, metaData);
-            if (null == obj)
-            {
-                throw ADP.InvalidCast();
-            }
-            return (string)obj;
-        }
-
-
-        // dealing with v200 SMI
-        internal static TimeSpan GetTimeSpan(SmiEventSink_Default sink, SmiTypedGetterSetter getters, int ordinal, SmiMetaData metaData)
-        {
-            ThrowIfITypedGettersIsNull(sink, getters, ordinal);
-            if (CanAccessGetterDirectly(metaData, ExtendedClrTypeCode.TimeSpan))
-            {
-                return GetTimeSpan_Unchecked(sink, getters, ordinal);
-            }
-            return (TimeSpan)GetValue200(sink, getters, ordinal, metaData);
-        }
-
-        // GetValue() for v200 SMI (new Katmai Date/Time types)
-        internal static object GetValue200(
-            SmiEventSink_Default sink,
-            SmiTypedGetterSetter getters,
-            int ordinal,
-            SmiMetaData metaData
-            )
-        {
-            object result = null;
-            if (IsDBNull_Unchecked(sink, getters, ordinal))
-            {
-                result = DBNull.Value;
-            }
-            else
-            {
-                switch (metaData.SqlDbType)
-                {
-                    case SqlDbType.Variant:  // Handle variants specifically for v200, since they could contain v200 types
-                        metaData = getters.GetVariantType(sink, ordinal);
-                        sink.ProcessMessagesAndThrow();
-                        Debug.Assert(SqlDbType.Variant != metaData.SqlDbType, "Variant-within-variant causes endless recursion!");
-                        result = GetValue200(sink, getters, ordinal, metaData);
-                        break;
-                    case SqlDbType.Date:
-                    case SqlDbType.DateTime2:
-                        result = GetDateTime_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Time:
-                        result = GetTimeSpan_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.DateTimeOffset:
-                        result = GetDateTimeOffset_Unchecked(sink, getters, ordinal);
-                        break;
-                    default:
-                        result = GetValue(sink, getters, ordinal, metaData);
-                        break;
-                }
-            }
-
-            return result;
-        }
-
-        //  implements SqlClient 1.1-compatible GetValue() semantics for everything except output parameters
-        internal static object GetValue(
-            SmiEventSink_Default sink,
-            ITypedGettersV3 getters,
-            int ordinal,
-            SmiMetaData metaData
-            )
-        {
-            object result = null;
-            if (IsDBNull_Unchecked(sink, getters, ordinal))
-            {
-                result = DBNull.Value;
-            }
-            else
-            {
-                switch (metaData.SqlDbType)
-                {
-                    case SqlDbType.BigInt:
-                        result = GetInt64_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Binary:
-                        result = GetByteArray_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Bit:
-                        result = GetBoolean_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Char:
-                        result = GetString_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.DateTime:
-                        result = GetDateTime_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Decimal:
-                        result = GetSqlDecimal_Unchecked(sink, getters, ordinal).Value;
-                        break;
-                    case SqlDbType.Float:
-                        result = GetDouble_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Image:
-                        result = GetByteArray_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Int:
-                        result = GetInt32_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Money:
-                        result = GetSqlMoney_Unchecked(sink, getters, ordinal).Value;
-                        break;
-                    case SqlDbType.NChar:
-                        result = GetString_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.NText:
-                        result = GetString_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.NVarChar:
-                        result = GetString_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Real:
-                        result = GetSingle_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.UniqueIdentifier:
-                        result = GetGuid_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.SmallDateTime:
-                        result = GetDateTime_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.SmallInt:
-                        result = GetInt16_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.SmallMoney:
-                        result = GetSqlMoney_Unchecked(sink, getters, ordinal).Value;
-                        break;
-                    case SqlDbType.Text:
-                        result = GetString_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Timestamp:
-                        result = GetByteArray_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.TinyInt:
-                        result = GetByte_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.VarBinary:
-                        result = GetByteArray_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.VarChar:
-                        result = GetString_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Variant:
-                        metaData = getters.GetVariantType(sink, ordinal);
-                        sink.ProcessMessagesAndThrow();
-                        Debug.Assert(SqlDbType.Variant != metaData.SqlDbType, "Variant-within-variant causes endless recursion!");
-                        result = GetValue(sink, getters, ordinal, metaData);
-                        break;
-                    case SqlDbType.Xml:
-                        result = GetSqlXml_Unchecked(sink, getters, ordinal).Value;
-                        break;
-                    case SqlDbType.Udt:
-                        result = GetUdt_LengthChecked(sink, getters, ordinal, metaData);
-                        break;
-                }
-            }
-
-            return result;
-        }
-
-        // dealing with v200 SMI
-        internal static object GetSqlValue200(
-            SmiEventSink_Default sink,
-            SmiTypedGetterSetter getters,
-            int ordinal,
-            SmiMetaData metaData
-            )
-        {
-            object result = null;
-            if (IsDBNull_Unchecked(sink, getters, ordinal))
-            {
-                if (SqlDbType.Udt == metaData.SqlDbType)
-                {
-                    result = NullUdtInstance(metaData);
-                }
-                else
-                {
-                    result = s_typeSpecificNullForSqlValue[(int)metaData.SqlDbType];
-                }
-            }
-            else
-            {
-                switch (metaData.SqlDbType)
-                {
-                    case SqlDbType.Variant: // Handle variants specifically for v200, since they could contain v200 types
-                        metaData = getters.GetVariantType(sink, ordinal);
-                        sink.ProcessMessagesAndThrow();
-                        Debug.Assert(SqlDbType.Variant != metaData.SqlDbType, "Variant-within-variant causes endless recursion!");
-                        result = GetSqlValue200(sink, getters, ordinal, metaData);
-                        break;
-                    case SqlDbType.Date:
-                    case SqlDbType.DateTime2:
-                        result = GetDateTime_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Time:
-                        result = GetTimeSpan_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.DateTimeOffset:
-                        result = GetDateTimeOffset_Unchecked(sink, getters, ordinal);
-                        break;
-                    default:
-                        result = GetSqlValue(sink, getters, ordinal, metaData);
-                        break;
-                }
-            }
-
-            return result;
-        }
-
-        //  implements SqlClient 1.1-compatible GetSqlValue() semantics for everything except output parameters
-        internal static object GetSqlValue(
-            SmiEventSink_Default sink,
-            ITypedGettersV3 getters,
-            int ordinal,
-            SmiMetaData metaData
-            )
-        {
-            object result = null;
-            if (IsDBNull_Unchecked(sink, getters, ordinal))
-            {
-                if (SqlDbType.Udt == metaData.SqlDbType)
-                {
-                    result = NullUdtInstance(metaData);
-                }
-                else
-                {
-                    result = s_typeSpecificNullForSqlValue[(int)metaData.SqlDbType];
-                }
-            }
-            else
-            {
-                switch (metaData.SqlDbType)
-                {
-                    case SqlDbType.BigInt:
-                        result = new SqlInt64(GetInt64_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Binary:
-                        result = GetSqlBinary_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Bit:
-                        result = new SqlBoolean(GetBoolean_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Char:
-                        result = new SqlString(GetString_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.DateTime:
-                        result = new SqlDateTime(GetDateTime_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Decimal:
-                        result = GetSqlDecimal_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Float:
-                        result = new SqlDouble(GetDouble_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Image:
-                        result = GetSqlBinary_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Int:
-                        result = new SqlInt32(GetInt32_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Money:
-                        result = GetSqlMoney_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.NChar:
-                        result = new SqlString(GetString_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.NText:
-                        result = new SqlString(GetString_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.NVarChar:
-                        result = new SqlString(GetString_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Real:
-                        result = new SqlSingle(GetSingle_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.UniqueIdentifier:
-                        result = new SqlGuid(GetGuid_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.SmallDateTime:
-                        result = new SqlDateTime(GetDateTime_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.SmallInt:
-                        result = new SqlInt16(GetInt16_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.SmallMoney:
-                        result = GetSqlMoney_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Text:
-                        result = new SqlString(GetString_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Timestamp:
-                        result = GetSqlBinary_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.TinyInt:
-                        result = new SqlByte(GetByte_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.VarBinary:
-                        result = GetSqlBinary_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.VarChar:
-                        result = new SqlString(GetString_Unchecked(sink, getters, ordinal));
-                        break;
-                    case SqlDbType.Variant:
-                        metaData = getters.GetVariantType(sink, ordinal);
-                        sink.ProcessMessagesAndThrow();
-                        Debug.Assert(SqlDbType.Variant != metaData.SqlDbType, "Variant-within-variant causes endless recursion!");
-                        result = GetSqlValue(sink, getters, ordinal, metaData);
-                        break;
-                    case SqlDbType.Xml:
-                        result = GetSqlXml_Unchecked(sink, getters, ordinal);
-                        break;
-                    case SqlDbType.Udt:
-                        result = GetUdt_LengthChecked(sink, getters, ordinal, metaData);
-                        break;
-                }
-            }
-
-            return result;
-        }
-
-        // null return values for SqlClient 1.1-compatible GetSqlValue()
-        private static readonly object[] s_typeSpecificNullForSqlValue = {
-            SqlInt64.Null,      // SqlDbType.BigInt
-            SqlBinary.Null,     // SqlDbType.Binary
-            SqlBoolean.Null,    // SqlDbType.Bit
-            SqlString.Null,     // SqlDbType.Char
-            SqlDateTime.Null,   // SqlDbType.DateTime
-            SqlDecimal.Null,    // SqlDbType.Decimal
-            SqlDouble.Null,     // SqlDbType.Float
-            SqlBinary.Null,     // SqlDbType.Image
-            SqlInt32.Null,      // SqlDbType.Int
-            SqlMoney.Null,      // SqlDbType.Money
-            SqlString.Null,     // SqlDbType.NChar
-            SqlString.Null,     // SqlDbType.NText
-            SqlString.Null,     // SqlDbType.NVarChar
-            SqlSingle.Null,     // SqlDbType.Real
-            SqlGuid.Null,       // SqlDbType.UniqueIdentifier
-            SqlDateTime.Null,   // SqlDbType.SmallDateTime
-            SqlInt16.Null,      // SqlDbType.SmallInt
-            SqlMoney.Null,      // SqlDbType.SmallMoney
-            SqlString.Null,     // SqlDbType.Text
-            SqlBinary.Null,     // SqlDbType.Timestamp
-            SqlByte.Null,       // SqlDbType.TinyInt
-            SqlBinary.Null,     // SqlDbType.VarBinary
-            SqlString.Null,     // SqlDbType.VarChar
-            DBNull.Value,       // SqlDbType.Variant
-            null,               // 24
-            SqlXml.Null,        // SqlDbType.Xml
-            null,               // 26
-            null,               // 27
-            null,               // 28
-            null,               // SqlDbType.Udt -- requires instantiating udt-specific type
-            null,               // SqlDbType.Structured
-            DBNull.Value,       // SqlDbType.Date
-            DBNull.Value,       // SqlDbType.Time
-            DBNull.Value,       // SqlDbType.DateTime2
-            DBNull.Value,       // SqlDbType.DateTimeOffset
-        };
-
-        internal static object NullUdtInstance(SmiMetaData metaData)
-        {
-            Type t = metaData.Type;
-            Debug.Assert(t != null, "Unexpected null of Udt type on NullUdtInstance!");
-            return t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, Array.Empty<object>(), CultureInfo.InvariantCulture);
-        }
-
-        // Strongly-typed setters are a bit simpler than their corresponding getters.
-        //      1) check to make sure the type is compatible (exception if not)
-        //      2) push the data
-        internal static void SetDBNull(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, bool value)
-        {
-            SetDBNull_Unchecked(sink, setters, ordinal);
-        }
-
-        internal static void SetBoolean(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, bool value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Boolean);
-
-            SetBoolean_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetByte(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, byte value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Byte);
-
-            SetByte_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static long SetBytes(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.ByteArray);
-            if (null == buffer)
-            {
-                throw ADP.ArgumentNull(nameof(buffer));
-            }
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, fieldOffset, buffer.Length, bufferOffset, length);
-            Debug.Assert(length >= 0, "Buffer.Length was invalid!");
-            if (0 == length)
-            {
-                // Front end semantics says to ignore fieldOffset and bufferOffset
-                //  if not doing any actual work.
-                // Back end semantics says they must be valid, even for no work.
-                // Compensate by setting offsets to zero here (valid for any scenario)
-                fieldOffset = 0;
-                bufferOffset = 0;
-            }
-            return SetBytes_Unchecked(sink, setters, ordinal, fieldOffset, buffer, bufferOffset, length);
-        }
-
-        internal static long SetBytesLength(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, long length)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.ByteArray);
-
-            if (length < 0)
-            {
-                throw ADP.InvalidDataLength(length);
-            }
-
-            if (metaData.MaxLength >= 0 && length > metaData.MaxLength)
-            {
-                length = metaData.MaxLength;
-            }
-
-            setters.SetBytesLength(sink, ordinal, length);
-            sink.ProcessMessagesAndThrow();
-
-            return length;
-        }
-
-        internal static long SetChars(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.CharArray);
-            if (null == buffer)
-            {
-                throw ADP.ArgumentNull(nameof(buffer));
-            }
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, fieldOffset, buffer.Length, bufferOffset, length);
-            Debug.Assert(length >= 0, "Buffer.Length was invalid!");
-            if (0 == length)
-            {
-                // Front end semantics says to ignore fieldOffset and bufferOffset
-                //  if not doing any actual work.
-                // Back end semantics says they must be valid, even for no work.
-                // Compensate by setting offsets to zero here (valid for any scenario)
-                fieldOffset = 0;
-                bufferOffset = 0;
-            }
-            return SetChars_Unchecked(sink, setters, ordinal, fieldOffset, buffer, bufferOffset, length);
-        }
-
-        internal static void SetDateTime(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, DateTime value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.DateTime);
-
-            SetDateTime_Checked(sink, setters, ordinal, metaData, value);
-        }
-
-        internal static void SetDateTimeOffset(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, DateTimeOffset value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.DateTimeOffset);
-            SetDateTimeOffset_Unchecked(sink, (SmiTypedGetterSetter)setters, ordinal, value);
-        }
-
-        internal static void SetDecimal(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, decimal value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Decimal);
-
-            SetDecimal_PossiblyMoney(sink, setters, ordinal, metaData, value);
-        }
-
-        internal static void SetDouble(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, double value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Double);
-
-            SetDouble_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetGuid(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, Guid value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Guid);
-
-            SetGuid_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetInt16(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, short value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Int16);
-
-            SetInt16_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetInt32(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, int value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Int32);
-
-            SetInt32_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetInt64(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, long value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Int64);
-
-            SetInt64_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSingle(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, float value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.Single);
-
-            SetSingle_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlBinary(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlBinary value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlBinary);
-            SetSqlBinary_LengthChecked(sink, setters, ordinal, metaData, value, 0);
-        }
-
-        internal static void SetSqlBoolean(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlBoolean value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlBoolean);
-
-            SetSqlBoolean_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlByte(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlByte value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlByte);
-
-            SetSqlByte_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlBytes(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlBytes value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlBytes);
-
-            SetSqlBytes_LengthChecked(sink, setters, ordinal, metaData, value, 0);
-        }
-
-        internal static void SetSqlChars(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlChars value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlChars);
-            SetSqlChars_LengthChecked(sink, setters, ordinal, metaData, value, 0);
-        }
-
-        internal static void SetSqlDateTime(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlDateTime value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlDateTime);
-
-            SetSqlDateTime_Checked(sink, setters, ordinal, metaData, value);
-        }
-
-        internal static void SetSqlDecimal(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlDecimal value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlDecimal);
-
-            SetSqlDecimal_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlDouble(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlDouble value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlDouble);
-
-            SetSqlDouble_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlGuid(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlGuid value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlGuid);
-
-            SetSqlGuid_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlInt16(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlInt16 value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlInt16);
-
-            SetSqlInt16_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlInt32(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlInt32 value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlInt32);
-
-            SetSqlInt32_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlInt64(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlInt64 value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlInt64);
-
-            SetSqlInt64_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlMoney(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlMoney value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlMoney);
-
-            SetSqlMoney_Checked(sink, setters, ordinal, metaData, value);
-        }
-
-        internal static void SetSqlSingle(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlSingle value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlSingle);
-
-            SetSqlSingle_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetSqlString(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlString value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlString);
-            SetSqlString_LengthChecked(sink, setters, ordinal, metaData, value, 0);
-        }
-
-        internal static void SetSqlXml(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlXml value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.SqlXml);
-
-            SetSqlXml_Unchecked(sink, setters, ordinal, value);
-        }
-
-        internal static void SetString(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, string value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.String);
-
-            SetString_LengthChecked(sink, setters, ordinal, metaData, value, 0);
-        }
-
-        internal static void SetTimeSpan(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, TimeSpan value)
-        {
-            ThrowIfInvalidSetterAccess(metaData, ExtendedClrTypeCode.TimeSpan);
-            SetTimeSpan_Checked(sink, (SmiTypedGetterSetter)setters, ordinal, metaData, value);
-        }
-
-        //  Implements SqlClient 2.0-compatible SetValue() semantics
-        //      Assumes caller already validated type against the metadata, other than trimming lengths
-        internal static void SetCompatibleValue(
-            SmiEventSink_Default sink,
-            ITypedSettersV3 setters,
-            int ordinal,
-            SmiMetaData metaData,       // metadata for target setter column
-            object value,
-            ExtendedClrTypeCode typeCode,
-            int offset
-            )
-        {
-            // Ensure either an invalid type, or caller validated compatibility
-            // SqlDbType.Variant and have special handling
-            Debug.Assert(typeCode == ExtendedClrTypeCode.Invalid ||
-                            typeCode == ExtendedClrTypeCode.SByte ||
-                            typeCode == ExtendedClrTypeCode.UInt16 ||
-                            typeCode == ExtendedClrTypeCode.UInt32 ||
-                            typeCode == ExtendedClrTypeCode.UInt64 ||
-                            typeCode == ExtendedClrTypeCode.DBNull ||
-                            typeCode == ExtendedClrTypeCode.Empty ||
-                            CanAccessSetterDirectly(metaData, typeCode) ||
-                            value is DataFeed /* already validated */);
-
-            switch (typeCode)
-            {
-                case ExtendedClrTypeCode.Invalid: throw ADP.UnknownDataType(value.GetType());
-                case ExtendedClrTypeCode.Boolean: SetBoolean_Unchecked(sink, setters, ordinal, (bool)value); break;
-                case ExtendedClrTypeCode.Byte: SetByte_Unchecked(sink, setters, ordinal, (byte)value); break;
-                case ExtendedClrTypeCode.Char:
-                    {
-                        char[] charsValue = new char[] { (char)value };
-                        // recur with array type
-                        SetCompatibleValue(sink, setters, ordinal, metaData, charsValue, ExtendedClrTypeCode.CharArray, 0);
-                        break;
-                    }
-                case ExtendedClrTypeCode.DateTime: SetDateTime_Checked(sink, setters, ordinal, metaData, (DateTime)value); break;
-                case ExtendedClrTypeCode.DBNull: SetDBNull_Unchecked(sink, setters, ordinal); break;
-                case ExtendedClrTypeCode.Decimal: SetDecimal_PossiblyMoney(sink, setters, ordinal, metaData, (decimal)value); break;
-                case ExtendedClrTypeCode.Double: SetDouble_Unchecked(sink, setters, ordinal, (double)value); break;
-                case ExtendedClrTypeCode.Empty: SetDBNull_Unchecked(sink, setters, ordinal); break;
-                case ExtendedClrTypeCode.Int16: SetInt16_Unchecked(sink, setters, ordinal, (short)value); break;
-                case ExtendedClrTypeCode.Int32: SetInt32_Unchecked(sink, setters, ordinal, (int)value); break;
-                case ExtendedClrTypeCode.Int64: SetInt64_Unchecked(sink, setters, ordinal, (long)value); break;
-                case ExtendedClrTypeCode.SByte: throw ADP.InvalidCast();
-                case ExtendedClrTypeCode.Single: SetSingle_Unchecked(sink, setters, ordinal, (float)value); break;
-                case ExtendedClrTypeCode.String: SetString_LengthChecked(sink, setters, ordinal, metaData, (string)value, offset); break;
-                case ExtendedClrTypeCode.UInt16: throw ADP.InvalidCast();
-                case ExtendedClrTypeCode.UInt32: throw ADP.InvalidCast();
-                case ExtendedClrTypeCode.UInt64: throw ADP.InvalidCast();
-                case ExtendedClrTypeCode.Object: SetUdt_LengthChecked(sink, setters, ordinal, metaData, value); break;
-                case ExtendedClrTypeCode.ByteArray: SetByteArray_LengthChecked(sink, setters, ordinal, metaData, (byte[])value, offset); break;
-                case ExtendedClrTypeCode.CharArray: SetCharArray_LengthChecked(sink, setters, ordinal, metaData, (char[])value, offset); break;
-                case ExtendedClrTypeCode.Guid: SetGuid_Unchecked(sink, setters, ordinal, (Guid)value); break;
-                case ExtendedClrTypeCode.SqlBinary: SetSqlBinary_LengthChecked(sink, setters, ordinal, metaData, (SqlBinary)value, offset); break;
-                case ExtendedClrTypeCode.SqlBoolean: SetSqlBoolean_Unchecked(sink, setters, ordinal, (SqlBoolean)value); break;
-                case ExtendedClrTypeCode.SqlByte: SetSqlByte_Unchecked(sink, setters, ordinal, (SqlByte)value); break;
-                case ExtendedClrTypeCode.SqlDateTime: SetSqlDateTime_Checked(sink, setters, ordinal, metaData, (SqlDateTime)value); break;
-                case ExtendedClrTypeCode.SqlDouble: SetSqlDouble_Unchecked(sink, setters, ordinal, (SqlDouble)value); break;
-                case ExtendedClrTypeCode.SqlGuid: SetSqlGuid_Unchecked(sink, setters, ordinal, (SqlGuid)value); break;
-                case ExtendedClrTypeCode.SqlInt16: SetSqlInt16_Unchecked(sink, setters, ordinal, (SqlInt16)value); break;
-                case ExtendedClrTypeCode.SqlInt32: SetSqlInt32_Unchecked(sink, setters, ordinal, (SqlInt32)value); break;
-                case ExtendedClrTypeCode.SqlInt64: SetSqlInt64_Unchecked(sink, setters, ordinal, (SqlInt64)value); break;
-                case ExtendedClrTypeCode.SqlMoney: SetSqlMoney_Checked(sink, setters, ordinal, metaData, (SqlMoney)value); break;
-                case ExtendedClrTypeCode.SqlDecimal: SetSqlDecimal_Unchecked(sink, setters, ordinal, (SqlDecimal)value); break;
-                case ExtendedClrTypeCode.SqlSingle: SetSqlSingle_Unchecked(sink, setters, ordinal, (SqlSingle)value); break;
-                case ExtendedClrTypeCode.SqlString: SetSqlString_LengthChecked(sink, setters, ordinal, metaData, (SqlString)value, offset); break;
-                case ExtendedClrTypeCode.SqlChars: SetSqlChars_LengthChecked(sink, setters, ordinal, metaData, (SqlChars)value, offset); break;
-                case ExtendedClrTypeCode.SqlBytes: SetSqlBytes_LengthChecked(sink, setters, ordinal, metaData, (SqlBytes)value, offset); break;
-                case ExtendedClrTypeCode.SqlXml: SetSqlXml_Unchecked(sink, setters, ordinal, (SqlXml)value); break;
-                case ExtendedClrTypeCode.Stream: SetStream_Unchecked(sink, setters, ordinal, metaData, (StreamDataFeed)value); break;
-                case ExtendedClrTypeCode.TextReader: SetTextReader_Unchecked(sink, setters, ordinal, metaData, (TextDataFeed)value); break;
-                case ExtendedClrTypeCode.XmlReader: SetXmlReader_Unchecked(sink, setters, ordinal, ((XmlDataFeed)value)._source); break;
-                default:
-                    Debug.Fail("Unvalidated extendedtypecode: " + typeCode);
-                    break;
-            }
-        }
-
-        // VSTFDevDiv#479681 - Data corruption when sending Katmai Date types to the server via TVP
-        // Ensures proper handling on DateTime2 sub type for Sql_Variants and TVPs.
-        internal static void SetCompatibleValueV200(
-            SmiEventSink_Default sink,
-            SmiTypedGetterSetter setters,
-            int ordinal,
-            SmiMetaData metaData,
-            object value,
-            ExtendedClrTypeCode typeCode,
-            int offset,
-            int length,
-            ParameterPeekAheadValue peekAhead,
-            SqlBuffer.StorageType storageType
-            )
-        {
-            // Ensure caller validated compatibility for types handled directly in this method
-            Debug.Assert((ExtendedClrTypeCode.DataTable != typeCode &&
-                            ExtendedClrTypeCode.DbDataReader != typeCode &&
-                            ExtendedClrTypeCode.IEnumerableOfSqlDataRecord != typeCode) ||
-                        CanAccessSetterDirectly(metaData, typeCode), "Un-validated type '" + typeCode + "' for metaData: " + metaData.SqlDbType);
-
-            if (typeCode == ExtendedClrTypeCode.DateTime)
-            {
-                if (storageType == SqlBuffer.StorageType.DateTime2)
-                    SetDateTime2_Checked(sink, setters, ordinal, metaData, (DateTime)value);
-                else if (storageType == SqlBuffer.StorageType.Date)
-                    SetDate_Checked(sink, setters, ordinal, metaData, (DateTime)value);
-                else
-                    SetDateTime_Checked(sink, setters, ordinal, metaData, (DateTime)value);
-            }
-            else
-            {
-                SetCompatibleValueV200(sink, setters, ordinal, metaData, value, typeCode, offset, length, peekAhead);
-            }
-        }
-
-        //  Implements SqlClient 2.0-compatible SetValue() semantics + Orcas extensions
-        //      Assumes caller already validated basic type against the metadata, other than trimming lengths and
-        //      checking individual field values (TVPs)
-        internal static void SetCompatibleValueV200(
-            SmiEventSink_Default sink,
-            SmiTypedGetterSetter setters,
-            int ordinal,
-            SmiMetaData metaData,
-            object value,
-            ExtendedClrTypeCode typeCode,
-            int offset,
-            int length,
-            ParameterPeekAheadValue peekAhead
-            )
-        {
-            // Ensure caller validated compatibility for types handled directly in this method
-            Debug.Assert((ExtendedClrTypeCode.DataTable != typeCode &&
-                            ExtendedClrTypeCode.DbDataReader != typeCode &&
-                            ExtendedClrTypeCode.IEnumerableOfSqlDataRecord != typeCode) ||
-                        CanAccessSetterDirectly(metaData, typeCode), "Un-validated type '" + typeCode + "' for metaData: " + metaData.SqlDbType);
-
-            switch (typeCode)
-            {
-                case ExtendedClrTypeCode.DataTable:
-                    SetDataTable_Unchecked(sink, setters, ordinal, metaData, (DataTable)value);
-                    break;
-                case ExtendedClrTypeCode.DbDataReader:
-                    SetDbDataReader_Unchecked(sink, setters, ordinal, metaData, (DbDataReader)value);
-                    break;
-                case ExtendedClrTypeCode.IEnumerableOfSqlDataRecord:
-                    SetIEnumerableOfSqlDataRecord_Unchecked(sink, setters, ordinal, metaData, (IEnumerable<SqlDataRecord>)value, peekAhead);
-                    break;
-                case ExtendedClrTypeCode.TimeSpan:
-                    SetTimeSpan_Checked(sink, setters, ordinal, metaData, (TimeSpan)value);
-                    break;
-                case ExtendedClrTypeCode.DateTimeOffset:
-                    SetDateTimeOffset_Unchecked(sink, setters, ordinal, (DateTimeOffset)value);
-                    break;
-                default:
-                    SetCompatibleValue(sink, setters, ordinal, metaData, value, typeCode, offset);
-                    break;
-            }
-        }
-
-        private static void SetDataTable_Unchecked(
-                SmiEventSink_Default sink,
-                SmiTypedGetterSetter setters,
-                int ordinal,
-                SmiMetaData metaData,
-                DataTable value
-            )
-        {
-            // Get the target gettersetter
-            setters = setters.GetTypedGetterSetter(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-
-            // iterate over all records
-            //  if first record was obtained earlier, use it prior to pulling more
-            ExtendedClrTypeCode[] cellTypes = new ExtendedClrTypeCode[metaData.FieldMetaData.Count];
-            for (int i = 0; i < metaData.FieldMetaData.Count; i++)
-            {
-                cellTypes[i] = ExtendedClrTypeCode.Invalid;
-            }
-            foreach (DataRow row in value.Rows)
-            {
-                setters.NewElement(sink);
-                sink.ProcessMessagesAndThrow();
-
-                // Set all columns in the record
-                for (int i = 0; i < metaData.FieldMetaData.Count; i++)
-                {
-                    SmiMetaData fieldMetaData = metaData.FieldMetaData[i];
-                    if (row.IsNull(i))
-                    {
-                        SetDBNull_Unchecked(sink, setters, i);
-                    }
-                    else
-                    {
-                        object cellValue = row[i];
-
-                        // Only determine cell types for first row, to save expensive
-                        if (ExtendedClrTypeCode.Invalid == cellTypes[i])
-                        {
-                            cellTypes[i] = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(
-                                    fieldMetaData.SqlDbType, fieldMetaData.IsMultiValued, cellValue, fieldMetaData.Type);
-                        }
-                        SetCompatibleValueV200(sink, setters, i, fieldMetaData, cellValue, cellTypes[i], 0, NoLengthLimit, null);
-                    }
-                }
-            }
-
-            setters.EndElements(sink);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        // Copy multiple fields from reader to ITypedSettersV3
-        //  Assumes caller enforces that reader and setter metadata are compatible
-        internal static void FillCompatibleITypedSettersFromReader(SmiEventSink_Default sink, ITypedSettersV3 setters, SmiMetaData[] metaData, SqlDataReader reader)
-        {
-            for (int i = 0; i < metaData.Length; i++)
-            {
-                if (reader.IsDBNull(i))
-                {
-                    ValueUtilsSmi.SetDBNull_Unchecked(sink, setters, i);
-                }
-                else
-                {
-                    switch (metaData[i].SqlDbType)
-                    {
-                        case SqlDbType.BigInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int64));
-                            ValueUtilsSmi.SetInt64_Unchecked(sink, setters, i, reader.GetInt64(i));
-                            break;
-                        case SqlDbType.Binary:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            ValueUtilsSmi.SetSqlBytes_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlBytes(i), 0);
-                            break;
-                        case SqlDbType.Bit:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Boolean));
-                            SetBoolean_Unchecked(sink, setters, i, reader.GetBoolean(i));
-                            break;
-                        case SqlDbType.Char:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlChars));
-                            SetSqlChars_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlChars(i), 0);
-                            break;
-                        case SqlDbType.DateTime:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], reader.GetDateTime(i));
-                            break;
-                        case SqlDbType.Decimal:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlDecimal));
-                            SetSqlDecimal_Unchecked(sink, setters, i, reader.GetSqlDecimal(i));
-                            break;
-                        case SqlDbType.Float:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Double));
-                            SetDouble_Unchecked(sink, setters, i, reader.GetDouble(i));
-                            break;
-                        case SqlDbType.Image:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetSqlBytes_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlBytes(i), 0);
-                            break;
-                        case SqlDbType.Int:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int32));
-                            SetInt32_Unchecked(sink, setters, i, reader.GetInt32(i));
-                            break;
-                        case SqlDbType.Money:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlMoney));
-                            SetSqlMoney_Unchecked(sink, setters, i, metaData[i], reader.GetSqlMoney(i));
-                            break;
-                        case SqlDbType.NChar:
-                        case SqlDbType.NText:
-                        case SqlDbType.NVarChar:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlChars));
-                            SetSqlChars_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlChars(i), 0);
-                            break;
-                        case SqlDbType.Real:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Single));
-                            SetSingle_Unchecked(sink, setters, i, reader.GetFloat(i));
-                            break;
-                        case SqlDbType.UniqueIdentifier:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Guid));
-                            SetGuid_Unchecked(sink, setters, i, reader.GetGuid(i));
-                            break;
-                        case SqlDbType.SmallDateTime:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], reader.GetDateTime(i));
-                            break;
-                        case SqlDbType.SmallInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int16));
-                            SetInt16_Unchecked(sink, setters, i, reader.GetInt16(i));
-                            break;
-                        case SqlDbType.SmallMoney:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlMoney));
-                            SetSqlMoney_Checked(sink, setters, i, metaData[i], reader.GetSqlMoney(i));
-                            break;
-                        case SqlDbType.Text:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlChars));
-                            SetSqlChars_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlChars(i), 0);
-                            break;
-                        case SqlDbType.Timestamp:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetSqlBytes_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlBytes(i), 0);
-                            break;
-                        case SqlDbType.TinyInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Byte));
-                            SetByte_Unchecked(sink, setters, i, reader.GetByte(i));
-                            break;
-                        case SqlDbType.VarBinary:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetSqlBytes_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlBytes(i), 0);
-                            break;
-                        case SqlDbType.VarChar:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.String));
-                            SetSqlChars_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlChars(i), 0);
-                            break;
-                        case SqlDbType.Xml:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlXml));
-                            SetSqlXml_Unchecked(sink, setters, i, reader.GetSqlXml(i));
-                            break;
-                        case SqlDbType.Variant:
-                            object o = reader.GetSqlValue(i);
-                            ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCode(o);
-                            SetCompatibleValue(sink, setters, i, metaData[i], o, typeCode, 0);
-                            break;
-
-                        case SqlDbType.Udt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetSqlBytes_LengthChecked(sink, setters, i, metaData[i], reader.GetSqlBytes(i), 0);
-                            break;
-
-                        default:
-                            // In order for us to get here we would have to have an
-                            // invalid instance of SqlDbType, or one would have to add
-                            // new member to SqlDbType without adding a case in this
-                            // switch, hence the assert.
-                            Debug.Fail("unsupported DbType:" + metaData[i].SqlDbType.ToString());
-                            throw ADP.NotSupported();
-                    }
-                }
-            }
-        }
-
-        // Copy multiple fields from reader to SmiTypedGetterSetter
-        //  Supports V200 code path, without damaging backward compat for V100 code.
-        //  Main differences are supporting DbDataReader, and for binary, character, decimal and Udt types.
-        //  Assumes caller enforces that reader and setter metadata are compatible
-        internal static void FillCompatibleSettersFromReader(SmiEventSink_Default sink, SmiTypedGetterSetter setters, IList<SmiExtendedMetaData> metaData, DbDataReader reader)
-        {
-            for (int i = 0; i < metaData.Count; i++)
-            {
-                if (reader.IsDBNull(i))
-                {
-                    ValueUtilsSmi.SetDBNull_Unchecked(sink, setters, i);
-                }
-                else
-                {
-                    switch (metaData[i].SqlDbType)
-                    {
-                        case SqlDbType.BigInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int64));
-                            SetInt64_Unchecked(sink, setters, i, reader.GetInt64(i));
-                            break;
-                        case SqlDbType.Binary:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.ByteArray));
-                            SetBytes_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.Bit:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Boolean));
-                            SetBoolean_Unchecked(sink, setters, i, reader.GetBoolean(i));
-                            break;
-                        case SqlDbType.Char:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.CharArray));
-                            SetCharsOrString_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.DateTime:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], reader.GetDateTime(i));
-                            break;
-                        case SqlDbType.Decimal:
-                            { // block to scope sqlReader local to avoid conflicts
-                                Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlDecimal));
-                                // Support full fidelity for SqlDataReader
-                                SqlDataReader sqlReader = reader as SqlDataReader;
-                                if (null != sqlReader)
-                                {
-                                    SetSqlDecimal_Unchecked(sink, setters, i, sqlReader.GetSqlDecimal(i));
-                                }
-                                else
-                                {
-                                    SetSqlDecimal_Unchecked(sink, setters, i, new SqlDecimal(reader.GetDecimal(i)));
-                                }
-                            }
-                            break;
-                        case SqlDbType.Float:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Double));
-                            SetDouble_Unchecked(sink, setters, i, reader.GetDouble(i));
-                            break;
-                        case SqlDbType.Image:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.ByteArray));
-                            SetBytes_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.Int:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int32));
-                            SetInt32_Unchecked(sink, setters, i, reader.GetInt32(i));
-                            break;
-                        case SqlDbType.Money:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlMoney));
-                            SetSqlMoney_Checked(sink, setters, i, metaData[i], new SqlMoney(reader.GetDecimal(i)));
-                            break;
-                        case SqlDbType.NChar:
-                        case SqlDbType.NText:
-                        case SqlDbType.NVarChar:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.CharArray));
-                            SetCharsOrString_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.Real:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Single));
-                            SetSingle_Unchecked(sink, setters, i, reader.GetFloat(i));
-                            break;
-                        case SqlDbType.UniqueIdentifier:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Guid));
-                            SetGuid_Unchecked(sink, setters, i, reader.GetGuid(i));
-                            break;
-                        case SqlDbType.SmallDateTime:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], reader.GetDateTime(i));
-                            break;
-                        case SqlDbType.SmallInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int16));
-                            SetInt16_Unchecked(sink, setters, i, reader.GetInt16(i));
-                            break;
-                        case SqlDbType.SmallMoney:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlMoney));
-                            SetSqlMoney_Checked(sink, setters, i, metaData[i], new SqlMoney(reader.GetDecimal(i)));
-                            break;
-                        case SqlDbType.Text:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.CharArray));
-                            SetCharsOrString_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.Timestamp:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.ByteArray));
-                            SetBytes_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.TinyInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Byte));
-                            SetByte_Unchecked(sink, setters, i, reader.GetByte(i));
-                            break;
-                        case SqlDbType.VarBinary:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.ByteArray));
-                            SetBytes_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.VarChar:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.String));
-                            SetCharsOrString_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-                        case SqlDbType.Xml:
-                            {
-                                Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlXml));
-                                SqlDataReader sqlReader = reader as SqlDataReader;
-                                if (null != sqlReader)
-                                {
-                                    SetSqlXml_Unchecked(sink, setters, i, sqlReader.GetSqlXml(i));
-                                }
-                                else
-                                {
-                                    SetBytes_FromReader(sink, setters, i, metaData[i], reader, 0);
-                                }
-                            }
-                            break;
-                        case SqlDbType.Variant:
-                            {  // block to scope sqlReader local and avoid conflicts
-                                // Support better options for SqlDataReader
-                                SqlDataReader sqlReader = reader as SqlDataReader;
-                                SqlBuffer.StorageType storageType = SqlBuffer.StorageType.Empty;
-                                object o;
-                                if (null != sqlReader)
-                                {
-                                    o = sqlReader.GetSqlValue(i);
-                                    storageType = sqlReader.GetVariantInternalStorageType(i);
-                                }
-                                else
-                                {
-                                    o = reader.GetValue(i);
-                                }
-                                ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(metaData[i].SqlDbType, metaData[i].IsMultiValued, o, null);
-                                if ((storageType == SqlBuffer.StorageType.DateTime2) || (storageType == SqlBuffer.StorageType.Date))
-                                    SetCompatibleValueV200(sink, setters, i, metaData[i], o, typeCode, 0, 0, null, storageType);
-                                else
-                                    SetCompatibleValueV200(sink, setters, i, metaData[i], o, typeCode, 0, 0, null);
-                            }
-                            break;
-
-                        case SqlDbType.Udt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.ByteArray));
-                            // Skip serialization for Udt types.
-                            SetBytes_FromReader(sink, setters, i, metaData[i], reader, 0);
-                            break;
-
-                        // SqlDbType.Structured should have been caught before this point for TVPs.  SUDTs will still need to implement.
-
-                        case SqlDbType.Date:
-                        case SqlDbType.DateTime2:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], reader.GetDateTime(i));
-                            break;
-                        case SqlDbType.Time:
-                            { // block to scope sqlReader local and avoid conflicts
-                                Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.TimeSpan));
-                                SqlDataReader sqlReader = reader as SqlDataReader;
-                                TimeSpan ts;
-                                if (null != sqlReader)
-                                {
-                                    ts = sqlReader.GetTimeSpan(i);
-                                }
-                                else
-                                {
-                                    ts = (TimeSpan)reader.GetValue(i);
-                                }
-                                SetTimeSpan_Checked(sink, setters, i, metaData[i], ts);
-                            }
-                            break;
-                        case SqlDbType.DateTimeOffset:
-                            { // block to scope sqlReader local and avoid conflicts
-                                Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTimeOffset));
-                                SqlDataReader sqlReader = reader as SqlDataReader;
-                                DateTimeOffset dto;
-                                if (null != sqlReader)
-                                {
-                                    dto = sqlReader.GetDateTimeOffset(i);
-                                }
-                                else
-                                {
-                                    dto = (DateTimeOffset)reader.GetValue(i);
-                                }
-                                SetDateTimeOffset_Unchecked(sink, setters, i, dto);
-                            }
-                            break;
-
-                        default:
-                            // In order for us to get here we would have to have an
-                            // invalid instance of SqlDbType, or one would have to add
-                            // new member to SqlDbType without adding a case in this
-                            // switch, hence the assert.
-                            Debug.Fail("unsupported DbType:" + metaData[i].SqlDbType.ToString());
-                            throw ADP.NotSupported();
-                    }
-                }
-            }
-        }
-
-
-        internal static void FillCompatibleSettersFromRecord(SmiEventSink_Default sink, SmiTypedGetterSetter setters, SmiMetaData[] metaData, SqlDataRecord record, SmiDefaultFieldsProperty useDefaultValues)
-        {
-            for (int i = 0; i < metaData.Length; ++i)
-            {
-                if (null != useDefaultValues && useDefaultValues[i])
-                {
-                    continue;
-                }
-                if (record.IsDBNull(i))
-                {
-                    ValueUtilsSmi.SetDBNull_Unchecked(sink, setters, i);
-                }
-                else
-                {
-                    switch (metaData[i].SqlDbType)
-                    {
-                        case SqlDbType.BigInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int64));
-                            SetInt64_Unchecked(sink, setters, i, record.GetInt64(i));
-                            break;
-                        case SqlDbType.Binary:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetBytes_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.Bit:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Boolean));
-                            SetBoolean_Unchecked(sink, setters, i, record.GetBoolean(i));
-                            break;
-                        case SqlDbType.Char:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlChars));
-                            SetChars_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.DateTime:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], record.GetDateTime(i));
-                            break;
-                        case SqlDbType.Decimal:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlDecimal));
-                            SetSqlDecimal_Unchecked(sink, setters, i, record.GetSqlDecimal(i));
-                            break;
-                        case SqlDbType.Float:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Double));
-                            SetDouble_Unchecked(sink, setters, i, record.GetDouble(i));
-                            break;
-                        case SqlDbType.Image:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetBytes_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.Int:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int32));
-                            SetInt32_Unchecked(sink, setters, i, record.GetInt32(i));
-                            break;
-                        case SqlDbType.Money:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlMoney));
-                            SetSqlMoney_Unchecked(sink, setters, i, metaData[i], record.GetSqlMoney(i));
-                            break;
-                        case SqlDbType.NChar:
-                        case SqlDbType.NText:
-                        case SqlDbType.NVarChar:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlChars));
-                            SetChars_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.Real:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Single));
-                            SetSingle_Unchecked(sink, setters, i, record.GetFloat(i));
-                            break;
-                        case SqlDbType.UniqueIdentifier:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Guid));
-                            SetGuid_Unchecked(sink, setters, i, record.GetGuid(i));
-                            break;
-                        case SqlDbType.SmallDateTime:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], record.GetDateTime(i));
-                            break;
-                        case SqlDbType.SmallInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Int16));
-                            SetInt16_Unchecked(sink, setters, i, record.GetInt16(i));
-                            break;
-                        case SqlDbType.SmallMoney:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlMoney));
-                            SetSqlMoney_Checked(sink, setters, i, metaData[i], record.GetSqlMoney(i));
-                            break;
-                        case SqlDbType.Text:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlChars));
-                            SetChars_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.Timestamp:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetBytes_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.TinyInt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.Byte));
-                            SetByte_Unchecked(sink, setters, i, record.GetByte(i));
-                            break;
-                        case SqlDbType.VarBinary:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetBytes_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.VarChar:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.String));
-                            SetChars_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.Xml:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlXml));
-                            SetSqlXml_Unchecked(sink, setters, i, record.GetSqlXml(i));    // perf improvement?
-                            break;
-                        case SqlDbType.Variant:
-                            object o = record.GetSqlValue(i);
-                            ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCode(o);
-                            SetCompatibleValueV200(sink, setters, i, metaData[i], o, typeCode, 0, -1 /* no length restriction */, null /* no peekahead */);
-                            break;
-                        case SqlDbType.Udt:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.SqlBytes));
-                            SetBytes_FromRecord(sink, setters, i, metaData[i], record, 0);
-                            break;
-                        case SqlDbType.Date:
-                        case SqlDbType.DateTime2:
-                            Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTime));
-                            SetDateTime_Checked(sink, setters, i, metaData[i], record.GetDateTime(i));
-                            break;
-                        case SqlDbType.Time:
-                            { // block to scope sqlReader local and avoid conflicts
-                                Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.TimeSpan));
-                                SqlDataRecord sqlRecord = record as SqlDataRecord;
-                                TimeSpan ts;
-                                if (null != sqlRecord)
-                                {
-                                    ts = sqlRecord.GetTimeSpan(i);
-                                }
-                                else
-                                {
-                                    ts = (TimeSpan)record.GetValue(i);
-                                }
-                                SetTimeSpan_Checked(sink, setters, i, metaData[i], ts);
-                            }
-                            break;
-                        case SqlDbType.DateTimeOffset:
-                            { // block to scope sqlReader local and avoid conflicts
-                                Debug.Assert(CanAccessSetterDirectly(metaData[i], ExtendedClrTypeCode.DateTimeOffset));
-                                SqlDataRecord sqlRecord = record as SqlDataRecord;
-                                DateTimeOffset dto;
-                                if (null != sqlRecord)
-                                {
-                                    dto = sqlRecord.GetDateTimeOffset(i);
-                                }
-                                else
-                                {
-                                    dto = (DateTimeOffset)record.GetValue(i);
-                                }
-                                SetDateTimeOffset_Unchecked(sink, setters, i, dto);
-                            }
-                            break;
-
-                        default:
-                            Debug.Fail("unsupported DbType:" + metaData[i].SqlDbType.ToString());
-                            throw ADP.NotSupported();
-                    }
-                }
-            }
-        }
-
-        // spool a Stream into a scratch stream from the Smi interface and return it as a Stream
-        internal static Stream CopyIntoNewSmiScratchStream(Stream source, SmiEventSink_Default sink)
-        {
-            Stream dest = new MemoryStream();
-
-            int chunkSize;
-            if (source.CanSeek && __maxByteChunkSize > source.Length)
-            {
-                chunkSize = unchecked((int)source.Length);  // unchecked cast is safe due to check on line above
-            }
-            else
-            {
-                chunkSize = __maxByteChunkSize;
-            }
-
-            byte[] copyBuffer = new byte[chunkSize];
-            int bytesRead;
-            while (0 != (bytesRead = source.Read(copyBuffer, 0, chunkSize)))
-            {
-                dest.Write(copyBuffer, 0, bytesRead);
-            }
-            dest.Flush();
-
-            //  Need to re-wind scratch stream to beginning before returning
-            dest.Seek(0, SeekOrigin.Begin);
-
-            return dest;
-        }
-
-        //
-        //  Common utility code to get lengths correct for trimming
-        //
-        private static object GetUdt_LengthChecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            object result;
-            if (IsDBNull_Unchecked(sink, getters, ordinal))
-            {
-                Type t = metaData.Type;
-                Debug.Assert(t != null, "Unexpected null of udtType on GetUdt_LengthChecked!");
-                result = t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, Array.Empty<object>(), CultureInfo.InvariantCulture);
-                Debug.Assert(result != null);
-            }
-            else
-            {
-                // Note: do not need to copy getter stream, since it will not be used beyond
-                //  deserialization (valid lifetime of getters is limited).
-                Stream s = new SmiGettersStream(sink, getters, ordinal, metaData);
-                result = SerializationHelperSql9.Deserialize(s, metaData.Type);
-            }
-            return result;
-        }
-
-        private static decimal GetDecimal_PossiblyMoney(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData)
-        {
-            if (SqlDbType.Decimal == metaData.SqlDbType)
-            {
-                return GetSqlDecimal_Unchecked(sink, getters, ordinal).Value;
-            }
-            else
-            {
-                Debug.Assert(SqlDbType.Money == metaData.SqlDbType ||
-                                SqlDbType.SmallMoney == metaData.SqlDbType,
-                            "Unexpected sqldbtype=" + metaData.SqlDbType);
-                return GetSqlMoney_Unchecked(sink, getters, ordinal).Value;
-            }
-        }
-
-        private static void SetDecimal_PossiblyMoney(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, decimal value)
-        {
-            if (SqlDbType.Decimal == metaData.SqlDbType || SqlDbType.Variant == metaData.SqlDbType)
-            {
-                SetDecimal_Unchecked(sink, setters, ordinal, value);
-            }
-            else
-            {
-                Debug.Assert(SqlDbType.Money == metaData.SqlDbType ||
-                                SqlDbType.SmallMoney == metaData.SqlDbType,
-                            "Unexpected sqldbtype=" + metaData.SqlDbType);
-                SetSqlMoney_Checked(sink, setters, ordinal, metaData, new SqlMoney(value));
-            }
-        }
-
-        // Hard coding smalldatetime limits...
-        private static readonly DateTime s_dtSmallMax = new DateTime(2079, 06, 06, 23, 59, 29, 998);
-        private static readonly DateTime s_dtSmallMin = new DateTime(1899, 12, 31, 23, 59, 29, 999);
-        private static void VerifyDateTimeRange(SqlDbType dbType, DateTime value)
-        {
-            if (SqlDbType.SmallDateTime == dbType && (s_dtSmallMax < value || s_dtSmallMin > value))
-            {
-                throw ADP.InvalidMetaDataValue();
-            }
-        }
-
-        private static readonly TimeSpan s_timeMin = TimeSpan.Zero;
-        private static readonly TimeSpan s_timeMax = new TimeSpan(TimeSpan.TicksPerDay - 1);
-        private static void VerifyTimeRange(SqlDbType dbType, TimeSpan value)
-        {
-            if (SqlDbType.Time == dbType && (s_timeMin > value || value > s_timeMax))
-            {
-                throw ADP.InvalidMetaDataValue();
-            }
-        }
-
-        private static void SetDateTime_Checked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, DateTime value)
-        {
-            VerifyDateTimeRange(metaData.SqlDbType, value);
-            SetDateTime_Unchecked(sink, setters, ordinal, ((SqlDbType.Date == metaData.SqlDbType) ? value.Date : value));
-        }
-
-        private static void SetTimeSpan_Checked(SmiEventSink_Default sink, SmiTypedGetterSetter setters, int ordinal, SmiMetaData metaData, TimeSpan value)
-        {
-            VerifyTimeRange(metaData.SqlDbType, value);
-            SetTimeSpan_Unchecked(sink, setters, ordinal, value);
-        }
-
-        private static void SetSqlDateTime_Checked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlDateTime value)
-        {
-            if (!value.IsNull)
-            {
-                VerifyDateTimeRange(metaData.SqlDbType, value.Value);
-            }
-            SetSqlDateTime_Unchecked(sink, setters, ordinal, value);
-        }
-
-        private static void SetDateTime2_Checked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, DateTime value)
-        {
-            VerifyDateTimeRange(metaData.SqlDbType, value);
-            SetDateTime2_Unchecked(sink, setters, ordinal, metaData, value);
-        }
-
-        private static void SetDate_Checked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, DateTime value)
-        {
-            VerifyDateTimeRange(metaData.SqlDbType, value);
-            SetDate_Unchecked(sink, setters, ordinal, metaData, value);
-        }
-
-        private static void SetSqlMoney_Checked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlMoney value)
-        {
-            if (!value.IsNull && SqlDbType.SmallMoney == metaData.SqlDbType)
-            {
-                decimal decimalValue = value.Value;
-                if (TdsEnums.SQL_SMALL_MONEY_MIN > decimalValue || TdsEnums.SQL_SMALL_MONEY_MAX < decimalValue)
-                {
-                    throw SQL.MoneyOverflow(decimalValue.ToString(CultureInfo.InvariantCulture));
-                }
-            }
-            SetSqlMoney_Unchecked(sink, setters, ordinal, metaData, value);
-        }
-
-        private static void SetByteArray_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, byte[] buffer, int offset)
-        {
-            int length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, buffer.Length, offset, buffer.Length - offset);
-            Debug.Assert(length >= 0, "buffer.Length was invalid!");
-            SetByteArray_Unchecked(sink, setters, ordinal, buffer, offset, length);
-        }
-
-        private static void SetCharArray_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, char[] buffer, int offset)
-        {
-            int length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, buffer.Length, offset, buffer.Length - offset);
-            Debug.Assert(length >= 0, "buffer.Length was invalid!");
-            SetCharArray_Unchecked(sink, setters, ordinal, buffer, offset, length);
-        }
-
-        private static void SetSqlBinary_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlBinary value, int offset)
-        {
-            int length = 0;
-            if (!value.IsNull)
-            {
-                length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, value.Length, offset, value.Length - offset);
-                Debug.Assert(length >= 0, "value.Length was invalid!");
-            }
-            SetSqlBinary_Unchecked(sink, setters, ordinal, value, offset, length);
-        }
-
-        private static void SetBytes_FromRecord(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlDataRecord record, int offset)
-        {
-            int length = 0;
-
-            // Deal with large values by sending bufferLength of NoLengthLimit (== assume
-            //  CheckXetParameters will ignore requested-length checks in this case
-            long bufferLength = record.GetBytes(ordinal, 0, null, 0, 0);
-            if (bufferLength > int.MaxValue)
-            {
-                bufferLength = NoLengthLimit;
-            }
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, checked((int)bufferLength), offset, checked((int)bufferLength));
-
-            int chunkSize;
-            if (length > __maxByteChunkSize || length < 0)
-            {
-                chunkSize = __maxByteChunkSize;
-            }
-            else
-            {
-                chunkSize = checked((int)length);
-            }
-
-            byte[] buffer = new byte[chunkSize];
-            long bytesRead;
-            long bytesWritten = 1;  // prime value to get into write loop
-            long currentOffset = offset;
-            long lengthWritten = 0;
-
-            while ((length < 0 || lengthWritten < length) &&
-                    0 != (bytesRead = record.GetBytes(ordinal, currentOffset, buffer, 0, chunkSize)) &&
-                    0 != bytesWritten)
-            {
-                bytesWritten = setters.SetBytes(sink, ordinal, currentOffset, buffer, 0, checked((int)bytesRead));
-                sink.ProcessMessagesAndThrow();
-                checked { currentOffset += bytesWritten; }
-                checked { lengthWritten += bytesWritten; }
-            }
-
-            // Make sure to trim any left-over data
-            setters.SetBytesLength(sink, ordinal, currentOffset);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetBytes_FromReader(SmiEventSink_Default sink, SmiTypedGetterSetter setters, int ordinal, SmiMetaData metaData, DbDataReader reader, int offset)
-        {
-            int length = 0;
-
-            // Deal with large values by sending bufferLength of NoLengthLimit (== assume
-            //  CheckXetParameters will ignore requested-length checks in this case)
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, NoLengthLimit /* buffer length */, offset, NoLengthLimit /* requested length */ );
-
-            // Use fixed chunk size for all cases to avoid inquiring from reader.
-            int chunkSize = __maxByteChunkSize;
-
-            byte[] buffer = new byte[chunkSize];
-            long bytesRead;
-            long bytesWritten = 1;  // prime value to get into write loop
-            long currentOffset = offset;
-            long lengthWritten = 0;
-
-            while ((length < 0 || lengthWritten < length) &&
-                    0 != (bytesRead = reader.GetBytes(ordinal, currentOffset, buffer, 0, chunkSize)) &&
-                    0 != bytesWritten)
-            {
-                bytesWritten = setters.SetBytes(sink, ordinal, currentOffset, buffer, 0, checked((int)bytesRead));
-                sink.ProcessMessagesAndThrow();
-                checked { currentOffset += bytesWritten; }
-                checked { lengthWritten += bytesWritten; }
-            }
-
-            // Make sure to trim any left-over data (remember to trim at end of offset, not just the amount written
-            setters.SetBytesLength(sink, ordinal, currentOffset);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlBytes_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlBytes value, int offset)
-        {
-            int length = 0;
-            if (!value.IsNull)
-            {
-                // Deal with large values by sending bufferLength of NoLengthLimit (== assume
-                //  CheckXetParameters will ignore requested-length checks in this case
-                long bufferLength = value.Length;
-                if (bufferLength > int.MaxValue)
-                {
-                    bufferLength = NoLengthLimit;
-                }
-                length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, checked((int)bufferLength), offset, checked((int)bufferLength));
-            }
-            SetSqlBytes_Unchecked(sink, setters, ordinal, value, 0, length);
-        }
-
-        private static void SetChars_FromRecord(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlDataRecord record, int offset)
-        {
-            int length = 0;
-
-            // Deal with large values by sending bufferLength of NoLengthLimit
-            //  CheckXetParameters will ignore length checks in this case
-            long bufferLength = record.GetChars(ordinal, 0, null, 0, 0);
-            if (bufferLength > int.MaxValue)
-            {
-                bufferLength = NoLengthLimit;
-            }
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, checked((int)bufferLength), offset, checked((int)bufferLength - offset));
-
-            int chunkSize;
-            if (length > __maxCharChunkSize || length < 0)
-            {
-                if (MetaDataUtilsSmi.IsAnsiType(metaData.SqlDbType))
-                {
-                    chunkSize = __maxByteChunkSize;
-                }
-                else
-                {
-                    chunkSize = __maxCharChunkSize;
-                }
-            }
-            else
-            {
-                chunkSize = checked((int)length);
-            }
-
-            char[] buffer = new char[chunkSize];
-            long charsRead;
-            long charsWritten = 1;  // prime value to get into write loop
-            long currentOffset = offset;
-            long lengthWritten = 0;
-
-            while ((length < 0 || lengthWritten < length) &&
-                    0 != (charsRead = record.GetChars(ordinal, currentOffset, buffer, 0, chunkSize)) &&
-                    0 != charsWritten)
-            {
-                charsWritten = setters.SetChars(sink, ordinal, currentOffset, buffer, 0, checked((int)charsRead));
-                sink.ProcessMessagesAndThrow();
-                checked { currentOffset += charsWritten; }
-                checked { lengthWritten += charsWritten; }
-            }
-
-            // Make sure to trim any left-over data
-            setters.SetCharsLength(sink, ordinal, currentOffset);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        // Transfer a character value from a reader when we're not sure which GetXXX method the reader will support.
-        //  Prefers to chunk data via GetChars, but falls back to GetString if that fails.
-        //  Mainly put in place because DataTableReader doesn't support GetChars on string columns, but others could fail too...
-        private static void SetCharsOrString_FromReader(SmiEventSink_Default sink, SmiTypedGetterSetter setters, int ordinal, SmiMetaData metaData, DbDataReader reader, int offset)
-        {
-            bool success = false;
-            try
-            {
-                SetChars_FromReader(sink, setters, ordinal, metaData, reader, offset);
-                success = true;
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-            }
-
-            if (!success)
-            {
-                SetString_FromReader(sink, setters, ordinal, metaData, reader, offset);
-            }
-        }
-
-        // Use chunking via SetChars to transfer a value from a reader to a gettersetter
-        private static void SetChars_FromReader(SmiEventSink_Default sink, SmiTypedGetterSetter setters, int ordinal, SmiMetaData metaData, DbDataReader reader, int offset)
-        {
-            int length = 0;
-
-            // Deal with large values by sending bufferLength of NoLengthLimit (== assume
-            //  CheckXetParameters will ignore requested-length checks in this case)
-            length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, NoLengthLimit /* buffer length */, offset, NoLengthLimit /* requested length */ );
-
-            // Use fixed chunk size for all cases to avoid inquiring from reader.
-            int chunkSize;
-            if (MetaDataUtilsSmi.IsAnsiType(metaData.SqlDbType))
-            {
-                chunkSize = __maxByteChunkSize;
-            }
-            else
-            {
-                chunkSize = __maxCharChunkSize;
-            }
-
-            char[] buffer = new char[chunkSize];
-            long charsRead;
-            long charsWritten = 1;  // prime value to get into write loop
-            long currentOffset = offset;
-            long lengthWritten = 0;
-
-            while ((length < 0 || lengthWritten < length) &&
-                    0 != (charsRead = reader.GetChars(ordinal, currentOffset, buffer, 0, chunkSize)) &&
-                    0 != charsWritten)
-            {
-                charsWritten = setters.SetChars(sink, ordinal, currentOffset, buffer, 0, checked((int)charsRead));
-                sink.ProcessMessagesAndThrow();
-                checked { currentOffset += charsWritten; }
-                checked { lengthWritten += charsWritten; }
-            }
-
-            // Make sure to trim any left-over data (remember to trim at end of offset, not just the amount written
-            setters.SetCharsLength(sink, ordinal, currentOffset);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetString_FromReader(SmiEventSink_Default sink, SmiTypedGetterSetter setters, int ordinal, SmiMetaData metaData, DbDataReader reader, int offset)
-        {
-            string value = reader.GetString(ordinal);
-            int length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, value.Length, 0, NoLengthLimit /* buffer */, offset, NoLengthLimit /* request */);
-
-            setters.SetString(sink, ordinal, value, offset, length);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlChars_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlChars value, int offset)
-        {
-            int length = 0;
-            if (!value.IsNull)
-            {
-                // Deal with large values by sending bufferLength of NoLengthLimit
-                //  CheckXetParameters will ignore length checks in this case
-                long bufferLength = value.Length;
-                if (bufferLength > int.MaxValue)
-                {
-                    bufferLength = NoLengthLimit;
-                }
-                length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, checked((int)bufferLength), offset, checked((int)bufferLength - offset));
-            }
-            SetSqlChars_Unchecked(sink, setters, ordinal, value, 0, length);
-        }
-
-        private static void SetSqlString_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlString value, int offset)
-        {
-            if (value.IsNull)
-            {
-                SetDBNull_Unchecked(sink, setters, ordinal);
-            }
-            else
-            {
-                string stringValue = value.Value;
-                int length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, stringValue.Length, offset, stringValue.Length - offset);
-                Debug.Assert(length >= 0, "value.Length was invalid!");
-                SetSqlString_Unchecked(sink, setters, ordinal, metaData, value, offset, length);
-            }
-        }
-
-        private static void SetString_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, string value, int offset)
-        {
-            int length = CheckXetParameters(metaData.SqlDbType, metaData.MaxLength, NoLengthLimit /* actual */, 0, value.Length, offset, checked(value.Length - offset));
-            Debug.Assert(length >= 0, "value.Length was invalid!");
-            SetString_Unchecked(sink, setters, ordinal, value, offset, length);
-        }
-
-        private static void SetUdt_LengthChecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, object value)
-        {
-            if (ADP.IsNull(value))
-            {
-                setters.SetDBNull(sink, ordinal);
-                sink.ProcessMessagesAndThrow();
-            }
-            else
-            {
-                Stream target = new SmiSettersStream(sink, setters, ordinal, metaData);
-                SerializationHelperSql9.Serialize(target, value);
-            }
-        }
-
-
-        //
-        //  Semantics support routines
-        //
-
-        private static void ThrowIfInvalidSetterAccess(SmiMetaData metaData, ExtendedClrTypeCode setterTypeCode)
-        {
-            if (!CanAccessSetterDirectly(metaData, setterTypeCode))
-            {
-                throw ADP.InvalidCast();
-            }
-        }
-
-        private static void ThrowIfITypedGettersIsNull(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            if (IsDBNull_Unchecked(sink, getters, ordinal))
-            {
-                throw SQL.SqlNullValue();
-            }
-        }
-
-        private static bool CanAccessGetterDirectly(SmiMetaData metaData, ExtendedClrTypeCode setterTypeCode)
-        {
-            // Make sure no-one adds new ExtendedType, nor SqlDbType without updating this file!
-            Debug.Assert(ExtendedClrTypeCode.First == 0 && (int)ExtendedClrTypeCode.Last == s_canAccessGetterDirectly.GetLength(0) - 1, "ExtendedClrTypeCodes does not match with __canAccessGetterDirectly");
-            Debug.Assert(SqlDbType.BigInt == 0 && (int)SqlDbType.DateTimeOffset == s_canAccessGetterDirectly.GetLength(1) - 1, "SqlDbType does not match with __canAccessGetterDirectly");
-            Debug.Assert(ExtendedClrTypeCode.First <= setterTypeCode && ExtendedClrTypeCode.Last >= setterTypeCode);
-            Debug.Assert(SqlDbType.BigInt <= metaData.SqlDbType && SqlDbType.DateTimeOffset >= metaData.SqlDbType);
-
-            bool returnValue = s_canAccessGetterDirectly[(int)setterTypeCode, (int)metaData.SqlDbType];
-
-            // Additional restrictions to distinguish TVPs and Structured UDTs
-            if (returnValue &&
-                   (ExtendedClrTypeCode.DataTable == setterTypeCode ||
-                    ExtendedClrTypeCode.DbDataReader == setterTypeCode ||
-                    ExtendedClrTypeCode.IEnumerableOfSqlDataRecord == setterTypeCode))
-            {
-                returnValue = metaData.IsMultiValued;
-            }
-
-            return returnValue;
-        }
-
-        private static bool CanAccessSetterDirectly(SmiMetaData metaData, ExtendedClrTypeCode setterTypeCode)
-        {
-            // Make sure no-one adds new ExtendedType, nor SqlDbType without updating this file!
-            Debug.Assert(ExtendedClrTypeCode.First == 0 && (int)ExtendedClrTypeCode.Last == s_canAccessSetterDirectly.GetLength(0) - 1, "ExtendedClrTypeCodes does not match with __canAccessSetterDirectly");
-            Debug.Assert(SqlDbType.BigInt == 0 && (int)SqlDbType.DateTimeOffset == s_canAccessSetterDirectly.GetLength(1) - 1, "SqlDbType does not match with __canAccessSetterDirectly");
-            Debug.Assert(ExtendedClrTypeCode.First <= setterTypeCode && ExtendedClrTypeCode.Last >= setterTypeCode);
-            Debug.Assert(SqlDbType.BigInt <= metaData.SqlDbType && SqlDbType.DateTimeOffset >= metaData.SqlDbType);
-
-            bool returnValue = s_canAccessSetterDirectly[(int)setterTypeCode, (int)metaData.SqlDbType];
-
-            // Additional restrictions to distinguish TVPs and Structured UDTs
-            if (returnValue &&
-                   (ExtendedClrTypeCode.DataTable == setterTypeCode ||
-                    ExtendedClrTypeCode.DbDataReader == setterTypeCode ||
-                    ExtendedClrTypeCode.IEnumerableOfSqlDataRecord == setterTypeCode))
-            {
-                returnValue = metaData.IsMultiValued;
-            }
-
-            return returnValue;
-        }
-
-        private static long PositiveMin(long first, long second)
-        {
-            if (first < 0)
-            {
-                return second;
-            }
-
-            if (second < 0)
-            {
-                return first;
-            }
-
-            return Math.Min(first, second);
-        }
-
-        // Check Get Byte/Chars parameters, throw or adjust invalid values
-        private static int CheckXetParameters(
-                SqlDbType dbType,
-                long maxLength,
-                long actualLength,
-                long fieldOffset,
-                int bufferLength,
-                int bufferOffset,
-                int length)
-        {
-            if (0 > fieldOffset)
-                throw ADP.NegativeParameter(nameof(fieldOffset));
-
-            // if negative buffer index, throw
-            if (bufferOffset < 0)
-            {
-                throw ADP.InvalidDestinationBufferIndex(bufferLength, bufferOffset, nameof(bufferOffset));
-            }
-
-            // skip further length checks for LOB buffer lengths
-            if (bufferLength < 0)
-            {
-                length = checked((int)PositiveMin(length, PositiveMin(maxLength, actualLength)));
-                if (length < NoLengthLimit)
-                {
-                    length = NoLengthLimit;
-                }
-                return length;
-            }
-
-            // if bad buffer index, throw
-            if (bufferOffset > bufferLength)
-            {
-                throw ADP.InvalidDestinationBufferIndex(bufferLength, bufferOffset, nameof(bufferOffset));
-            }
-
-            // if there is not enough room in the buffer for data
-            if (checked(length + bufferOffset) > bufferLength)
-                throw ADP.InvalidBufferSizeOrIndex(length, bufferOffset);
-
-            if (length < 0)
-                throw ADP.InvalidDataLength(length);
-
-            if (0 <= actualLength && actualLength <= fieldOffset)
-            {
-                return 0;
-            }
-
-            // trim length against both bufferLength and actual or max length
-            //  (actual or max < 0 means don't trim against that value)
-            //  Note that parameter UDTs don't know the correct maxlength, so the back end does
-            //      the trimming.  Actual length should still be trimmed against here, though.
-            length = Math.Min(length, bufferLength - bufferOffset);
-
-            // special case for variants, since their maxLength is actually a bit bigger than
-            // the actual data length allowed.
-            if (SqlDbType.Variant == dbType)
-            {
-                length = Math.Min(length, TdsEnums.TYPE_SIZE_LIMIT);
-            }
-
-            Debug.Assert(0 > maxLength || 0 > actualLength ||
-                    maxLength >= actualLength, "Actual = " + actualLength + ", max = " + maxLength + ", sqldbtype=" + dbType);
-
-            if (0 <= actualLength)
-            {
-                // Length is guaranteed to be >= 0 coming in and actualLength >= fieldOffset, so this operation guarantees result >= 0
-                length = (int)Math.Min((long)length, actualLength - fieldOffset);
-                Debug.Assert(length >= 0, "result < 0, actualLength/fieldOffset problem?");
-            }
-            else if (SqlDbType.Udt != dbType && 0 <= maxLength)
-            {
-                length = (int)Math.Min((long)length, maxLength - fieldOffset);
-                Debug.Assert(length >= 0, "Result < 0, maxlen/fieldoffset problem?");
-            }
-
-            if (length < 0)
-            {
-                return 0;
-            }
-            else
-            {
-                return length;
-            }
-        }
-
-        //
-        // These tables are formal encoding of the "unchecked" method access rules for various types
-        //  The tables should only be accessed from the CanAccessXetterDirectly methods.
-        //
-
-        // A couple of private constants to increase the getter/setter access tables' contrast
-        private const bool X = true;
-        private const bool _ = false;
-
-        private static readonly bool[,] s_canAccessGetterDirectly = {
-            // SqlDbTypes as columns (abbreviated, but in order)
-            //  ExtendedClrTypeCodes as rows
-
-            //     BI, Bin, Bit, Ch, DT, Dec, Fl, Im, Int, Mny, NCh, NTx, NVC, Rl, UI, SDT, SI, SMn, Txt, TS, TI, VBn, VCh, Var, 24, Xml, 26, 27, 28, Udt, St, Dat, Tm, DT2, DTO
-            /*Bool*/
-         { _,  _,  X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Bool*/
-                                                                                                                                                                            /*Byte*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Byte*/
-                                                                                                                                                                            /*Char*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Char*/
-                                                                                                                                                                            /*DTime*/
-         { _,  _,  _, _, X, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  X, _, X, _, }, /*DateTime*/
-                                                                                                                                                                            /*DBNul*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*DBNull*/
-                                                                                                                                                                            /*Decim*/
-         { _,  _,  _, _, _, X, _, _, _, X, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Decimal*/
-                                                                                                                                                                            /*Doubl*/
-         { _,  _,  _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Double*/
-                                                                                                                                                                            /*Empty*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Empty*/
-                                                                                                                                                                            /*Int16*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Int16*/
-                                                                                                                                                                            /*Int32*/
-         { _,  _,  _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Int32*/
-                                                                                                                                                                            /*Int64*/
-         { X,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Int64*/
-                                                                                                                                                                            /*SByte*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SByte*/
-                                                                                                                                                                            /*Singl*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Single*/
-                                                                                                                                                                            /*Strng*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*String*/
-                                                                                                                                                                            /*UIn16*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*UInt16*/
-                                                                                                                                                                            /*UIn32*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*UInt32*/
-                                                                                                                                                                            /*UIn64*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*UInt64*/
-                                                                                                                                                                            /*Objct*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  X, _,  _, _, _, _, }, /*Object*/
-                                                                                                                                                                            /*BytAr*/
-         { _,  X,  _, X, _, _, _, X, _, _, X, X, X, _, _, _, _, _, X, X, _, X, X, _, _, X, _, _, _,  X, _,  _, _, _, _, }, /*ByteArray*/
-                                                                                                                                                                            /*ChrAr*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*CharArray*/
-                                                                                                                                                                            /*Guid*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Guid*/
-                                                                                                                                                                            /*SBin*/
-         { _,  X,  _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, X, _, X, _, _, _, _, _, _, _,  X, _,  _, _, _, _, }, /*SqlBinary*/
-                                                                                                                                                                            /*SBool*/
-         { _,  _,  X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlBoolean*/
-                                                                                                                                                                            /*SByte*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlByte*/
-                                                                                                                                                                            /*SDTme*/
-         { _,  _,  _, _, X, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  X, _, X, _, }, /*SqlDateTime*/
-                                                                                                                                                                            /*SDubl*/
-         { _,  _,  _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlDouble*/
-                                                                                                                                                                            /*SGuid*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlGuid*/
-                                                                                                                                                                            /*SIn16*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlInt16*/
-                                                                                                                                                                            /*SIn32*/
-         { _,  _,  _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlInt32*/
-                                                                                                                                                                            /*SIn64*/
-         { X,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlInt64*/
-                                                                                                                                                                            /*SMony*/
-         { _,  _,  _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlMoney*/
-                                                                                                                                                                            /*SDeci*/
-         { _,  _,  _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlDecimal*/
-                                                                                                                                                                            /*SSngl*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlSingle*/
-                                                                                                                                                                            /*SStrn*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlString*/
-                                                                                                                                                                            /*SChrs*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlChars*/
-                                                                                                                                                                            /*SByts*/
-         { _,  X,  _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, X, _, X, _, _, _, _, _, _, _,  X, _,  _, _, _, _, }, /*SqlBytes*/
-                                                                                                                                                                            /*SXml*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _,  _, _,  _, _, _, _, }, /*SqlXml*/
-                                                                                                                                                                            /*DTbl*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, X,  _, _, _, _, }, /*DataTable*/
-                                                                                                                                                                            /*Rdr */
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, X,  _, _, _, _, }, /*DbDataReader*/
-                                                                                                                                                                            /*EnSDR*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, X,  _, _, _, _, }, /*IEnurerable<SqlDataRecord>*/
-                                                                                                                                                                            /*TmSpn*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, X, _, _, }, /*TimeSpan*/
-                                                                                                                                                                            /*DTOst*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, X, }, /*DateTimeOffset*/
-                                                                                                                                                                            /*Strm */
-         { _,  X,  _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _,  X, _,  _, _, _, _, }, /*Stream*/
-                                                                                                                                                                            /*TxRdr*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*TextReader*/
-                                                                                                                                                                            /*XmlRd*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*XmlReader*/
-                                                                                                                                                                            //     BI, Bin, Bit, Ch, DT, Dec, Fl, Im, Int, Mny, NCh, NTx, NVC, Rl, UI, SDT, SI, SMn, Txt, TS, TI, VBn, VCh, Var, 24, Xml, 26, 27, 28, Udt, St, Dat, Tm, DT2, DTO
-        };
-
-        private static readonly bool[,] s_canAccessSetterDirectly = {
-            // Setters as columns (labels are abbreviated from ExtendedClrTypeCode names)
-            // SqlDbTypes as rows
-            //     BI, Bin, Bit, Ch, DT, Dec, Fl, Im, Int, Mny, NCh, NTx, NVC, Rl, UI, SDT, SI, SMn, Txt, TS, TI, VBn, VCh, Var, 24, Xml, 26, 27, 28, Udt, St, Dat, Tm, DT2, DTO
-            /*Bool*/
-         { _,  _,  X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Bool*/
-                                                                                                                                                                            /*Byte*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Byte*/
-                                                                                                                                                                            /*Char*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Char*/
-                                                                                                                                                                            /*DTime*/
-         { _,  _,  _, _, X, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  X, _, X, _, }, /*DateTime*/
-                                                                                                                                                                            /*DBNul*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*DBNull*/
-                                                                                                                                                                            /*Decim*/
-         { _,  _,  _, _, _, X, _, _, _, X, _, _, _, _, _, _, _, X, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Decimal*/
-                                                                                                                                                                            /*Doubl*/
-         { _,  _,  _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Double*/
-                                                                                                                                                                            /*Empty*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Empty*/
-                                                                                                                                                                            /*Int16*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Int16*/
-                                                                                                                                                                            /*Int32*/
-         { _,  _,  _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Int32*/
-                                                                                                                                                                            /*Int64*/
-         { X,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Int64*/
-                                                                                                                                                                            /*SByte*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SByte*/
-                                                                                                                                                                            /*Singl*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Single*/
-                                                                                                                                                                            /*Strng*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, X, _, X, _, _, _,  _, _,  _, _, _, _, }, /*String*/
-                                                                                                                                                                            /*UIn16*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*UInt16*/
-                                                                                                                                                                            /*UIn32*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*UInt32*/
-                                                                                                                                                                            /*UIn64*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*UInt64*/
-                                                                                                                                                                            /*Objct*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  X, _,  _, _, _, _, }, /*Object*/
-                                                                                                                                                                            /*BytAr*/
-         { _,  X,  _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, X, _, X, _, X, _, X, _, _, _,  X, _,  _, _, _, _, }, /*ByteArray*/
-                                                                                                                                                                            /*ChrAr*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*CharArray*/
-                                                                                                                                                                            /*Guid*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Guid*/
-                                                                                                                                                                            /*SBin*/
-         { _,  X,  _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, X, _, X, _, X, _, _, _, _, _,  X, _,  _, _, _, _, }, /*SqlBinary*/
-                                                                                                                                                                            /*SBool*/
-         { _,  _,  X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlBoolean*/
-                                                                                                                                                                            /*SByte*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlByte*/
-                                                                                                                                                                            /*SDTme*/
-         { _,  _,  _, _, X, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  X, _, X, _, }, /*SqlDateTime*/
-                                                                                                                                                                            /*SDubl*/
-         { _,  _,  _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlDouble*/
-                                                                                                                                                                            /*SGuid*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlGuid*/
-                                                                                                                                                                            /*SIn16*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlInt16*/
-                                                                                                                                                                            /*SIn32*/
-         { _,  _,  _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlInt32*/
-                                                                                                                                                                            /*SIn64*/
-         { X,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlInt64*/
-                                                                                                                                                                            /*SMony*/
-         { _,  _,  _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, X, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlMoney*/
-                                                                                                                                                                            /*SDeci*/
-         { _,  _,  _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlDecimal*/
-                                                                                                                                                                            /*SSngl*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlSingle*/
-                                                                                                                                                                            /*SStrn*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, X, _, X, _, _, _,  _, _,  _, _, _, _, }, /*SqlString*/
-                                                                                                                                                                            /*SChrs*/
-         { _,  _,  _, X, _, _, _, _, _, _, X, X, X, _, _, _, _, _, X, _, _, _, X, X, _, _, _, _, _,  _, _,  _, _, _, _, }, /*SqlChars*/
-                                                                                                                                                                            /*SByts*/
-         { _,  X,  _, _, _, _, _, X, _, _, _, _, _, _, _, _, _, _, _, X, _, X, _, X, _, _, _, _, _,  X, _,  _, _, _, _, }, /*SqlBytes*/
-                                                                                                                                                                            /*SXml*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, X, _, _, _,  _, _,  _, _, _, _, }, /*SqlXml*/
-                                                                                                                                                                            /*DTbl*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, X,  _, _, _, _, }, /*DataTable*/
-                                                                                                                                                                            /*Rdr */
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, X,  _, _, _, _, }, /*DbDataReader*/
-                                                                                                                                                                            /*EnSDR*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, X,  _, _, _, _, }, /*IEnurerable<SqlDataRecord>*/
-                                                                                                                                                                            /*TmSpn*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, X, _, _, }, /*TimeSpan*/
-                                                                                                                                                                            /*DTOst*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, X, }, /*DateTimeOffset*/
-                                                                                                                                                                            /*Strm */
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*Stream*/
-                                                                                                                                                                            /*TxRdr*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*TextReader*/
-                                                                                                                                                                            /*XmlRd*/
-         { _,  _,  _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _,  _, _,  _, _, _, _, }, /*XmlReader*/
-                                                                                                                                                                            //     BI, Bin, Bit, Ch, DT, Dec, Fl, Im, Int, Mny, NCh, NTx, NVC, Rl, UI, SDT, SI, SMn, Txt, TS, TI, VBn, VCh, Var, 24, Xml, 26, 27, 28, Udt, St, Dat, Tm, DT2, DTO
-        };
-
-
-        //
-        //  Private implementation of common mappings from a given type to corresponding Smi Getter/Setter
-        //      These classes do type validation, parameter limit validation, nor coercions
-        //
-        private static bool IsDBNull_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            bool result = getters.IsDBNull(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static bool GetBoolean_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            bool result = getters.GetBoolean(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static byte GetByte_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            byte result = getters.GetByte(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static byte[] GetByteArray_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            long length = getters.GetBytesLength(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            int len = checked((int)length);
-
-            byte[] buffer = new byte[len];
-            getters.GetBytes(sink, ordinal, 0, buffer, 0, len);
-            sink.ProcessMessagesAndThrow();
-            return buffer;
-        }
-
-        internal static int GetBytes_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-            Debug.Assert(ordinal >= 0, $"Invalid ordinal: {ordinal}");
-            Debug.Assert(sink != null, "Null SmiEventSink");
-            Debug.Assert(getters != null, "Null getters");
-            Debug.Assert(fieldOffset >= 0, $"Invalid field offset: {fieldOffset}");
-            Debug.Assert(buffer != null, "Null buffer");
-            Debug.Assert(bufferOffset >= 0 && length >= 0 && bufferOffset + length <= buffer.Length, $"Bad offset or length. bufferOffset: {bufferOffset}, length: {length}, buffer.Length{buffer.Length}");
-
-            int result = getters.GetBytes(sink, ordinal, fieldOffset, buffer, bufferOffset, length);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static long GetBytesLength_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            long result = getters.GetBytesLength(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-
-        private static char[] GetCharArray_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            long length = getters.GetCharsLength(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            int len = checked((int)length);
-
-            char[] buffer = new char[len];
-            getters.GetChars(sink, ordinal, 0, buffer, 0, len);
-            sink.ProcessMessagesAndThrow();
-            return buffer;
-        }
-
-        internal static int GetChars_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-            Debug.Assert(ordinal >= 0, $"Invalid ordinal: {ordinal}");
-            Debug.Assert(sink != null, "Null SmiEventSink");
-            Debug.Assert(getters != null, "Null getters");
-            Debug.Assert(fieldOffset >= 0, $"Invalid field offset: {fieldOffset}");
-            Debug.Assert(buffer != null, "Null buffer");
-            Debug.Assert(bufferOffset >= 0 && length >= 0 && bufferOffset + length <= buffer.Length, $"Bad offset or length. bufferOffset: {bufferOffset}, length: {length}, buffer.Length{buffer.Length}");
-
-            int result = getters.GetChars(sink, ordinal, fieldOffset, buffer, bufferOffset, length);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static long GetCharsLength_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            long result = getters.GetCharsLength(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static DateTime GetDateTime_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            DateTime result = getters.GetDateTime(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static DateTimeOffset GetDateTimeOffset_Unchecked(SmiEventSink_Default sink, SmiTypedGetterSetter getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            DateTimeOffset result = getters.GetDateTimeOffset(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static double GetDouble_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            double result = getters.GetDouble(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static Guid GetGuid_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            Guid result = getters.GetGuid(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static short GetInt16_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            short result = getters.GetInt16(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static int GetInt32_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            int result = getters.GetInt32(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static long GetInt64_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            long result = getters.GetInt64(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static float GetSingle_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            float result = getters.GetSingle(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static SqlBinary GetSqlBinary_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            byte[] buffer = GetByteArray_Unchecked(sink, getters, ordinal);
-            return new SqlBinary(buffer);
-        }
-
-        private static SqlDecimal GetSqlDecimal_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            SqlDecimal result = getters.GetSqlDecimal(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static SqlMoney GetSqlMoney_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            long temp = getters.GetInt64(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return SqlTypeWorkarounds.SqlMoneyCtor(temp, 1 /* ignored */ );
-        }
-
-        private static SqlXml GetSqlXml_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-
-            // Note: must make a copy of getter stream, since it will be used beyond
-            //  this method (valid lifetime of getters is limited).
-            Stream s = new SmiGettersStream(sink, getters, ordinal, SmiMetaData.DefaultXml);
-            Stream copy = ValueUtilsSmi.CopyIntoNewSmiScratchStream(s, sink);
-            SqlXml result = new SqlXml(copy);
-            return result;
-        }
-
-        private static string GetString_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            // Note: depending on different getters, the result string maybe truncated, e.g. for
-            // Inproc process, the getter is InProcRecordBuffer (implemented in SqlAcess), string will be
-            // truncated to 4000 (if length is more than 4000). If MemoryRecordBuffer getter is used, data
-            // is not truncated. Please refer VSDD 479655 for more detailed information regarding the string length.
-            string result = getters.GetString(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static TimeSpan GetTimeSpan_Unchecked(SmiEventSink_Default sink, SmiTypedGetterSetter getters, int ordinal)
-        {
-            Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
-
-            TimeSpan result = getters.GetTimeSpan(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static void SetBoolean_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, bool value)
-        {
-            setters.SetBoolean(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetByteArray_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, byte[] buffer, int bufferOffset, int length)
-        {
-            if (length > 0)
-            {
-                setters.SetBytes(sink, ordinal, 0, buffer, bufferOffset, length);
-                sink.ProcessMessagesAndThrow();
-            }
-            setters.SetBytesLength(sink, ordinal, length);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetStream_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metadata, StreamDataFeed feed)
-        {
-            long len = metadata.MaxLength;
-            byte[] buff = new byte[constBinBufferSize];
-            int nWritten = 0;
-            do
-            {
-                int nRead = 0;
-                int readSize = constBinBufferSize;
-                if (len > 0 && nWritten + readSize > len)
-                {
-                    readSize = (int)(len - nWritten);
-                }
-
-                Debug.Assert(readSize >= 0);
-
-                nRead = feed._source.Read(buff, 0, readSize);
-
-                if (nRead == 0)
-                {
-                    break;
-                }
-
-                setters.SetBytes(sink, ordinal, nWritten, buff, 0, nRead);
-                sink.ProcessMessagesAndThrow();
-
-                nWritten += nRead;
-            } while (len <= 0 || nWritten < len);
-
-            setters.SetBytesLength(sink, ordinal, nWritten);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetTextReader_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metadata, TextDataFeed feed)
-        {
-            long len = metadata.MaxLength;
-            char[] buff = new char[constTextBufferSize];
-            int nWritten = 0;
-            do
-            {
-                int nRead = 0;
-                int readSize = constTextBufferSize;
-                if (len > 0 && nWritten + readSize > len)
-                {
-                    readSize = (int)(len - nWritten);
-                }
-
-                Debug.Assert(readSize >= 0);
-
-                nRead = feed._source.Read(buff, 0, readSize);
-
-                if (nRead == 0)
-                {
-                    break;
-                }
-
-                setters.SetChars(sink, ordinal, nWritten, buff, 0, nRead);
-                sink.ProcessMessagesAndThrow();
-
-                nWritten += nRead;
-            } while (len <= 0 || nWritten < len);
-
-            setters.SetCharsLength(sink, ordinal, nWritten);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetByte_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, byte value)
-        {
-            setters.SetByte(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static int SetBytes_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            int result = setters.SetBytes(sink, ordinal, fieldOffset, buffer, bufferOffset, length);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static void SetCharArray_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, char[] buffer, int bufferOffset, int length)
-        {
-            if (length > 0)
-            {
-                setters.SetChars(sink, ordinal, 0, buffer, bufferOffset, length);
-                sink.ProcessMessagesAndThrow();
-            }
-            setters.SetCharsLength(sink, ordinal, length);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static int SetChars_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            int result = setters.SetChars(sink, ordinal, fieldOffset, buffer, bufferOffset, length);
-            sink.ProcessMessagesAndThrow();
-            return result;
-        }
-
-        private static void SetDBNull_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal)
-        {
-            setters.SetDBNull(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetDecimal_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, decimal value)
-        {
-            setters.SetSqlDecimal(sink, ordinal, new SqlDecimal(value));
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetDateTime_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, DateTime value)
-        {
-            setters.SetDateTime(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetDateTime2_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, DateTime value)
-        {
-            Debug.Assert(SqlDbType.Variant == metaData.SqlDbType, "Invalid type. This should be called only when the type is variant.");
-            setters.SetVariantMetaData(sink, ordinal, SmiMetaData.DefaultDateTime2);
-            setters.SetDateTime(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetDate_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, DateTime value)
-        {
-            Debug.Assert(SqlDbType.Variant == metaData.SqlDbType, "Invalid type. This should be called only when the type is variant.");
-            setters.SetVariantMetaData(sink, ordinal, SmiMetaData.DefaultDate);
-            setters.SetDateTime(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetTimeSpan_Unchecked(SmiEventSink_Default sink, SmiTypedGetterSetter setters, int ordinal, TimeSpan value)
-        {
-            setters.SetTimeSpan(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetDateTimeOffset_Unchecked(SmiEventSink_Default sink, SmiTypedGetterSetter setters, int ordinal, DateTimeOffset value)
-        {
-            setters.SetDateTimeOffset(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetDouble_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, double value)
-        {
-            setters.SetDouble(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetGuid_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, Guid value)
-        {
-            setters.SetGuid(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetInt16_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, short value)
-        {
-            setters.SetInt16(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetInt32_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, int value)
-        {
-            setters.SetInt32(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetInt64_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, long value)
-        {
-            setters.SetInt64(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSingle_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, float value)
-        {
-            setters.SetSingle(sink, ordinal, value);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlBinary_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlBinary value, int offset, int length)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                SetByteArray_Unchecked(sink, setters, ordinal, value.Value, offset, length);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlBoolean_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlBoolean value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetBoolean(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlByte_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlByte value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetByte(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        // note: length < 0 indicates write everything
-        private static void SetSqlBytes_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlBytes value, int offset, long length)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-                sink.ProcessMessagesAndThrow();
-            }
-            else
-            {
-                int chunkSize;
-                if (length > __maxByteChunkSize || length < 0)
-                {
-                    chunkSize = __maxByteChunkSize;
-                }
-                else
-                {
-                    chunkSize = checked((int)length);
-                }
-
-                byte[] buffer = new byte[chunkSize];
-                long bytesRead;
-                long bytesWritten = 1;  // prime value to get into write loop
-                long currentOffset = offset;
-                long lengthWritten = 0;
-
-                while ((length < 0 || lengthWritten < length) &&
-                        0 != (bytesRead = value.Read(currentOffset, buffer, 0, chunkSize)) &&
-                        0 != bytesWritten)
-                {
-                    bytesWritten = setters.SetBytes(sink, ordinal, currentOffset, buffer, 0, checked((int)bytesRead));
-                    sink.ProcessMessagesAndThrow();
-                    checked { currentOffset += bytesWritten; }
-                    checked { lengthWritten += bytesWritten; }
-                }
-
-                // Make sure to trim any left-over data
-                setters.SetBytesLength(sink, ordinal, currentOffset);
-                sink.ProcessMessagesAndThrow();
-            }
-        }
-
-        private static void SetSqlChars_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlChars value, int offset, int length)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-                sink.ProcessMessagesAndThrow();
-            }
-            else
-            {
-                int chunkSize;
-                if (length > __maxCharChunkSize || length < 0)
-                {
-                    chunkSize = __maxCharChunkSize;
-                }
-                else
-                {
-                    chunkSize = checked((int)length);
-                }
-
-                char[] buffer = new char[chunkSize];
-                long charsRead;
-                long charsWritten = 1;  // prime value to get into write loop
-                long currentOffset = offset;
-                long lengthWritten = 0;
-
-                while ((length < 0 || lengthWritten < length) &&
-                        0 != (charsRead = value.Read(currentOffset, buffer, 0, chunkSize)) &&
-                        0 != charsWritten)
-                {
-                    charsWritten = setters.SetChars(sink, ordinal, currentOffset, buffer, 0, checked((int)charsRead));
-                    sink.ProcessMessagesAndThrow();
-                    checked { currentOffset += charsWritten; }
-                    checked { lengthWritten += charsWritten; }
-                }
-
-                // Make sure to trim any left-over data
-                setters.SetCharsLength(sink, ordinal, currentOffset);
-                sink.ProcessMessagesAndThrow();
-            }
-        }
-
-        private static void SetSqlDateTime_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlDateTime value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetDateTime(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlDecimal_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlDecimal value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetSqlDecimal(sink, ordinal, value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlDouble_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlDouble value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetDouble(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlGuid_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlGuid value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetGuid(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlInt16_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlInt16 value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetInt16(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlInt32_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlInt32 value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetInt32(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlInt64_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlInt64 value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetInt64(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlMoney_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlMoney value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                if (SqlDbType.Variant == metaData.SqlDbType)
-                {
-                    setters.SetVariantMetaData(sink, ordinal, SmiMetaData.DefaultMoney);
-                    sink.ProcessMessagesAndThrow();
-                }
-
-                setters.SetInt64(sink, ordinal, SqlTypeWorkarounds.SqlMoneyToSqlInternalRepresentation(value));
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlSingle_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlSingle value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-            }
-            else
-            {
-                setters.SetSingle(sink, ordinal, value.Value);
-            }
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetSqlString_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData, SqlString value, int offset, int length)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-                sink.ProcessMessagesAndThrow();
-            }
-            else
-            {
-                if (SqlDbType.Variant == metaData.SqlDbType)
-                {
-                    // Set up a NVarChar metadata with correct LCID/Collation
-                    metaData = new SmiMetaData(
-                            SqlDbType.NVarChar,
-                            SmiMetaData.MaxUnicodeCharacters,
-                            0,
-                            0,
-                            value.LCID,
-                            value.SqlCompareOptions,
-                            null);
-                    setters.SetVariantMetaData(sink, ordinal, metaData);
-                    sink.ProcessMessagesAndThrow();
-                }
-                SetString_Unchecked(sink, setters, ordinal, value.Value, offset, length);
-            }
-        }
-
-        private static void SetSqlXml_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SqlXml value)
-        {
-            if (value.IsNull)
-            {
-                setters.SetDBNull(sink, ordinal);
-                sink.ProcessMessagesAndThrow();
-            }
-            else
-            {
-                SetXmlReader_Unchecked(sink, setters, ordinal, value.CreateReader());
-            }
-        }
-
-        private static void SetXmlReader_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, XmlReader xmlReader)
-        {
-            // set up writer
-            XmlWriterSettings WriterSettings = new XmlWriterSettings();
-            WriterSettings.CloseOutput = false; // don't close the memory stream
-            WriterSettings.ConformanceLevel = ConformanceLevel.Fragment;
-            WriterSettings.Encoding = System.Text.Encoding.Unicode;
-            WriterSettings.OmitXmlDeclaration = true;
-
-            System.IO.Stream target = new SmiSettersStream(sink, setters, ordinal, SmiMetaData.DefaultXml);
-
-            XmlWriter xmlWriter = XmlWriter.Create(target, WriterSettings);
-
-            // now spool the data into the writer (WriteNode will call Read())
-            xmlReader.Read();
-            while (!xmlReader.EOF)
-            {
-                xmlWriter.WriteNode(xmlReader, true);
-            }
-            xmlWriter.Flush();
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetString_Unchecked(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, string value, int offset, int length)
-        {
-            setters.SetString(sink, ordinal, value, offset, length);
-            sink.ProcessMessagesAndThrow();
-        }
-
-
-        // Set a DbDataReader to a Structured+MultiValued setter (table type)
-        //  Assumes metaData correctly describes the reader's shape, and consumes only the current resultset
-        private static void SetDbDataReader_Unchecked(
-            SmiEventSink_Default sink,
-            SmiTypedGetterSetter setters,
-            int ordinal,
-            SmiMetaData metaData,
-            DbDataReader value
-            )
-        {
-            // Get the target gettersetter
-            setters = setters.GetTypedGetterSetter(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-
-            // Iterate over all rows in the current set of results
-            while (value.Read())
-            {
-                setters.NewElement(sink);
-                sink.ProcessMessagesAndThrow();
-
-                FillCompatibleSettersFromReader(sink, setters, metaData.FieldMetaData, value);
-            }
-
-            setters.EndElements(sink);
-            sink.ProcessMessagesAndThrow();
-        }
-
-        private static void SetIEnumerableOfSqlDataRecord_Unchecked(
-            SmiEventSink_Default sink,
-            SmiTypedGetterSetter setters,
-            int ordinal,
-            SmiMetaData metaData,
-            IEnumerable<SqlDataRecord> value,
-            ParameterPeekAheadValue peekAhead
-            )
-        {
-            // Get target gettersetter
-            setters = setters.GetTypedGetterSetter(sink, ordinal);
-            sink.ProcessMessagesAndThrow();
-
-            IEnumerator<SqlDataRecord> enumerator = null;
-            try
-            {
-                // Need to copy field metadata to an array to call FillCompatibleITypeSettersFromRecord
-                SmiExtendedMetaData[] mdFields = new SmiExtendedMetaData[metaData.FieldMetaData.Count];
-                metaData.FieldMetaData.CopyTo(mdFields, 0);
-
-                SmiDefaultFieldsProperty defaults = (SmiDefaultFieldsProperty)metaData.ExtendedProperties[SmiPropertySelector.DefaultFields];
-
-                int recordNumber = 1;   // used only for reporting position when there are errors.
-
-                // obtain enumerator and handle any peekahead values
-                if (null != peekAhead && null != peekAhead.FirstRecord)
-                {
-                    // hook up to enumerator
-                    enumerator = peekAhead.Enumerator;
-
-                    // send the first record that was obtained earlier
-                    setters.NewElement(sink);
-                    sink.ProcessMessagesAndThrow();
-                    FillCompatibleSettersFromRecord(sink, setters, mdFields, peekAhead.FirstRecord, defaults);
-                    recordNumber++;
-                }
-                else
-                {
-                    enumerator = value.GetEnumerator();
-                }
-
-                using (enumerator)
-                {
-                    while (enumerator.MoveNext())
-                    {
-                        setters.NewElement(sink);
-                        sink.ProcessMessagesAndThrow();
-
-                        SqlDataRecord record = enumerator.Current;
-
-                        if (record.FieldCount != mdFields.Length)
-                        {
-                            throw SQL.EnumeratedRecordFieldCountChanged(recordNumber);
-                        }
-
-                        for (int i = 0; i < record.FieldCount; i++)
-                        {
-                            if (!MetaDataUtilsSmi.IsCompatible(metaData.FieldMetaData[i], record.GetSqlMetaData(i)))
-                            {
-                                throw SQL.EnumeratedRecordMetaDataChanged(record.GetName(i), recordNumber);
-                            }
-                        }
-
-                        FillCompatibleSettersFromRecord(sink, setters, mdFields, record, defaults);
-                        recordNumber++;
-                    }
-
-                    setters.EndElements(sink);
-                    sink.ProcessMessagesAndThrow();
-                }
-            }
-            finally
-            {
-                // Clean up!
-                IDisposable disposable = enumerator as IDisposable;
-                if (null != disposable)
-                {
-                    disposable.Dispose();
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/PinvokeAnalyzerExceptionList.analyzerdata.windows b/src/libraries/System.Data.SqlClient/src/PinvokeAnalyzerExceptionList.analyzerdata.windows
deleted file mode 100644 (file)
index 5c06489..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-<!-- Not a bug. sni.dll is a native component that ships as part of the package. -->
-kernel32.dll!LoadLibraryExW
-sni.dll!GetSniMaxComposedSpnLength
-sni.dll!SNIAddProviderWrapper
-sni.dll!SNICheckConnectionWrapper
-sni.dll!SNICloseWrapper
-sni.dll!SNIGetInfoWrapper
-sni.dll!SNIGetLastError
-sni.dll!SNIInitialize
-sni.dll!SNIOpenSyncExWrapper
-sni.dll!SNIOpenWrapper
-sni.dll!SNIPacketAllocateWrapper
-sni.dll!SNIPacketGetDataWrapper
-sni.dll!SNIPacketRelease
-sni.dll!SNIPacketResetWrapper
-sni.dll!SNIPacketSetData
-sni.dll!SNIQueryInfo
-sni.dll!SNIReadAsyncWrapper
-sni.dll!SNIReadSyncOverAsync
-sni.dll!SNIRemoveProviderWrapper
-sni.dll!SNISecGenClientContextWrapper
-sni.dll!SNISecInitPackage
-sni.dll!SNISetInfoWrapper
-sni.dll!SNITerminate
-sni.dll!SNIWaitForSSLHandshakeToCompleteWrapper
-sni.dll!SNIWriteAsyncWrapper
-sni.dll!SNIWriteSyncOverAsync
-sni.dll!UnmanagedIsTokenRestricted
-sspicli.dll!AcceptSecurityContext
-sspicli.dll!AcquireCredentialsHandleW
-sspicli.dll!ApplyControlToken
-sspicli.dll!CompleteAuthToken
-sspicli.dll!DecryptMessage
-sspicli.dll!DeleteSecurityContext
-sspicli.dll!EncryptMessage
-sspicli.dll!EnumerateSecurityPackagesW
-sspicli.dll!FreeContextBuffer
-sspicli.dll!FreeCredentialsHandle
-sspicli.dll!InitializeSecurityContextW
-sspicli.dll!QueryContextAttributesW
-sspicli.dll!QuerySecurityContextToken
-sspicli.dll!SetContextAttributesW
-sspicli.dll!SspiEncodeStringsAsAuthIdentity
-sspicli.dll!SspiFreeAuthIdentity
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/Resources/Strings.resx b/src/libraries/System.Data.SqlClient/src/Resources/Strings.resx
deleted file mode 100644 (file)
index cf16f2f..0000000
+++ /dev/null
@@ -1,1340 +0,0 @@
-<root>
-  <!-- 
-    Microsoft ResX Schema 
-    
-    Version 2.0
-    
-    The primary goals of this format is to allow a simple XML format 
-    that is mostly human readable. The generation and parsing of the 
-    various data types are done through the TypeConverter classes 
-    associated with the data types.
-    
-    Example:
-    
-    ... ado.net/XML headers & schema ...
-    <resheader name="resmimetype">text/microsoft-resx</resheader>
-    <resheader name="version">2.0</resheader>
-    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
-    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
-    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
-    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
-    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
-        <value>[base64 mime encoded serialized .NET Framework object]</value>
-    </data>
-    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
-        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
-        <comment>This is a comment</comment>
-    </data>
-                
-    There are any number of "resheader" rows that contain simple 
-    name/value pairs.
-    
-    Each data row contains a name, and value. The row also contains a 
-    type or mimetype. Type corresponds to a .NET class that support 
-    text/value conversion through the TypeConverter architecture. 
-    Classes that don't support this are serialized and stored with the 
-    mimetype set.
-    
-    The mimetype is used for serialized objects, and tells the 
-    ResXResourceReader how to depersist the object. This is currently not 
-    extensible. For a given mimetype the value must be set accordingly:
-    
-    Note - application/x-microsoft.net.object.binary.base64 is the format 
-    that the ResXResourceWriter will generate, however the reader can 
-    read any of the formats listed below.
-    
-    mimetype: application/x-microsoft.net.object.binary.base64
-    value   : The object must be serialized with 
-            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
-            : and then encoded with base64 encoding.
-    
-    mimetype: application/x-microsoft.net.object.soap.base64
-    value   : The object must be serialized with 
-            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
-            : and then encoded with base64 encoding.
-
-    mimetype: application/x-microsoft.net.object.bytearray.base64
-    value   : The object must be serialized into a byte array 
-            : using a System.ComponentModel.TypeConverter
-            : and then encoded with base64 encoding.
-    -->
-  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
-    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
-    <xsd:element name="root" msdata:IsDataSet="true">
-      <xsd:complexType>
-        <xsd:choice maxOccurs="unbounded">
-          <xsd:element name="metadata">
-            <xsd:complexType>
-              <xsd:sequence>
-                <xsd:element name="value" type="xsd:string" minOccurs="0" />
-              </xsd:sequence>
-              <xsd:attribute name="name" use="required" type="xsd:string" />
-              <xsd:attribute name="type" type="xsd:string" />
-              <xsd:attribute name="mimetype" type="xsd:string" />
-              <xsd:attribute ref="xml:space" />
-            </xsd:complexType>
-          </xsd:element>
-          <xsd:element name="assembly">
-            <xsd:complexType>
-              <xsd:attribute name="alias" type="xsd:string" />
-              <xsd:attribute name="name" type="xsd:string" />
-            </xsd:complexType>
-          </xsd:element>
-          <xsd:element name="data">
-            <xsd:complexType>
-              <xsd:sequence>
-                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
-                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
-              </xsd:sequence>
-              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
-              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
-              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
-              <xsd:attribute ref="xml:space" />
-            </xsd:complexType>
-          </xsd:element>
-          <xsd:element name="resheader">
-            <xsd:complexType>
-              <xsd:sequence>
-                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
-              </xsd:sequence>
-              <xsd:attribute name="name" type="xsd:string" use="required" />
-            </xsd:complexType>
-          </xsd:element>
-        </xsd:choice>
-      </xsd:complexType>
-    </xsd:element>
-  </xsd:schema>
-  <resheader name="resmimetype">
-    <value>text/microsoft-resx</value>
-  </resheader>
-  <resheader name="version">
-    <value>2.0</value>
-  </resheader>
-  <resheader name="reader">
-    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
-  </resheader>
-  <resheader name="writer">
-    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
-  </resheader>
-  <data name="ADP_CollectionIndexInt32" xml:space="preserve">
-    <value>Invalid index {0} for this {1} with Count={2}.</value>
-  </data>
-  <data name="ADP_CollectionIndexString" xml:space="preserve">
-    <value>An {0} with {1} '{2}' is not contained by this {3}.</value>
-  </data>
-  <data name="ADP_CollectionInvalidType" xml:space="preserve">
-    <value>The {0} only accepts non-null {1} type objects, not {2} objects.</value>
-  </data>
-  <data name="ADP_CollectionIsNotParent" xml:space="preserve">
-    <value>The {0} is already contained by another {1}.</value>
-  </data>
-  <data name="ADP_CollectionNullValue" xml:space="preserve">
-    <value>The {0} only accepts non-null {1} type objects.</value>
-  </data>
-  <data name="ADP_CollectionRemoveInvalidObject" xml:space="preserve">
-    <value>Attempted to remove an {0} that is not contained by this {1}.</value>
-  </data>
-  <data name="ADP_ConnectionAlreadyOpen" xml:space="preserve">
-    <value>The connection was not closed. {0}</value>
-  </data>
-  <data name="ADP_ConnectionStateMsg_Closed" xml:space="preserve">
-    <value>The connection's current state is closed.</value>
-  </data>
-  <data name="ADP_ConnectionStateMsg_Connecting" xml:space="preserve">
-    <value>The connection's current state is connecting.</value>
-  </data>
-  <data name="ADP_ConnectionStateMsg_Open" xml:space="preserve">
-    <value>The connection's current state is open.</value>
-  </data>
-  <data name="ADP_ConnectionStateMsg_OpenExecuting" xml:space="preserve">
-    <value>The connection's current state is executing.</value>
-  </data>
-  <data name="ADP_ConnectionStateMsg_OpenFetching" xml:space="preserve">
-    <value>The connection's current state is fetching.</value>
-  </data>
-  <data name="ADP_ConnectionStateMsg" xml:space="preserve">
-    <value>The connection's current state: {0}.</value>
-  </data>
-  <data name="ADP_ConnectionStringSyntax" xml:space="preserve">
-    <value>Format of the initialization string does not conform to specification starting at index {0}.</value>
-  </data>
-  <data name="ADP_DataReaderClosed" xml:space="preserve">
-    <value>Invalid attempt to call {0} when reader is closed.</value>
-  </data>
-  <data name="ADP_InternalConnectionError" xml:space="preserve">
-    <value>Internal DbConnection Error: {0}</value>
-  </data>
-  <data name="ADP_InvalidEnumerationValue" xml:space="preserve">
-    <value>The {0} enumeration value, {1}, is invalid.</value>
-  </data>
-  <data name="ADP_NotSupportedEnumerationValue" xml:space="preserve">
-    <value>The {0} enumeration value, {1}, is not supported by the {2} method.</value>
-  </data>
-  <data name="ADP_InvalidOffsetValue" xml:space="preserve">
-    <value>Invalid parameter Offset value '{0}'. The value must be greater than or equal to 0.</value>
-  </data>
-  <data name="ADP_TransactionPresent" xml:space="preserve">
-    <value>Connection currently has transaction enlisted.  Finish current transaction and retry.</value>
-  </data>
-  <data name="ADP_LocalTransactionPresent" xml:space="preserve">
-    <value>Cannot enlist in the transaction because a local transaction is in progress on the connection.  Finish local transaction and retry.</value>
-  </data>
-  <data name="ADP_NoConnectionString" xml:space="preserve">
-    <value>The ConnectionString property has not been initialized.</value>
-  </data>
-  <data name="ADP_OpenConnectionPropertySet" xml:space="preserve">
-    <value>Not allowed to change the '{0}' property. {1}</value>
-  </data>
-  <data name="ADP_PendingAsyncOperation" xml:space="preserve">
-    <value>Can not start another operation while there is an asynchronous operation pending.</value>
-  </data>
-  <data name="ADP_PooledOpenTimeout" xml:space="preserve">
-    <value>Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.</value>
-  </data>
-  <data name="ADP_NonPooledOpenTimeout" xml:space="preserve">
-    <value>Timeout attempting to open the connection.  The time period elapsed prior to attempting to open the connection has been exceeded.  This may have occurred because of too many simultaneous non-pooled connection attempts.</value>
-  </data>
-  <data name="ADP_SingleValuedProperty" xml:space="preserve">
-    <value>The only acceptable value for the property '{0}' is '{1}'.</value>
-  </data>
-  <data name="ADP_DoubleValuedProperty" xml:space="preserve">
-    <value>The acceptable values for the property '{0}' are '{1}' or '{2}'.</value>
-  </data>
-  <data name="ADP_InvalidPrefixSuffix" xml:space="preserve">
-    <value>Specified QuotePrefix and QuoteSuffix values do not match.</value>
-  </data>
-  <data name="Arg_ArrayPlusOffTooSmall" xml:space="preserve">
-    <value>Destination array is not long enough to copy all the items in the collection. Check array index and length.</value>
-  </data>
-  <data name="Arg_RankMultiDimNotSupported" xml:space="preserve">
-    <value>Only single dimensional arrays are supported for the requested action.</value>
-  </data>
-  <data name="Arg_RemoveArgNotFound" xml:space="preserve">
-    <value>Cannot remove the specified item because it was not found in the specified Collection.</value>
-  </data>
-  <data name="ArgumentOutOfRange_NeedNonNegNum" xml:space="preserve">
-    <value>Non-negative number required.</value>
-  </data>
-  <data name="Data_InvalidOffsetLength" xml:space="preserve">
-    <value>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</value>
-  </data>
-  <data name="SqlConvert_ConvertFailed" xml:space="preserve">
-    <value>Cannot convert object of type '{0}' to object of type '{1}'.</value>
-  </data>
-  <data name="SQL_WrongType" xml:space="preserve">
-    <value>Expecting argument of type {1}, but received type {0}.</value>
-  </data>
-  <data name="ADP_DeriveParametersNotSupported" xml:space="preserve">
-    <value>{0} DeriveParameters only supports CommandType.StoredProcedure, not CommandType. {1}.</value>
-  </data>
-  <data name="ADP_NoStoredProcedureExists" xml:space="preserve">
-    <value>The stored procedure '{0}' doesn't exist.</value>
-  </data>
-  <data name="ADP_InvalidConnectionOptionValue" xml:space="preserve">
-    <value>Invalid value for key '{0}'.</value>
-  </data>
-  <data name="ADP_MissingConnectionOptionValue" xml:space="preserve">
-    <value>Use of key '{0}' requires the key '{1}' to be present.</value>
-  </data>
-  <data name="ADP_InvalidConnectionOptionValueLength" xml:space="preserve">
-    <value>The value's length for key '{0}' exceeds it's limit of '{1}'.</value>
-  </data>
-  <data name="ADP_KeywordNotSupported" xml:space="preserve">
-    <value>Keyword not supported: '{0}'.</value>
-  </data>
-  <data name="ADP_InternalProviderError" xml:space="preserve">
-    <value>Internal .NET Framework Data Provider error {0}.</value>
-  </data>
-  <data name="ADP_InvalidMultipartName" xml:space="preserve">
-    <value>{0} '{1}'.</value>
-  </data>
-  <data name="ADP_InvalidMultipartNameQuoteUsage" xml:space="preserve">
-    <value>{0} '{1}', incorrect usage of quotes.</value>
-  </data>
-  <data name="ADP_InvalidMultipartNameToManyParts" xml:space="preserve">
-    <value>{0} '{1}', the current limit of '{2}' is insufficient.</value>
-  </data>
-  <data name="SQL_SqlCommandCommandText" xml:space="preserve">
-    <value>SqlCommand.DeriveParameters failed because the SqlCommand.CommandText property value is an invalid multipart name</value>
-  </data>
-  <data name="SQL_BatchedUpdatesNotAvailableOnContextConnection" xml:space="preserve">
-    <value>Batching updates is not supported on the context connection.</value>
-  </data>
-  <data name="SQL_BulkCopyDestinationTableName" xml:space="preserve">
-    <value>SqlBulkCopy.WriteToServer failed because the SqlBulkCopy.DestinationTableName is an invalid multipart name</value>
-  </data>
-  <data name="SQL_TDSParserTableName" xml:space="preserve">
-    <value>Processing of results from SQL Server failed because of an invalid multipart name</value>
-  </data>
-  <data name="SQL_TypeName" xml:space="preserve">
-    <value>SqlParameter.TypeName is an invalid multipart name</value>
-  </data>
-  <data name="SQLMSF_FailoverPartnerNotSupported" xml:space="preserve">
-    <value>Connecting to a mirrored SQL Server instance using the MultiSubnetFailover connection option is not supported.</value>
-  </data>
-  <data name="SQL_NotSupportedEnumerationValue" xml:space="preserve">
-    <value>The {0} enumeration value, {1}, is not supported by the .NET Framework SqlClient Data Provider.</value>
-  </data>
-  <data name="ADP_CommandTextRequired" xml:space="preserve">
-    <value>{0}: CommandText property has not been initialized</value>
-  </data>
-  <data name="ADP_ConnectionRequired" xml:space="preserve">
-    <value>{0}: Connection property has not been initialized.</value>
-  </data>
-  <data name="ADP_OpenConnectionRequired" xml:space="preserve">
-    <value>{0} requires an open and available Connection. {1}</value>
-  </data>
-  <data name="ADP_TransactionConnectionMismatch" xml:space="preserve">
-    <value>The transaction is either not associated with the current connection or has been completed.</value>
-  </data>
-  <data name="ADP_TransactionRequired" xml:space="preserve">
-    <value>{0} requires the command to have a transaction when the connection assigned to the command is in a pending local transaction.  The Transaction property of the command has not been initialized.</value>
-  </data>
-  <data name="ADP_OpenReaderExists" xml:space="preserve">
-    <value>There is already an open DataReader associated with this Command which must be closed first.</value>
-  </data>
-  <data name="ADP_CalledTwice" xml:space="preserve">
-    <value>The method '{0}' cannot be called more than once for the same execution.</value>
-  </data>
-  <data name="ADP_InvalidCommandTimeout" xml:space="preserve">
-    <value>Invalid CommandTimeout value {0}; the value must be &gt;= 0.</value>
-  </data>
-  <data name="ADP_UninitializedParameterSize" xml:space="preserve">
-    <value>{1}[{0}]: the Size property has an invalid size of 0.</value>
-  </data>
-  <data name="ADP_PrepareParameterType" xml:space="preserve">
-    <value>{0}.Prepare method requires all parameters to have an explicitly set type.</value>
-  </data>
-  <data name="ADP_PrepareParameterSize" xml:space="preserve">
-    <value>{0}.Prepare method requires all variable length parameters to have an explicitly set non-zero Size.</value>
-  </data>
-  <data name="ADP_PrepareParameterScale" xml:space="preserve">
-    <value>{0}.Prepare method requires parameters of type '{1}' have an explicitly set Precision and Scale.</value>
-  </data>
-  <data name="ADP_MismatchedAsyncResult" xml:space="preserve">
-    <value>Mismatched end method call for asyncResult.  Expected call to {0} but {1} was called instead.</value>
-  </data>
-  <data name="ADP_ClosedConnectionError" xml:space="preserve">
-    <value>Invalid operation. The connection is closed.</value>
-  </data>
-  <data name="ADP_ConnectionIsDisabled" xml:space="preserve">
-    <value>The connection has been disabled.</value>
-  </data>
-  <data name="ADP_EmptyDatabaseName" xml:space="preserve">
-    <value>Database cannot be null, the empty string, or string of only whitespace.</value>
-  </data>
-  <data name="ADP_InvalidSourceBufferIndex" xml:space="preserve">
-    <value>Invalid source buffer (size of {0}) offset: {1}</value>
-  </data>
-  <data name="ADP_InvalidDestinationBufferIndex" xml:space="preserve">
-    <value>Invalid destination buffer (size of {0}) offset: {1}</value>
-  </data>
-  <data name="ADP_StreamClosed" xml:space="preserve">
-    <value>Invalid attempt to {0} when stream is closed.</value>
-  </data>
-  <data name="ADP_InvalidSeekOrigin" xml:space="preserve">
-    <value>Specified SeekOrigin value is invalid.</value>
-  </data>
-  <data name="ADP_NonSequentialColumnAccess" xml:space="preserve">
-    <value>Invalid attempt to read from column ordinal '{0}'.  With CommandBehavior.SequentialAccess, you may only read from column ordinal '{1}' or greater.</value>
-  </data>
-  <data name="ADP_InvalidDataType" xml:space="preserve">
-    <value>The parameter data type of {0} is invalid.</value>
-  </data>
-  <data name="ADP_UnknownDataType" xml:space="preserve">
-    <value>No mapping exists from object type {0} to a known managed provider native type.</value>
-  </data>
-  <data name="ADP_UnknownDataTypeCode" xml:space="preserve">
-    <value>Unable to handle an unknown TypeCode {0} returned by Type {1}.</value>
-  </data>
-  <data name="ADP_DbTypeNotSupported" xml:space="preserve">
-    <value>No mapping exists from DbType {0} to a known {1}.</value>
-  </data>
-  <data name="ADP_VersionDoesNotSupportDataType" xml:space="preserve">
-    <value>The version of SQL Server in use does not support datatype '{0}'.</value>
-  </data>
-  <data name="ADP_ParameterValueOutOfRange" xml:space="preserve">
-    <value>Parameter value '{0}' is out of range.</value>
-  </data>
-  <data name="ADP_BadParameterName" xml:space="preserve">
-    <value>Specified parameter name '{0}' is not valid.</value>
-  </data>
-  <data name="ADP_InvalidSizeValue" xml:space="preserve">
-    <value>Invalid parameter Size value '{0}'. The value must be greater than or equal to 0.</value>
-  </data>
-  <data name="ADP_NegativeParameter" xml:space="preserve">
-    <value>Invalid value for argument '{0}'. The value must be greater than or equal to 0.</value>
-  </data>
-  <data name="ADP_InvalidMetaDataValue" xml:space="preserve">
-    <value>Invalid value for this metadata.</value>
-  </data>
-  <data name="ADP_ParameterConversionFailed" xml:space="preserve">
-    <value>Failed to convert parameter value from a {0} to a {1}.</value>
-  </data>
-  <data name="ADP_ParallelTransactionsNotSupported" xml:space="preserve">
-    <value>{0} does not support parallel transactions.</value>
-  </data>
-  <data name="ADP_TransactionZombied" xml:space="preserve">
-    <value>This {0} has completed; it is no longer usable.</value>
-  </data>
-  <data name="ADP_InvalidDataLength2" xml:space="preserve">
-    <value>Specified length '{0}' is out of range.</value>
-  </data>
-  <data name="ADP_NonSeqByteAccess" xml:space="preserve">
-    <value>Invalid {2} attempt at dataIndex '{0}'.  With CommandBehavior.SequentialAccess, you may only read from dataIndex '{1}' or greater.</value>
-  </data>
-  <data name="ADP_InvalidMinMaxPoolSizeValues" xml:space="preserve">
-    <value>Invalid min or max pool size values, min pool size cannot be greater than the max pool size.</value>
-  </data>
-  <data name="SQL_InvalidPacketSizeValue" xml:space="preserve">
-    <value>Invalid 'Packet Size'.  The value must be an integer &gt;= 512 and &lt;= 32768.</value>
-  </data>
-  <data name="SQL_NullEmptyTransactionName" xml:space="preserve">
-    <value>Invalid transaction or invalid name for a point at which to save within the transaction.</value>
-  </data>
-  <data name="SQL_UserInstanceFailoverNotCompatible" xml:space="preserve">
-    <value>User Instance and Failover are not compatible options.  Please choose only one of the two in the connection string.</value>
-  </data>
-  <data name="SQL_EncryptionNotSupportedByClient" xml:space="preserve">
-    <value>The instance of SQL Server you attempted to connect to requires encryption but this machine does not support it.</value>
-  </data>
-  <data name="SQL_EncryptionNotSupportedByServer" xml:space="preserve">
-    <value>The instance of SQL Server you attempted to connect to does not support encryption.</value>
-  </data>
-  <data name="SQL_InvalidSQLServerVersionUnknown" xml:space="preserve">
-    <value>Unsupported SQL Server version.  The .NET Framework SqlClient Data Provider can only be used with SQL Server versions 7.0 and later.</value>
-  </data>
-  <data name="SQL_CannotCreateNormalizer" xml:space="preserve">
-    <value>Cannot create normalizer for '{0}'.</value>
-  </data>
-  <data name="SQL_CannotModifyPropertyAsyncOperationInProgress" xml:space="preserve">
-    <value>{0} cannot be changed while async operation is in progress.</value>
-  </data>
-  <data name="SQL_InstanceFailure" xml:space="preserve">
-    <value>Instance failure.</value>
-  </data>
-  <data name="SQL_InvalidPartnerConfiguration" xml:space="preserve">
-    <value>Server {0}, database {1} is not configured for database mirroring.</value>
-  </data>
-  <data name="SQL_MarsUnsupportedOnConnection" xml:space="preserve">
-    <value>The connection does not support MultipleActiveResultSets.</value>
-  </data>
-  <data name="SQL_NonLocalSSEInstance" xml:space="preserve">
-    <value>SSE Instance re-direction is not supported for non-local user instances.</value>
-  </data>
-  <data name="SQL_PendingBeginXXXExists" xml:space="preserve">
-    <value>The command execution cannot proceed due to a pending asynchronous operation already in progress.</value>
-  </data>
-  <data name="SQL_NonXmlResult" xml:space="preserve">
-    <value>Invalid command sent to ExecuteXmlReader.  The command must return an Xml result.</value>
-  </data>
-  <data name="SQL_InvalidParameterTypeNameFormat" xml:space="preserve">
-    <value>Invalid 3 part name format for TypeName.</value>
-  </data>
-  <data name="SQL_InvalidParameterNameLength" xml:space="preserve">
-    <value>The length of the parameter '{0}' exceeds the limit of 128 characters.</value>
-  </data>
-  <data name="SQL_PrecisionValueOutOfRange" xml:space="preserve">
-    <value>Precision value '{0}' is either less than 0 or greater than the maximum allowed precision of 38.</value>
-  </data>
-  <data name="SQL_ScaleValueOutOfRange" xml:space="preserve">
-    <value>Scale value '{0}' is either less than 0 or greater than the maximum allowed scale of 38.</value>
-  </data>
-  <data name="SQL_TimeScaleValueOutOfRange" xml:space="preserve">
-    <value>Scale value '{0}' is either less than 0 or greater than the maximum allowed scale of 7.</value>
-  </data>
-  <data name="SQL_ParameterInvalidVariant" xml:space="preserve">
-    <value>Parameter '{0}' exceeds the size limit for the sql_variant datatype.</value>
-  </data>
-  <data name="SQL_ParameterTypeNameRequired" xml:space="preserve">
-    <value>The {0} type parameter '{1}' must have a valid type name.</value>
-  </data>
-  <data name="SQL_InvalidInternalPacketSize" xml:space="preserve">
-    <value>Invalid internal packet size:</value>
-  </data>
-  <data name="SQL_InvalidTDSVersion" xml:space="preserve">
-    <value>The SQL Server instance returned an invalid or unsupported protocol version during login negotiation.</value>
-  </data>
-  <data name="SQL_InvalidTDSPacketSize" xml:space="preserve">
-    <value>Invalid Packet Size.</value>
-  </data>
-  <data name="SQL_ParsingError" xml:space="preserve">
-    <value>Internal connection fatal error.</value>
-  </data>
-  <data name="SQL_ConnectionLockedForBcpEvent" xml:space="preserve">
-    <value>The connection cannot be used because there is an ongoing operation that must be finished.</value>
-  </data>
-  <data name="SQL_SNIPacketAllocationFailure" xml:space="preserve">
-    <value>Memory allocation for internal connection failed.</value>
-  </data>
-  <data name="SQL_SmallDateTimeOverflow" xml:space="preserve">
-    <value>SqlDbType.SmallDateTime overflow.  Value '{0}' is out of range.  Must be between 1/1/1900 12:00:00 AM and 6/6/2079 11:59:59 PM.</value>
-  </data>
-  <data name="SQL_TimeOverflow" xml:space="preserve">
-    <value>SqlDbType.Time overflow.  Value '{0}' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.</value>
-  </data>
-  <data name="SQL_MoneyOverflow" xml:space="preserve">
-    <value>SqlDbType.SmallMoney overflow.  Value '{0}' is out of range.  Must be between -214,748.3648 and 214,748.3647.</value>
-  </data>
-  <data name="SQL_CultureIdError" xml:space="preserve">
-    <value>The Collation specified by SQL Server is not supported.</value>
-  </data>
-  <data name="SQL_OperationCancelled" xml:space="preserve">
-    <value>Operation cancelled by user.</value>
-  </data>
-  <data name="SQL_SevereError" xml:space="preserve">
-    <value>A severe error occurred on the current command.  The results, if any, should be discarded.</value>
-  </data>
-  <data name="SQL_SSPIGenerateError" xml:space="preserve">
-    <value>Failed to generate SSPI context.</value>
-  </data>
-  <data name="SQL_KerberosTicketMissingError" xml:space="preserve">
-    <value>Cannot authenticate using Kerberos. Ensure Kerberos has been initialized on the client with 'kinit' and a Service Principal Name has been registered for the SQL Server to allow Kerberos authentication.</value>  
-  </data>
-  <data name="SQL_SqlServerBrowserNotAccessible" xml:space="preserve">
-    <value>Cannot connect to SQL Server Browser. Ensure SQL Server Browser has been started.</value>
-  </data>
-  <data name="SQL_InvalidSSPIPacketSize" xml:space="preserve">
-    <value>Invalid SSPI packet size.</value>
-  </data>
-  <data name="SQL_SSPIInitializeError" xml:space="preserve">
-    <value>Cannot initialize SSPI package.</value>
-  </data>
-  <data name="SQL_Timeout" xml:space="preserve">
-    <value>Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.</value>
-  </data>
-  <data name="SQL_Timeout_PreLogin_Begin" xml:space="preserve">
-    <value>Connection Timeout Expired.  The timeout period elapsed at the start of the pre-login phase.  This could be because of insufficient time provided for connection timeout.</value>
-  </data>
-  <data name="SQL_Timeout_PreLogin_InitializeConnection" xml:space="preserve">
-    <value>Connection Timeout Expired.  The timeout period elapsed while attempting to create and initialize a socket to the server.  This could be either because the server was unreachable or unable to respond back in time.</value>
-  </data>
-  <data name="SQL_Timeout_PreLogin_SendHandshake" xml:space="preserve">
-    <value>Connection Timeout Expired.  The timeout period elapsed while making a pre-login handshake request.  This could be because the server was unable to respond back in time.</value>
-  </data>
-  <data name="SQL_Timeout_PreLogin_ConsumeHandshake" xml:space="preserve">
-    <value>Connection Timeout Expired.  The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.  This could be because the pre-login handshake failed or the server was unable to respond back in time.</value>
-  </data>
-  <data name="SQL_Timeout_Login_Begin" xml:space="preserve">
-    <value>Connection Timeout Expired.  The timeout period elapsed at the start of the login phase.  This could be because of insufficient time provided for connection timeout.</value>
-  </data>
-  <data name="SQL_Timeout_Login_ProcessConnectionAuth" xml:space="preserve">
-    <value>Connection Timeout Expired.  The timeout period elapsed while attempting to authenticate the login.  This could be because the server failed to authenticate the user or the server was unable to respond back in time.</value>
-  </data>
-  <data name="SQL_Timeout_PostLogin" xml:space="preserve">
-    <value>Connection Timeout Expired.  The timeout period elapsed during the post-login phase.  The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections.</value>
-  </data>
-  <data name="SQL_Timeout_FailoverInfo" xml:space="preserve">
-    <value>This failure occurred while attempting to connect to the {0} server.</value>
-  </data>
-  <data name="SQL_Timeout_RoutingDestinationInfo" xml:space="preserve">
-    <value>This failure occurred while attempting to connect to the routing destination. The duration spent while attempting to connect to the original server was - [Pre-Login] initialization={0}; handshake={1}; [Login] initialization={2}; authentication={3}; [Post-Login] complete={4};  </value>
-  </data>
-  <data name="SQL_Duration_PreLogin_Begin" xml:space="preserve">
-    <value>The duration spent while attempting to connect to this server was - [Pre-Login] initialization={0};</value>
-  </data>
-  <data name="SQL_Duration_PreLoginHandshake" xml:space="preserve">
-    <value>The duration spent while attempting to connect to this server was - [Pre-Login] initialization={0}; handshake={1}; </value>
-  </data>
-  <data name="SQL_Duration_Login_Begin" xml:space="preserve">
-    <value>The duration spent while attempting to connect to this server was - [Pre-Login] initialization={0}; handshake={1}; [Login] initialization={2}; </value>
-  </data>
-  <data name="SQL_Duration_Login_ProcessConnectionAuth" xml:space="preserve">
-    <value>The duration spent while attempting to connect to this server was - [Pre-Login] initialization={0}; handshake={1}; [Login] initialization={2}; authentication={3}; </value>
-  </data>
-  <data name="SQL_Duration_PostLogin" xml:space="preserve">
-    <value>The duration spent while attempting to connect to this server was - [Pre-Login] initialization={0}; handshake={1}; [Login] initialization={2}; authentication={3}; [Post-Login] complete={4}; </value>
-  </data>
-  <data name="SQL_UserInstanceFailure" xml:space="preserve">
-    <value>A user instance was requested in the connection string but the server specified does not support this option.</value>
-  </data>
-  <data name="SQL_InvalidRead" xml:space="preserve">
-    <value>Invalid attempt to read when no data is present.</value>
-  </data>
-  <data name="SQL_NonBlobColumn" xml:space="preserve">
-    <value>Invalid attempt to GetBytes on column '{0}'.  The GetBytes function can only be used on columns of type Text, NText, or Image.</value>
-  </data>
-  <data name="SQL_NonCharColumn" xml:space="preserve">
-    <value>Invalid attempt to GetChars on column '{0}'.  The GetChars function can only be used on columns of type Text, NText, Xml, VarChar or NVarChar.</value>
-  </data>
-  <data name="SQL_StreamNotSupportOnColumnType" xml:space="preserve">
-    <value>Invalid attempt to GetStream on column '{0}'. The GetStream function can only be used on columns of type Binary, Image, Udt or VarBinary.</value>
-  </data>
-  <data name="SQL_TextReaderNotSupportOnColumnType" xml:space="preserve">
-    <value>Invalid attempt to GetTextReader on column '{0}'. The GetTextReader function can only be used on columns of type Char, NChar, NText, NVarChar, Text or VarChar.</value>
-  </data>
-  <data name="SQL_XmlReaderNotSupportOnColumnType" xml:space="preserve">
-    <value>Invalid attempt to GetXmlReader on column '{0}'. The GetXmlReader function can only be used on columns of type Xml.</value>
-  </data>
-  <data name="SqlDelegatedTransaction_PromotionFailed" xml:space="preserve">
-    <value>Failure while attempting to promote transaction.</value>
-  </data>
-  <data name="SQL_InvalidBufferSizeOrIndex" xml:space="preserve">
-    <value>Buffer offset '{1}' plus the bytes available '{0}' is greater than the length of the passed in buffer.</value>
-  </data>
-  <data name="SQL_InvalidDataLength" xml:space="preserve">
-    <value>Data length '{0}' is less than 0.</value>
-  </data>
-  <data name="SQL_BulkLoadMappingInaccessible" xml:space="preserve">
-    <value>The mapped collection is in use and cannot be accessed at this time;</value>
-  </data>
-  <data name="SQL_BulkLoadMappingsNamesOrOrdinalsOnly" xml:space="preserve">
-    <value>Mappings must be either all name or all ordinal based.</value>
-  </data>
-  <data name="SQL_BulkLoadCannotConvertValue" xml:space="preserve">
-    <value>The given value of type {0} from the data source cannot be converted to type {1} of the specified target column.</value>
-  </data>
-  <data name="SQL_BulkLoadNonMatchingColumnMapping" xml:space="preserve">
-    <value>The given ColumnMapping does not match up with any column in the source or destination.</value>
-  </data>
-  <data name="SQL_BulkLoadNonMatchingColumnName" xml:space="preserve">
-    <value>The given ColumnName '{0}' does not match up with any column in data source.</value>
-  </data>
-  <data name="SQL_BulkLoadStringTooLong" xml:space="preserve">
-    <value>String or binary data would be truncated.</value>
-  </data>
-  <data name="SQL_BulkLoadInvalidTimeout" xml:space="preserve">
-    <value>Timeout Value '{0}' is less than 0.</value>
-  </data>
-  <data name="SQL_BulkLoadInvalidVariantValue" xml:space="preserve">
-    <value>Value cannot be converted to SqlVariant.</value>
-  </data>
-  <data name="SQL_BulkLoadExistingTransaction" xml:space="preserve">
-    <value>Unexpected existing transaction.</value>
-  </data>
-  <data name="SQL_BulkLoadNoCollation" xml:space="preserve">
-    <value>Failed to obtain column collation information for the destination table. If the table is not in the current database the name must be qualified using the database name (e.g. [mydb]..[mytable](e.g. [mydb]..[mytable]); this also applies to temporary-tables (e.g. #mytable would be specified as tempdb..#mytable).</value>
-  </data>
-  <data name="SQL_BulkLoadConflictingTransactionOption" xml:space="preserve">
-    <value>Must not specify SqlBulkCopyOption.UseInternalTransaction and pass an external Transaction at the same time.</value>
-  </data>
-  <data name="SQL_BulkLoadInvalidOperationInsideEvent" xml:space="preserve">
-    <value>Function must not be called during event.</value>
-  </data>
-  <data name="SQL_BulkLoadMissingDestinationTable" xml:space="preserve">
-    <value>The DestinationTableName property must be set before calling this method.</value>
-  </data>
-  <data name="SQL_BulkLoadInvalidDestinationTable" xml:space="preserve">
-    <value>Cannot access destination table '{0}'.</value>
-  </data>
-  <data name="SQL_BulkLoadNotAllowDBNull" xml:space="preserve">
-    <value>Column '{0}' does not allow DBNull.Value.</value>
-  </data>
-  <data name="Sql_BulkLoadLcidMismatch" xml:space="preserve">
-    <value>The locale id '{0}' of the source column '{1}' and the locale id '{2}' of the destination column '{3}' do not match.</value>
-  </data>
-  <data name="SQL_BulkLoadPendingOperation" xml:space="preserve">
-    <value>Attempt to invoke bulk copy on an object that has a pending operation.</value>
-  </data>
-  <data name="SQL_CannotGetDTCAddress" xml:space="preserve">
-    <value>Unable to get the address of the distributed transaction coordinator for the server, from the server.  Is DTC enabled on the server?</value>
-  </data>
-  <data name="SQL_ConnectionDoomed" xml:space="preserve">
-    <value>The requested operation cannot be completed because the connection has been broken.</value>
-  </data>
-  <data name="SQL_OpenResultCountExceeded" xml:space="preserve">
-    <value>Open result count exceeded.</value>
-  </data>
-  <data name="SQL_StreamWriteNotSupported" xml:space="preserve">
-    <value>The Stream does not support writing.</value>
-  </data>
-  <data name="SQL_StreamReadNotSupported" xml:space="preserve">
-    <value>The Stream does not support reading.</value>
-  </data>
-  <data name="SQL_StreamSeekNotSupported" xml:space="preserve">
-    <value>The Stream does not support seeking.</value>
-  </data>
-  <data name="SQL_ExClientConnectionId" xml:space="preserve">
-    <value>ClientConnectionId:{0}</value>
-  </data>
-  <data name="SQL_ExErrorNumberStateClass" xml:space="preserve">
-    <value>Error Number:{0},State:{1},Class:{2}</value>
-  </data>
-  <data name="SQL_ExOriginalClientConnectionId" xml:space="preserve">
-    <value>ClientConnectionId before routing:{0}</value>
-  </data>
-  <data name="SQL_ExRoutingDestination" xml:space="preserve">
-    <value>Routing Destination:{0}</value>
-  </data>
-  <data name="SQL_UnsupportedSysTxVersion" xml:space="preserve">
-    <value>The currently loaded System.Transactions.dll does not support Global Transactions.</value>
-  </data>
-  <data name="SqlMisc_NullString" xml:space="preserve">
-    <value>Null</value>
-  </data>
-  <data name="SqlMisc_MessageString" xml:space="preserve">
-    <value>Message</value>
-  </data>
-  <data name="SqlMisc_ArithOverflowMessage" xml:space="preserve">
-    <value>Arithmetic Overflow.</value>
-  </data>
-  <data name="SqlMisc_DivideByZeroMessage" xml:space="preserve">
-    <value>Divide by zero error encountered.</value>
-  </data>
-  <data name="SqlMisc_NullValueMessage" xml:space="preserve">
-    <value>Data is Null. This method or property cannot be called on Null values.</value>
-  </data>
-  <data name="SqlMisc_TruncationMessage" xml:space="preserve">
-    <value>Numeric arithmetic causes truncation.</value>
-  </data>
-  <data name="SqlMisc_DateTimeOverflowMessage" xml:space="preserve">
-    <value>SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.</value>
-  </data>
-  <data name="SqlMisc_ConcatDiffCollationMessage" xml:space="preserve">
-    <value>Two strings to be concatenated have different collation.</value>
-  </data>
-  <data name="SqlMisc_CompareDiffCollationMessage" xml:space="preserve">
-    <value>Two strings to be compared have different collation.</value>
-  </data>
-  <data name="SqlMisc_InvalidFlagMessage" xml:space="preserve">
-    <value>Invalid flag value.</value>
-  </data>
-  <data name="SqlMisc_NumeToDecOverflowMessage" xml:space="preserve">
-    <value>Conversion from SqlDecimal to Decimal overflows.</value>
-  </data>
-  <data name="SqlMisc_ConversionOverflowMessage" xml:space="preserve">
-    <value>Conversion overflows.</value>
-  </data>
-  <data name="SqlMisc_InvalidDateTimeMessage" xml:space="preserve">
-    <value>Invalid SqlDateTime.</value>
-  </data>
-  <data name="SqlMisc_TimeZoneSpecifiedMessage" xml:space="preserve">
-    <value>A time zone was specified. SqlDateTime does not support time zones.</value>
-  </data>
-  <data name="SqlMisc_InvalidArraySizeMessage" xml:space="preserve">
-    <value>Invalid array size.</value>
-  </data>
-  <data name="SqlMisc_InvalidPrecScaleMessage" xml:space="preserve">
-    <value>Invalid numeric precision/scale.</value>
-  </data>
-  <data name="SqlMisc_FormatMessage" xml:space="preserve">
-    <value>The input wasn't in a correct format.</value>
-  </data>
-  <data name="SqlMisc_StreamErrorMessage" xml:space="preserve">
-    <value>An error occurred while reading.</value>
-  </data>
-  <data name="SqlMisc_TruncationMaxDataMessage" xml:space="preserve">
-    <value>Data returned is larger than 2Gb in size. Use SequentialAccess command behavior in order to get all of the data.</value>
-  </data>
-  <data name="SqlMisc_NotFilledMessage" xml:space="preserve">
-    <value>SQL Type has not been loaded with data.</value>
-  </data>
-  <data name="SqlMisc_AlreadyFilledMessage" xml:space="preserve">
-    <value>SQL Type has already been loaded with data.</value>
-  </data>
-  <data name="SqlMisc_ClosedXmlReaderMessage" xml:space="preserve">
-    <value>Invalid attempt to access a closed XmlReader.</value>
-  </data>
-  <data name="SqlMisc_InvalidOpStreamClosed" xml:space="preserve">
-    <value>Invalid attempt to call {0} when the stream is closed.</value>
-  </data>
-  <data name="SqlMisc_InvalidOpStreamNonWritable" xml:space="preserve">
-    <value>Invalid attempt to call {0} when the stream non-writable.</value>
-  </data>
-  <data name="SqlMisc_InvalidOpStreamNonReadable" xml:space="preserve">
-    <value>Invalid attempt to call {0} when the stream non-readable.</value>
-  </data>
-  <data name="SqlMisc_InvalidOpStreamNonSeekable" xml:space="preserve">
-    <value>Invalid attempt to call {0} when the stream is non-seekable.</value>
-  </data>
-  <data name="SqlMisc_SubclassMustOverride" xml:space="preserve">
-    <value>Subclass did not override a required method.</value>
-  </data>
-  <data name="SqlUdtReason_NoUdtAttribute" xml:space="preserve">
-    <value>no UDT attribute</value>
-  </data>
-  <data name="SQLUDT_InvalidSqlType" xml:space="preserve">
-    <value>Specified type is not registered on the target server. {0}.</value>
-  </data>
-  <data name="Sql_InternalError" xml:space="preserve">
-    <value>Internal Error</value>
-  </data>
-  <data name="ADP_OperationAborted" xml:space="preserve">
-    <value>Operation aborted.</value>
-  </data>
-  <data name="ADP_OperationAbortedExceptionMessage" xml:space="preserve">
-    <value>Operation aborted due to an exception (see InnerException for details).</value>
-  </data>
-  <data name="ADP_TransactionCompletedButNotDisposed" xml:space="preserve">
-    <value>The transaction associated with the current connection has completed but has not been disposed.  The transaction must be disposed before the connection can be used to execute SQL statements.</value>
-  </data>
-  <data name="SqlParameter_UnsupportedTVPOutputParameter" xml:space="preserve">
-    <value>ParameterDirection '{0}' specified for parameter '{1}' is not supported. Table-valued parameters only support ParameterDirection.Input.</value>
-  </data>
-  <data name="SqlParameter_DBNullNotSupportedForTVP" xml:space="preserve">
-    <value>DBNull value for parameter '{0}' is not supported. Table-valued parameters cannot be DBNull.</value>
-  </data>
-  <data name="SqlParameter_UnexpectedTypeNameForNonStruct" xml:space="preserve">
-    <value>TypeName specified for parameter '{0}'.  TypeName must only be set for Structured parameters.</value>
-  </data>
-  <data name="NullSchemaTableDataTypeNotSupported" xml:space="preserve">
-    <value>DateType column for field '{0}' in schema table is null.  DataType must be non-null.</value>
-  </data>
-  <data name="InvalidSchemaTableOrdinals" xml:space="preserve">
-    <value>Invalid column ordinals in schema table.  ColumnOrdinals, if present, must not have duplicates or gaps.</value>
-  </data>
-  <data name="SQL_EnumeratedRecordMetaDataChanged" xml:space="preserve">
-    <value>Metadata for field '{0}' of record '{1}' did not match the original record's metadata.</value>
-  </data>
-  <data name="SQL_EnumeratedRecordFieldCountChanged" xml:space="preserve">
-    <value>Number of fields in record '{0}' does not match the number in the original record.</value>
-  </data>
-  <data name="GT_Disabled" xml:space="preserve">
-    <value>Global Transactions are not enabled for this Azure SQL Database. Please contact Azure SQL Database support for assistance.</value>
-  </data>
-  <data name="SQL_UnknownSysTxIsolationLevel" xml:space="preserve">
-    <value>Unrecognized System.Transactions.IsolationLevel enumeration value: {0}.</value>
-  </data>
-  <data name="SQLNotify_AlreadyHasCommand" xml:space="preserve">
-    <value>This SqlCommand object is already associated with another SqlDependency object.</value>
-  </data>
-  <data name="SqlDependency_DatabaseBrokerDisabled" xml:space="preserve">
-    <value>The SQL Server Service Broker for the current database is not enabled, and as a result query notifications are not supported.  Please enable the Service Broker for this database if you wish to use notifications.</value>
-  </data>
-  <data name="SqlDependency_DefaultOptionsButNoStart" xml:space="preserve">
-    <value>When using SqlDependency without providing an options value, SqlDependency.Start() must be called prior to execution of a command added to the SqlDependency instance.</value>
-  </data>
-  <data name="SqlDependency_NoMatchingServerStart" xml:space="preserve">
-    <value>When using SqlDependency without providing an options value, SqlDependency.Start() must be called for each server that is being executed against.</value>
-  </data>
-  <data name="SqlDependency_NoMatchingServerDatabaseStart" xml:space="preserve">
-    <value>SqlDependency.Start has been called for the server the command is executing against more than once, but there is no matching server/user/database Start() call for current command.</value>
-  </data>
-  <data name="SqlDependency_EventNoDuplicate" xml:space="preserve">
-    <value>SqlDependency.OnChange does not support multiple event registrations for the same delegate.</value>
-  </data>
-  <data name="SqlDependency_IdMismatch" xml:space="preserve">
-    <value>No SqlDependency exists for the key.</value>
-  </data>
-  <data name="SqlDependency_InvalidTimeout" xml:space="preserve">
-    <value>Timeout specified is invalid. Timeout cannot be &lt; 0.</value>
-  </data>
-  <data name="SqlDependency_DuplicateStart" xml:space="preserve">
-    <value>SqlDependency does not support calling Start() with different connection strings having the same server, user, and database in the same app domain.</value>
-  </data>
-  <data name="SqlMetaData_InvalidSqlDbTypeForConstructorFormat" xml:space="preserve">
-    <value>The dbType {0} is invalid for this constructor.</value>
-  </data>
-  <data name="SqlMetaData_NameTooLong" xml:space="preserve">
-    <value>The name is too long.</value>
-  </data>
-  <data name="SqlMetaData_SpecifyBothSortOrderAndOrdinal" xml:space="preserve">
-    <value>The sort order and ordinal must either both be specified, or neither should be specified (SortOrder.Unspecified and -1).  The values given were: order = {0}, ordinal = {1}.</value>
-  </data>
-  <data name="SqlProvider_InvalidDataColumnType" xml:space="preserve">
-    <value>The type of column '{0}' is not supported.  The type is '{1}'</value>
-  </data>
-  <data name="SqlProvider_NotEnoughColumnsInStructuredType" xml:space="preserve">
-    <value>There are not enough fields in the Structured type.  Structured types must have at least one field.</value>
-  </data>
-  <data name="SqlProvider_DuplicateSortOrdinal" xml:space="preserve">
-    <value>The sort ordinal {0} was specified twice.</value>
-  </data>
-  <data name="SqlProvider_MissingSortOrdinal" xml:space="preserve">
-    <value>The sort ordinal {0} was not specified.</value>
-  </data>
-  <data name="SqlProvider_SortOrdinalGreaterThanFieldCount" xml:space="preserve">
-    <value>The sort ordinal {0} on field {1} exceeds the total number of fields.</value>
-  </data>
-  <data name="SQLUDT_MaxByteSizeValue" xml:space="preserve">
-    <value>range: 0-8000</value>
-  </data>
-  <data name="SQLUDT_Unexpected" xml:space="preserve">
-    <value>unexpected error encountered in SqlClient data provider. {0}</value>
-  </data>
-  <data name="SQLUDT_UnexpectedUdtTypeName" xml:space="preserve">
-    <value>UdtTypeName property must be set only for UDT parameters.</value>
-  </data>
-  <data name="SQLUDT_InvalidUdtTypeName" xml:space="preserve">
-    <value>UdtTypeName property must be set for UDT parameters.</value>
-  </data>
-  <data name="SqlUdt_InvalidUdtMessage" xml:space="preserve">
-    <value>'{0}' is an invalid user defined type, reason: {1}.</value>
-  </data>
-  <data name="SQL_UDTTypeName" xml:space="preserve">
-    <value>SqlParameter.UdtTypeName is an invalid multipart name</value>
-  </data>
-  <data name="SQL_InvalidUdt3PartNameFormat" xml:space="preserve">
-    <value>Invalid 3 part name format for UdtTypeName.</value>
-  </data>
-  <data name="IEnumerableOfSqlDataRecordHasNoRows" xml:space="preserve">
-    <value>There are no records in the SqlDataRecord enumeration. To send a table-valued parameter with no rows, use a null reference for the value instead.</value>
-  </data>
-  <data name="SNI_ERROR_1" xml:space="preserve">
-    <value>I/O Error detected in read/write operation</value>
-  </data>
-  <data name="SNI_ERROR_2" xml:space="preserve">
-    <value>Connection was terminated</value>
-  </data>
-  <data name="SNI_ERROR_3" xml:space="preserve">
-    <value>Asynchronous operations not supported</value>
-  </data>
-  <data name="SNI_ERROR_5" xml:space="preserve">
-    <value>Invalid parameter(s) found</value>
-  </data>
-  <data name="SNI_ERROR_6" xml:space="preserve">
-    <value>Unsupported protocol specified</value>
-  </data>
-  <data name="SNI_ERROR_7" xml:space="preserve">
-    <value>Invalid connection found when setting up new session protocol</value>
-  </data>
-  <data name="SNI_ERROR_8" xml:space="preserve">
-    <value>Protocol not supported</value>
-  </data>
-  <data name="SNI_ERROR_9" xml:space="preserve">
-    <value>Associating port with I/O completion mechanism failed</value>
-  </data>
-  <data name="SNI_ERROR_11" xml:space="preserve">
-    <value>Timeout error</value>
-  </data>
-  <data name="SNI_ERROR_12" xml:space="preserve">
-    <value>No server name supplied</value>
-  </data>
-  <data name="SNI_ERROR_13" xml:space="preserve">
-    <value>TerminateListener() has been called</value>
-  </data>
-  <data name="SNI_ERROR_14" xml:space="preserve">
-    <value>Win9x not supported</value>
-  </data>
-  <data name="SNI_ERROR_15" xml:space="preserve">
-    <value>Function not supported</value>
-  </data>
-  <data name="SNI_ERROR_16" xml:space="preserve">
-    <value>Shared-Memory heap error</value>
-  </data>
-  <data name="SNI_ERROR_17" xml:space="preserve">
-    <value>Cannot find an ip/ipv6 type address to connect</value>
-  </data>
-  <data name="SNI_ERROR_18" xml:space="preserve">
-    <value>Connection has been closed by peer</value>
-  </data>
-  <data name="SNI_ERROR_19" xml:space="preserve">
-    <value>Physical connection is not usable</value>
-  </data>
-  <data name="SNI_ERROR_20" xml:space="preserve">
-    <value>Connection has been closed</value>
-  </data>
-  <data name="SNI_ERROR_21" xml:space="preserve">
-    <value>Encryption is enforced but there is no valid certificate</value>
-  </data>
-  <data name="SNI_ERROR_22" xml:space="preserve">
-    <value>Couldn't load library</value>
-  </data>
-  <data name="SNI_ERROR_23" xml:space="preserve">
-    <value>Cannot open a new thread in server process</value>
-  </data>
-  <data name="SNI_ERROR_24" xml:space="preserve">
-    <value>Cannot post event to completion port</value>
-  </data>
-  <data name="SNI_ERROR_25" xml:space="preserve">
-    <value>Connection string is not valid</value>
-  </data>
-  <data name="SNI_ERROR_26" xml:space="preserve">
-    <value>Error Locating Server/Instance Specified</value>
-  </data>
-  <data name="SNI_ERROR_27" xml:space="preserve">
-    <value>Error getting enabled protocols list from registry</value>
-  </data>
-  <data name="SNI_ERROR_28" xml:space="preserve">
-    <value>Server doesn't support requested protocol</value>
-  </data>
-  <data name="SNI_ERROR_29" xml:space="preserve">
-    <value>Shared Memory is not supported for clustered server connectivity</value>
-  </data>
-  <data name="SNI_ERROR_30" xml:space="preserve">
-    <value>Invalid attempt bind to shared memory segment</value>
-  </data>
-  <data name="SNI_ERROR_31" xml:space="preserve">
-    <value>Encryption(ssl/tls) handshake failed</value>
-  </data>
-  <data name="SNI_ERROR_32" xml:space="preserve">
-    <value>Packet size too large for SSL Encrypt/Decrypt operations</value>
-  </data>
-  <data name="SNI_ERROR_33" xml:space="preserve">
-    <value>SSRP error</value>
-  </data>
-  <data name="SNI_ERROR_34" xml:space="preserve">
-    <value>Could not connect to the Shared Memory pipe</value>
-  </data>
-  <data name="SNI_ERROR_35" xml:space="preserve">
-    <value>An internal exception was caught</value>
-  </data>
-  <data name="SNI_ERROR_36" xml:space="preserve">
-    <value>The Shared Memory dll used to connect to SQL Server 2000 was not found</value>
-  </data>
-  <data name="SNI_ERROR_37" xml:space="preserve">
-    <value>The SQL Server 2000 Shared Memory client dll appears to be invalid/corrupted</value>
-  </data>
-  <data name="SNI_ERROR_38" xml:space="preserve">
-    <value>Cannot open a Shared Memory connection to SQL Server 2000</value>
-  </data>
-  <data name="SNI_ERROR_39" xml:space="preserve">
-    <value>Shared memory connectivity to SQL Server 2000 is either disabled or not available on this machine</value>
-  </data>
-  <data name="SNI_ERROR_40" xml:space="preserve">
-    <value>Could not open a connection to SQL Server</value>
-  </data>
-  <data name="SNI_ERROR_41" xml:space="preserve">
-    <value>Cannot open a Shared Memory connection to a remote SQL server</value>
-  </data>
-  <data name="SNI_ERROR_42" xml:space="preserve">
-    <value>Could not establish dedicated administrator connection (DAC) on default port. Make sure that DAC is enabled</value>
-  </data>
-  <data name="SNI_ERROR_43" xml:space="preserve">
-    <value>An error occurred while obtaining the dedicated administrator connection (DAC) port. Make sure that SQL Browser is running, or check the error log for the port number</value>
-  </data>
-  <data name="SNI_ERROR_44" xml:space="preserve">
-    <value>Could not compose Service Principal Name (SPN) for Windows Integrated Authentication. Possible causes are server(s) incorrectly specified to connection API calls, Domain Name System (DNS) lookup failure or memory shortage</value>
-  </data>
-  <data name="SNI_ERROR_47" xml:space="preserve">
-    <value>Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported.</value>
-  </data>
-  <data name="SNI_ERROR_48" xml:space="preserve">
-    <value>Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported.</value>
-  </data>
-  <data name="SNI_ERROR_49" xml:space="preserve">
-    <value>Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol.</value>
-  </data>
-  <data name="SNI_ERROR_50" xml:space="preserve">
-    <value>Local Database Runtime error occurred. </value>
-  </data>
-  <data name="SNI_ERROR_51" xml:space="preserve">
-    <value>An instance name was not specified while connecting to a Local Database Runtime. Specify an instance name in the format (localdb)\instance_name.</value>
-  </data>
-  <data name="SNI_ERROR_52" xml:space="preserve">
-    <value>Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.</value>
-  </data>
-  <data name="SNI_ERROR_53" xml:space="preserve">
-    <value>Invalid Local Database Runtime registry configuration found. Verify that SQL Server Express is properly installed.</value>
-  </data>
-  <data name="SNI_ERROR_54" xml:space="preserve">
-    <value>Unable to locate the registry entry for SQLUserInstance.dll file path. Verify that the Local Database Runtime feature of SQL Server Express is properly installed.</value>
-  </data>
-  <data name="SNI_ERROR_55" xml:space="preserve">
-    <value>Registry value contains an invalid SQLUserInstance.dll file path. Verify that the Local Database Runtime feature of SQL Server Express is properly installed.</value>
-  </data>
-  <data name="SNI_ERROR_56" xml:space="preserve">
-    <value>Unable to load the SQLUserInstance.dll from the location specified in the registry. Verify that the Local Database Runtime feature of SQL Server Express is properly installed.</value>
-  </data>
-  <data name="SNI_ERROR_57" xml:space="preserve">
-    <value>Invalid SQLUserInstance.dll found at the location specified in the registry. Verify that the Local Database Runtime feature of SQL Server Express is properly installed.</value>
-  </data>
-  <data name="Snix_Connect" xml:space="preserve">
-    <value>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.</value>
-  </data>
-  <data name="Snix_PreLoginBeforeSuccessfulWrite" xml:space="preserve">
-    <value>The client was unable to establish a connection because of an error during connection initialization process before login. Possible causes include the following:  the client tried to connect to an unsupported version of SQL Server; the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server.</value>
-  </data>
-  <data name="Snix_PreLogin" xml:space="preserve">
-    <value>A connection was successfully established with the server, but then an error occurred during the pre-login handshake.</value>
-  </data>
-  <data name="Snix_LoginSspi" xml:space="preserve">
-    <value>A connection was successfully established with the server, but then an error occurred when obtaining the security/SSPI context information for integrated security login.</value>
-  </data>
-  <data name="Snix_Login" xml:space="preserve">
-    <value>A connection was successfully established with the server, but then an error occurred during the login process.</value>
-  </data>
-  <data name="Snix_EnableMars" xml:space="preserve">
-    <value>Connection open and login was successful, but then an error occurred while enabling MARS for this connection.</value>
-  </data>
-  <data name="Snix_AutoEnlist" xml:space="preserve">
-    <value>Connection open and login was successful, but then an error occurred while enlisting the connection into the current distributed transaction.</value>
-  </data>
-  <data name="Snix_GetMarsSession" xml:space="preserve">
-    <value>Failed to establish a MARS session in preparation to send the request to the server.</value>
-  </data>
-  <data name="Snix_Execute" xml:space="preserve">
-    <value>A transport-level error has occurred when sending the request to the server.</value>
-  </data>
-  <data name="Snix_Read" xml:space="preserve">
-    <value>A transport-level error has occurred when receiving results from the server.</value>
-  </data>
-  <data name="Snix_Close" xml:space="preserve">
-    <value>A transport-level error has occurred during connection clean-up.</value>
-  </data>
-  <data name="Snix_SendRows" xml:space="preserve">
-    <value>A transport-level error has occurred while sending information to the server.</value>
-  </data>
-  <data name="Snix_ProcessSspi" xml:space="preserve">
-    <value>A transport-level error has occurred during SSPI handshake.</value>
-  </data>
-  <data name="LocalDB_FailedGetDLLHandle" xml:space="preserve">
-    <value>Local Database Runtime: Cannot load SQLUserInstance.dll.</value>
-  </data>
-  <data name="LocalDB_MethodNotFound" xml:space="preserve">
-    <value>Invalid SQLUserInstance.dll found at the location specified in the registry. Verify that the Local Database Runtime feature of SQL Server Express is properly installed.</value>
-  </data>
-  <data name="LocalDB_UnobtainableMessage" xml:space="preserve">
-    <value>Cannot obtain Local Database Runtime error message</value>
-  </data>
-  <data name="SQLROR_RecursiveRoutingNotSupported" xml:space="preserve">
-    <value>Two or more redirections have occurred. Only one redirection per login is allowed.</value>
-  </data>
-  <data name="SQLROR_FailoverNotSupported" xml:space="preserve">
-    <value>Connecting to a mirrored SQL Server instance using the ApplicationIntent ReadOnly connection option is not supported.</value>
-  </data>
-  <data name="SQLROR_UnexpectedRoutingInfo" xml:space="preserve">
-    <value>Unexpected routing information received.</value>
-  </data>
-  <data name="SQLROR_InvalidRoutingInfo" xml:space="preserve">
-    <value>Invalid routing information received.</value>
-  </data>
-  <data name="SQLROR_TimeoutAfterRoutingInfo" xml:space="preserve">
-    <value>Server provided routing information, but timeout already expired.</value>
-  </data>
-  <data name="SQLCR_InvalidConnectRetryCountValue" xml:space="preserve">
-    <value>Invalid ConnectRetryCount value (should be 0-255).</value>
-  </data>
-  <data name="SQLCR_InvalidConnectRetryIntervalValue" xml:space="preserve">
-    <value>Invalid ConnectRetryInterval value (should be 1-60).</value>
-  </data>
-  <data name="SQLCR_NextAttemptWillExceedQueryTimeout" xml:space="preserve">
-    <value>Next reconnection attempt will exceed query timeout. Reconnection was terminated.</value>
-  </data>
-  <data name="SQLCR_EncryptionChanged" xml:space="preserve">
-    <value>The server did not preserve SSL encryption during a recovery attempt, connection recovery is not possible.</value>
-  </data>
-  <data name="SQLCR_TDSVestionNotPreserved" xml:space="preserve">
-    <value>The server did not preserve the exact client TDS version requested during a recovery attempt, connection recovery is not possible.</value>
-  </data>
-  <data name="SQLCR_AllAttemptsFailed" xml:space="preserve">
-    <value>The connection is broken and recovery is not possible.  The client driver attempted to recover the connection one or more times and all attempts failed.  Increase the value of ConnectRetryCount to increase the number of recovery attempts.</value>
-  </data>
-  <data name="SQLCR_UnrecoverableServer" xml:space="preserve">
-    <value>The connection is broken and recovery is not possible.  The connection is marked by the server as unrecoverable.  No attempt was made to restore the connection.</value>
-  </data>
-  <data name="SQLCR_UnrecoverableClient" xml:space="preserve">
-    <value>The connection is broken and recovery is not possible.  The connection is marked by the client driver as unrecoverable.  No attempt was made to restore the connection.</value>
-  </data>
-  <data name="SQLCR_NoCRAckAtReconnection" xml:space="preserve">
-    <value>The server did not acknowledge a recovery attempt, connection recovery is not possible.</value>
-  </data>
-  <data name="SQL_UnsupportedKeyword" xml:space="preserve">
-    <value>The keyword '{0}' is not supported on this platform.</value>
-  </data>
-  <data name="SQL_UnsupportedFeature" xml:space="preserve">
-    <value>The server is attempting to use a feature that is not supported on this platform.</value>
-  </data>
-  <data name="SQL_UnsupportedToken" xml:space="preserve">
-    <value>Received an unsupported token '{0}' while reading data from the server.</value>
-  </data>
-  <data name="SQL_DbTypeNotSupportedOnThisPlatform" xml:space="preserve">
-    <value>Type {0} is not supported on this platform.</value>
-  </data>
-  <data name="SQL_NetworkLibraryNotSupported" xml:space="preserve">
-    <value>The keyword 'Network Library' is not supported on this platform, prefix the 'Data Source' with the protocol desired instead ('tcp:' for a TCP connection, or 'np:' for a Named Pipe connection).</value>
-  </data>
-  <data name="SNI_PN0" xml:space="preserve">
-    <value>HTTP Provider</value>
-  </data>
-  <data name="SNI_PN1" xml:space="preserve">
-    <value>Named Pipes Provider</value>
-  </data>
-  <data name="SNI_PN2" xml:space="preserve">
-    <value>Session Provider</value>
-  </data>
-  <data name="SNI_PN3" xml:space="preserve">
-    <value>Sign Provider</value>
-  </data>
-  <data name="SNI_PN4" xml:space="preserve">
-    <value>Shared Memory Provider</value>
-  </data>
-  <data name="SNI_PN5" xml:space="preserve">
-    <value>SMux Provider</value>
-  </data>
-  <data name="SNI_PN6" xml:space="preserve">
-    <value>SSL Provider</value>
-  </data>
-  <data name="SNI_PN7" xml:space="preserve">
-    <value>TCP Provider</value>
-  </data>
-  <data name="SNI_PN8" xml:space="preserve">
-    <value />
-  </data>
-  <data name="SNI_PN9" xml:space="preserve">
-    <value>SQL Network Interfaces</value>
-  </data>
-  <data name="AZURESQL_GenericEndpoint" xml:space="preserve">
-    <value>.database.windows.net</value>
-  </data>
-  <data name="AZURESQL_GermanEndpoint" xml:space="preserve">
-    <value>.database.cloudapi.de</value>
-  </data>
-  <data name="AZURESQL_UsGovEndpoint" xml:space="preserve">
-    <value>.database.usgovcloudapi.net</value>
-  </data>
-  <data name="AZURESQL_ChinaEndpoint" xml:space="preserve">
-    <value>.database.chinacloudapi.cn</value>
-  </data>
-  <data name="net_gssapi_operation_failed_detailed" xml:space="preserve">
-    <value>GSSAPI operation failed with error - {0} ({1}).</value>
-  </data>
-  <data name="net_gssapi_operation_failed" xml:space="preserve">
-    <value>GSSAPI operation failed with status: {0} (Minor status: {1}).</value>
-  </data>
-  <data name="net_gssapi_operation_failed_detailed_majoronly" xml:space="preserve">
-    <value>GSSAPI operation failed with error - {0}.</value>
-  </data>
-  <data name="net_gssapi_operation_failed_majoronly" xml:space="preserve">
-    <value>GSSAPI operation failed with status: {0}.</value>
-  </data>
-  <data name="net_gssapi_ntlm_missing_plugin" xml:space="preserve">
-    <value>NTLM authentication requires the GSSAPI plugin 'gss-ntlmssp'.</value>
-  </data>
-  <data name="net_ntlm_not_possible_default_cred" xml:space="preserve">
-    <value>NTLM authentication is not possible with default credentials on this platform.</value>
-  </data>
-  <data name="net_nego_not_supported_empty_target_with_defaultcreds" xml:space="preserve">
-    <value>Target name should be non empty if default credentials are passed.</value>
-  </data>
-  <data name="net_nego_server_not_supported" xml:space="preserve">
-    <value>Server implementation is not supported</value>
-  </data>
-  <data name="net_nego_protection_level_not_supported" xml:space="preserve">
-    <value>Requested protection level is not supported with the GSSAPI implementation currently installed.</value>
-  </data>
-  <data name="net_context_buffer_too_small" xml:space="preserve">
-    <value>Insufficient buffer space. Required: {0} Actual: {1}.</value>
-  </data>
-  <data name="net_auth_message_not_encrypted" xml:space="preserve">
-    <value>Protocol error: A received message contains a valid signature but it was not encrypted as required by the effective Protection Level.</value>
-  </data>
-  <data name="net_securitypackagesupport" xml:space="preserve">
-    <value>The requested security package is not supported.</value>
-  </data>
-  <data name="net_log_operation_failed_with_error" xml:space="preserve">
-    <value>{0} failed with error {1}.</value>
-  </data>
-  <data name="net_MethodNotImplementedException" xml:space="preserve">
-    <value>This method is not implemented by this class.</value>
-  </data>
-  <data name="event_OperationReturnedSomething" xml:space="preserve">
-    <value>{0} returned {1}.</value>
-  </data>
-  <data name="net_invalid_enum" xml:space="preserve">
-    <value>The specified value is not valid in the '{0}' enumeration.</value>
-  </data>
-  <data name="SSPIInvalidHandleType" xml:space="preserve">
-    <value>'{0}' is not a supported handle type.</value>
-  </data>
-  <data name="LocalDBNotSupported" xml:space="preserve">
-    <value>LocalDB is not supported on this platform.</value>
-  </data>
-  <data name="PlatformNotSupported_DataSqlClient" xml:space="preserve">
-    <value>System.Data.SqlClient is not supported on this platform.</value>
-  </data>
-  <data name="SqlParameter_InvalidTableDerivedPrecisionForTvp" xml:space="preserve">
-    <value>Precision '{0}' required to send all values in column '{1}' exceeds the maximum supported precision '{2}'. The values must all fit in a single precision.</value>
-  </data>
-  <data name="SqlProvider_InvalidDataColumnMaxLength" xml:space="preserve">
-    <value>The size of column '{0}' is not supported. The size is {1}.</value>
-  </data>
-  <data name="MDF_InvalidXmlInvalidValue" xml:space="preserve">
-    <value>The metadata XML is invalid. The {1} column of the {0} collection must contain a non-empty string.</value>
-  </data>
-  <data name="MDF_CollectionNameISNotUnique" xml:space="preserve">
-    <value>There are multiple collections named '{0}'.</value>
-  </data>
-  <data name="MDF_InvalidXmlMissingColumn" xml:space="preserve">
-    <value>The metadata XML is invalid. The {0} collection must contain a {1} column and it must be a string column.</value>
-  </data>
-  <data name="MDF_InvalidXml" xml:space="preserve">
-    <value>The metadata XML is invalid.</value>
-  </data>
-  <data name="MDF_NoColumns" xml:space="preserve">
-    <value>The schema table contains no columns.</value>
-  </data>
-  <data name="MDF_QueryFailed" xml:space="preserve">
-    <value>Unable to build the '{0}' collection because execution of the SQL query failed. See the inner exception for details.</value>
-  </data>
-  <data name="MDF_TooManyRestrictions" xml:space="preserve">
-    <value>More restrictions were provided than the requested schema ('{0}') supports.</value>
-  </data>
-  <data name="MDF_DataTableDoesNotExist" xml:space="preserve">
-    <value>The collection '{0}' is missing from the metadata XML.</value>
-  </data>
-  <data name="MDF_UndefinedCollection" xml:space="preserve">
-    <value>The requested collection ({0}) is not defined.</value>
-  </data>
-  <data name="MDF_UnsupportedVersion" xml:space="preserve">
-    <value>The requested collection ({0}) is not supported by this version of the provider.</value>
-  </data>
-  <data name="MDF_MissingRestrictionColumn" xml:space="preserve">
-    <value>One or more of the required columns of the restrictions collection is missing.</value>
-  </data>
-  <data name="MDF_MissingRestrictionRow" xml:space="preserve">
-    <value>A restriction exists for which there is no matching row in the restrictions collection.</value>
-  </data>
-  <data name="MDF_IncorrectNumberOfDataSourceInformationRows" xml:space="preserve">
-    <value>The DataSourceInformation table must contain exactly one row.</value>
-  </data>
-  <data name="MDF_MissingDataSourceInformationColumn" xml:space="preserve">
-    <value>One of the required DataSourceInformation tables columns is missing.</value>
-  </data>
-  <data name="MDF_AmbigousCollectionName" xml:space="preserve">
-    <value>The collection name '{0}' matches at least two collections with the same name but with different case, but does not match any of them exactly.</value>
-  </data>
-  <data name="MDF_UnableToBuildCollection" xml:space="preserve">
-    <value>Unable to build schema collection '{0}';</value>
-  </data>
-  <data name="ADP_InvalidArgumentLength" xml:space="preserve">
-    <value>The length of argument '{0}' exceeds its limit of '{1}'.</value>
-  </data>
-  <data name="ADP_MustBeReadOnly" xml:space="preserve">
-    <value>{0} must be marked as read only.</value>
-  </data>
-  <data name="ADP_InvalidMixedUsageOfSecureAndClearCredential" xml:space="preserve">
-    <value>Cannot use Credential with UserID, UID, Password, or PWD connection string keywords.</value>
-  </data>
-  <data name="ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity" xml:space="preserve">
-    <value>Cannot use Credential with Integrated Security connection string keyword.</value>
-  </data>
-  <data name="SQL_ChangePasswordArgumentMissing" xml:space="preserve">
-    <value>The '{0}' argument must not be null or empty.</value>
-  </data>
-  <data name="SQL_ChangePasswordConflictsWithSSPI" xml:space="preserve">
-    <value>ChangePassword can only be used with SQL authentication, not with integrated security.</value>
-  </data>
-  <data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
-    <value>ChangePassword requires SQL Server 9.0 or later.</value>
-  </data>
-  <data name="SQL_ChangePasswordUseOfUnallowedKey" xml:space="preserve">
-    <value>The keyword '{0}' must not be specified in the connectionString argument to ChangePassword.</value>
-  </data>
-  <data name="SQL_ParsingErrorWithState" xml:space="preserve">
-    <value>Internal connection fatal error. Error state: {0}.</value>
-  </data>
-  <data name="SQL_ParsingErrorValue" xml:space="preserve">
-    <value>Internal connection fatal error. Error state: {0}, Value: {1}.</value>
-  </data>
-  <data name="ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity" xml:space="preserve">
-    <value>Cannot set the AccessToken property if the 'Integrated Security' connection string keyword has been set to 'true' or 'SSPI'.</value>
-  </data>
-  <data name="ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword" xml:space="preserve">
-    <value>Cannot set the AccessToken property if 'UserID', 'UID', 'Password', or 'PWD' has been specified in connection string.</value>
-  </data>
-  <data name="ADP_InvalidMixedUsageOfCredentialAndAccessToken" xml:space="preserve">
-    <value>Cannot set the Credential property if the AccessToken property is already set.</value>
-  </data>
- <data name="SQL_ParsingErrorFeatureId" xml:space="preserve"> 
-    <value>Internal connection fatal error. Error state: {0}, Feature Id: {1}.</value>
-  </data>
-  <data name="SQL_ParsingErrorAuthLibraryType" xml:space="preserve"> 
-    <value>Internal connection fatal error. Error state: {0}, Authentication Library Type: {1}.</value>
-  </data>
-  <data name="SqlFileStream_InvalidPath" xml:space="preserve">
-    <value>The path name is not valid.</value>
-  </data>
-  <data name="SqlFileStream_PathNotValidDiskResource" xml:space="preserve">
-    <value>The path name is invalid or does not point to a disk file.</value>
-  </data>
-  <data name="SqlFileStream_FileAlreadyInTransaction" xml:space="preserve">
-    <value>The process cannot access the file specified because it has been opened in another transaction.</value>
-  </data>
-  <data name="SqlFileStream_InvalidParameter" xml:space="preserve">
-    <value>An invalid parameter was passed to the function.</value>
-  </data>
-  <data name="SqlFileStream_NotSupported" xml:space="preserve">
-    <value>SqlFileStream is not supported on this platform.</value>
-  </data>
-</root>
diff --git a/src/libraries/System.Data.SqlClient/src/Resources/System.Data.SqlClient.SqlMetaData.xml b/src/libraries/System.Data.SqlClient/src/Resources/System.Data.SqlClient.SqlMetaData.xml
deleted file mode 100644 (file)
index 35d3cfa..0000000
+++ /dev/null
@@ -1,2539 +0,0 @@
-<?xml version="1.0" standalone="yes"?>
-<NewDataSet>
-  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
-    <xs:element name="NewDataSet" msdata:IsDataSet="true">
-      <xs:complexType>
-        <xs:choice minOccurs="0" maxOccurs="unbounded">
-          <xs:element name="MetaDataCollections" msdata:MinimumCapacity="9">
-            <xs:complexType>
-              <xs:sequence>
-                <xs:element name="CollectionName" type="xs:string" minOccurs="0" />
-                <xs:element name="NumberOfRestrictions" type="xs:int" minOccurs="0" />
-                <xs:element name="NumberOfIdentifierParts" type="xs:int" minOccurs="0" />
-                <xs:element name="PopulationMechanism" type="xs:string" minOccurs="0" />
-                <xs:element name="PopulationString" type="xs:string" minOccurs="0" />
-                <xs:element name="MinimumVersion" type="xs:string" minOccurs="0" />
-                <xs:element name="MaximumVersion" type="xs:string" minOccurs="0" />
-              </xs:sequence>
-            </xs:complexType>
-          </xs:element>
-          <xs:element name="Restrictions" msdata:MinimumCapacity="3">
-            <xs:complexType>
-              <xs:sequence>
-                <xs:element name="CollectionName" type="xs:string" minOccurs="0" />
-                <xs:element name="RestrictionName" type="xs:string" minOccurs="0" />
-                <xs:element name="ParameterName" type="xs:string" minOccurs="0" />
-                <xs:element name="RestrictionDefault" type="xs:string" minOccurs="0" />
-                <xs:element name="RestrictionNumber" type="xs:int" minOccurs="0" />
-                <xs:element name="MinimumVersion" type="xs:string" minOccurs="0" />
-                <xs:element name="MaximumVersion" type="xs:string" minOccurs="0" />
-               </xs:sequence>
-            </xs:complexType>
-          </xs:element>
-          <xs:element name="DataSourceInformation" msdata:MinimumCapacity="18">
-            <xs:complexType>
-              <xs:sequence>
-                <xs:element name="CompositeIdentifierSeparatorPattern" type="xs:string" minOccurs="0" />
-                <xs:element name="DataSourceProductName" type="xs:string" minOccurs="0" />
-                <xs:element name="DataSourceProductVersion" type="xs:string" minOccurs="0" />
-                <xs:element name="DataSourceProductVersionNormalized" type="xs:string" minOccurs="0" />
-                <xs:element name="GroupByBehavior" msdata:DataType="System.Data.Common.GroupByBehavior, System.Data, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="xs:string" minOccurs="0" />
-                <xs:element name="IdentifierPattern" type="xs:string" minOccurs="0" />
-                <xs:element name="IdentifierCase" msdata:DataType="System.Data.Common.IdentifierCase, System.Data, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="xs:string" minOccurs="0" />
-                <xs:element name="OrderByColumnsInSelect" type="xs:boolean" minOccurs="0" />
-                <xs:element name="ParameterMarkerFormat" type="xs:string" minOccurs="0" />
-                <xs:element name="ParameterMarkerPattern" type="xs:string" minOccurs="0" />
-                <xs:element name="ParameterNameMaxLength" type="xs:int" minOccurs="0" />
-                <xs:element name="ParameterNamePattern" type="xs:string" minOccurs="0" />
-                <xs:element name="QuotedIdentifierPattern" type="xs:string" minOccurs="0" />
-                <xs:element name="QuotedIdentifierCase" msdata:DataType="System.Data.Common.IdentifierCase, System.Data, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="xs:string" minOccurs="0" />
-                <xs:element name="StatementSeparatorPattern" type="xs:string" minOccurs="0" />
-                <xs:element name="StringLiteralPattern" type="xs:string" minOccurs="0" />
-                <xs:element name="SupportedJoinOperators" msdata:DataType="System.Data.Common.SupportedJoinOperators, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="xs:string" minOccurs="0" />
-              </xs:sequence>
-            </xs:complexType>
-          </xs:element>
-          <xs:element name="DataTypes" msdata:MinimumCapacity="18">
-            <xs:complexType>
-              <xs:sequence>
-                <xs:element name="TypeName" type="xs:string" minOccurs="0" />
-                <xs:element name="ProviderDbType" type="xs:int" minOccurs="0" />
-                <xs:element name="ColumnSize" type="xs:long" minOccurs="0" />
-                <xs:element name="CreateFormat" type="xs:string" minOccurs="0" />
-                <xs:element name="CreateParameters" type="xs:string" minOccurs="0" />
-                <xs:element name="DataType" type="xs:string" minOccurs="0" />
-                <xs:element name="IsAutoIncrementable" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsBestMatch" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsCaseSensitive" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsFixedLength" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsFixedPrecisionScale" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsLong" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsNullable" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsSearchable" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsSearchableWithLike" type="xs:boolean" minOccurs="0" />
-                <xs:element name="IsUnsigned" type="xs:boolean" minOccurs="0" />
-                <xs:element name="MaximumScale" type="xs:short" minOccurs="0" />
-                <xs:element name="MinimumScale" type="xs:short" minOccurs="0" />
-                <xs:element name="IsConcurrencyType" type="xs:boolean" minOccurs="0" />
-                <xs:element name="MaximumVersion" type="xs:string" minOccurs="0" />
-                <xs:element name="MinimumVersion" type="xs:string" minOccurs="0" />
-                <xs:element name="IsLiteralSupported" type="xs:boolean" minOccurs="0" />
-                <xs:element name="LiteralPrefix" type="xs:string" minOccurs="0" />
-                <xs:element name="LiteralSuffix" type="xs:string" minOccurs="0" />
-              </xs:sequence>
-            </xs:complexType>
-          </xs:element>
-          <xs:element name="ReservedWords" msdata:MinimumCapacity="3">
-            <xs:complexType>
-              <xs:sequence>
-                <xs:element name="ReservedWord" type="xs:string" minOccurs="0" />
-                <xs:element name="MaximumVersion" type="xs:string" minOccurs="0" />
-                <xs:element name="MinimumVersion" type="xs:string" minOccurs="0" />
-              </xs:sequence>
-            </xs:complexType>
-          </xs:element>
-        </xs:choice>
-      </xs:complexType>
-    </xs:element>
-  </xs:schema>
-  <MetaDataCollections>
-    <CollectionName>MetaDataCollections</CollectionName>
-    <NumberOfRestrictions>0</NumberOfRestrictions>
-    <NumberOfIdentifierParts>0</NumberOfIdentifierParts>
-    <PopulationMechanism>DataTable</PopulationMechanism>
-    <PopulationString>MetaDataCollections</PopulationString>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>DataSourceInformation</CollectionName>
-    <NumberOfRestrictions>0</NumberOfRestrictions>
-    <NumberOfIdentifierParts>0</NumberOfIdentifierParts>
-    <PopulationMechanism>DataTable</PopulationMechanism>
-    <PopulationString>DataSourceInformation</PopulationString>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>DataTypes</CollectionName>
-    <NumberOfRestrictions>0</NumberOfRestrictions>
-    <NumberOfIdentifierParts>0</NumberOfIdentifierParts>
-    <PopulationMechanism>PrepareCollection</PopulationMechanism>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Restrictions</CollectionName>
-    <NumberOfRestrictions>0</NumberOfRestrictions>
-    <NumberOfIdentifierParts>0</NumberOfIdentifierParts>
-    <PopulationMechanism>DataTable</PopulationMechanism>
-    <PopulationString>Restrictions</PopulationString>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>ReservedWords</CollectionName>
-    <NumberOfRestrictions>0</NumberOfRestrictions>
-    <NumberOfIdentifierParts>0</NumberOfIdentifierParts>
-    <PopulationMechanism>DataTable</PopulationMechanism>
-    <PopulationString>ReservedWords</PopulationString>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Users</CollectionName>
-    <NumberOfRestrictions>1</NumberOfRestrictions>
-    <NumberOfIdentifierParts>1</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select uid, name as user_name, createdate, updatedate from sysusers where (name = @Name or (@Name is null))</PopulationString>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Databases</CollectionName>
-    <NumberOfRestrictions>1</NumberOfRestrictions>
-    <NumberOfIdentifierParts>1</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select name as database_name, dbid, crdate as create_date from master..sysdatabases where (name = @Name or (@Name is null))</PopulationString>
-    <MaximumVersion>09.99.999.9</MaximumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Databases</CollectionName>
-    <NumberOfRestrictions>1</NumberOfRestrictions>
-    <NumberOfIdentifierParts>1</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>IF OBJECT_ID('master..sysdatabases') IS NULL EXEC sp_executesql N'select name as database_name, dbid, crdate as create_date from sysdatabases where (name = @Name or (@Name is null))',N'@Name NVARCHAR(128)',@Name=@Name ELSE EXEC sp_executesql N'select name as database_name, dbid, crdate as create_date from master..sysdatabases where (name = @Name or (@Name is null))',N'@Name NVARCHAR(128)',@Name=@Name</PopulationString>
-    <MinimumVersion>10.00.000.0</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Tables</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE from INFORMATION_SCHEMA.TABLES where (TABLE_CATALOG = @Catalog or (@Catalog is null)) and (TABLE_SCHEMA = @Owner or (@Owner is null)) and (TABLE_NAME = @Name or (@Name is null)) and (TABLE_TYPE = @TableType or (@TableType is null))</PopulationString>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Columns</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH, NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE, DATETIME_PRECISION, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, CHARACTER_SET_NAME, COLLATION_CATALOG from INFORMATION_SCHEMA.COLUMNS where (TABLE_CATALOG = @Catalog or (@Catalog is null)) and (TABLE_SCHEMA = @Owner or (@Owner is null)) and (TABLE_NAME = @Table or (@Table is null)) and (COLUMN_NAME = @Column or (@Column is null)) order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME</PopulationString>
-    <MaximumVersion>09.99.999.9</MaximumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Columns</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>EXEC sys.sp_columns_managed @Catalog, @Owner, @Table, @Column, 0</PopulationString>
-    <MinimumVersion>10.00.000.0</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>AllColumns</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>EXEC sys.sp_columns_managed @Catalog, @Owner, @Table, @Column, 1</PopulationString>
-    <MinimumVersion>10.00.000.0</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>ColumnSetColumns</CollectionName>
-    <NumberOfRestrictions>3</NumberOfRestrictions>
-    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>EXEC sys.sp_columns_managed @Catalog, @Owner, @Table, null, 2</PopulationString>
-    <MinimumVersion>10.00.000.0</MinimumVersion>
-  </MetaDataCollections>
-<MetaDataCollections>
-    <CollectionName>StructuredTypeMembers</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>SELECT DB_NAME() AS TYPE_CATALOG, sc.name AS TYPE_SCHEMA, tt.name AS TYPE_NAME, c.name AS MEMBER_NAME, ColumnProperty(c.object_id, c.name, 'ordinal') AS ORDINAL_POSITION, convert(nvarchar(4000), object_definition(c.default_object_id)) AS MEMBER_DEFAULT,  convert(varchar(3), CASE c.is_nullable WHEN 1 THEN 'YES' ELSE 'NO' END) AS IS_NULLABLE, type_name(c.system_type_id) AS DATA_TYPE, ColumnProperty(c.object_id, c.name, 'charmaxlen') AS CHARACTER_MAXIMUM_LENGTH, ColumnProperty(c.object_id, c.name, 'octetmaxlen') AS CHARACTER_OCTET_LENGTH, convert(tinyint, CASE /* int/decimal/numeric/real/float/money */ WHEN c.system_type_id IN (48, 52, 56, 59, 60, 62, 106, 108, 122, 127) THEN c.precision END) AS NUMERIC_PRECISION, convert(smallint, CASE /* int/money/decimal/numeric */ WHEN c.system_type_id IN (48, 52, 56, 60, 106, 108, 122, 127) THEN 10 WHEN c.system_type_id IN (59, 62) THEN 2 END) AS NUMERIC_PRECISION_RADIX, /* real/float */ convert(int, CASE /* datetime/smalldatetime */ WHEN c.system_type_id IN (58, 61) THEN NULL ELSE odbcscale(c.system_type_id, c.scale) END) AS NUMERIC_SCALE, convert(smallint, CASE /* datetime/smalldatetime */ WHEN c.system_type_id IN (58, 61) THEN 3 END) AS DATETIME_PRECISION, convert(sysname, null) AS CHARACTER_SET_CATALOG, convert(sysname, null) AS CHARACTER_SET_SCHEMA, convert(sysname, CASE WHEN c.system_type_id IN (35, 167, 175) /*char/varchar/text*/ THEN CollationProperty(c.collation_name, 'sqlcharsetname') WHEN c.system_type_id IN (99, 231, 239) /*nchar/nvarchar/ntext*/ THEN N'UNICODE' END) AS CHARACTER_SET_NAME, convert(sysname, null) AS COLLATION_CATALOG FROM sys.schemas sc join sys.objects o on sc.schema_id = o.schema_id JOIN sys.table_types tt on o.object_id = tt.type_table_object_id JOIN sys.columns c ON c.object_id = o.object_id LEFT JOIN sys.types t ON c.user_type_id = t.user_type_id WHERE o.type IN ('TT') AND (DB_NAME() = @Catalog or (@Catalog is null)) and (sc.name = @Owner or (@Owner is null)) and (tt.name = @Type or (@Type is null)) and (c.name = @Member or (@Member is null)) order by sc.name, tt.name, c.name</PopulationString>
-    <MinimumVersion>09.00.000.0</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Views</CollectionName>
-    <NumberOfRestrictions>3</NumberOfRestrictions>
-    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CHECK_OPTION, IS_UPDATABLE from INFORMATION_SCHEMA.VIEWS where (TABLE_CATALOG = @Catalog or (@Catalog is null)) and (TABLE_SCHEMA = @Owner or (@Owner is null)) and (TABLE_NAME = @Table or (@Table is null)) order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME</PopulationString>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>ViewColumns</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME, TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE where (VIEW_CATALOG = @Catalog or (@Catalog is null)) and (VIEW_SCHEMA = @Owner or (@Owner is null)) and (VIEW_NAME = @Table or (@Table is null)) and (COLUMN_NAME = @Column or (@Column is null)) order by VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME</PopulationString>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>ProcedureParameters</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>1</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, ORDINAL_POSITION, PARAMETER_MODE, IS_RESULT, AS_LOCATOR, PARAMETER_NAME, CASE WHEN DATA_TYPE IS NULL THEN USER_DEFINED_TYPE_NAME WHEN DATA_TYPE = 'table type' THEN USER_DEFINED_TYPE_NAME ELSE DATA_TYPE END as DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH, COLLATION_CATALOG, COLLATION_SCHEMA, COLLATION_NAME, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, CHARACTER_SET_NAME, NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE, DATETIME_PRECISION, INTERVAL_TYPE, INTERVAL_PRECISION from INFORMATION_SCHEMA.PARAMETERS where (SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and (SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME = @Name or (@Name is null)) and (PARAMETER_NAME = @Parameter or (@Parameter is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, PARAMETER_NAME</PopulationString>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Procedures</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, CREATED, LAST_ALTERED from INFORMATION_SCHEMA.ROUTINES where (SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and (SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME = @Name or (@Name is null)) and (ROUTINE_TYPE = @Type or (@Type is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME</PopulationString>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>ForeignKeys</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, IS_DEFERRABLE, INITIALLY_DEFERRED from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where (CONSTRAINT_CATALOG = @Catalog or (@Catalog is null)) and (CONSTRAINT_SCHEMA = @Owner or (@Owner is null)) and (TABLE_NAME = @Table or (@Table is null)) and (CONSTRAINT_NAME = @Name or (@Name is null)) and CONSTRAINT_TYPE = 'FOREIGN KEY' order by CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME</PopulationString>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>IndexColumns</CollectionName>
-    <NumberOfRestrictions>5</NumberOfRestrictions>
-    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select distinct db_Name() as constraint_catalog, constraint_schema = user_name(o.uid), constraint_name = x.name, table_catalog  = db_name(), table_schema = user_name(o.uid), table_name = o.name, column_name = c.name, ordinal_position = convert(int, xk.keyno), KeyType  = c.xtype, index_name = x.name from sysobjects o, sysindexes x, syscolumns c, sysindexkeys xk where o.type in ('U') and x.id = o.id  and o.id = c.id and o.id = xk.id and x.indid = xk.indid and c.colid = xk.colid and xk.keyno &lt; = x.keycnt and permissions(o.id, c.name) &lt;&gt; 0  and (db_name() = @Catalog or (@Catalog is null)) and (user_name()= @Owner or (@Owner is null)) and (o.name = @Table or (@Table is null)) and (x.name = @ConstraintName or (@ConstraintName is null)) and (c.name = @Column or (@Column is null)) order by table_name, index_name</PopulationString>
-    <MaximumVersion>09.99.9999</MaximumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>IndexColumns</CollectionName>
-    <NumberOfRestrictions>5</NumberOfRestrictions>
-    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>EXEC sys.sp_indexcolumns_managed @Catalog, @Owner, @Table, @ConstraintName, @Column</PopulationString>
-    <MinimumVersion>10.00.0000</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Indexes</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select distinct db_Name() as constraint_catalog, constraint_schema = user_name(o.uid), constraint_name = x.name, table_catalog  = db_name(), table_schema = user_name(o.uid), table_name = o.name, index_name = x.name from sysobjects o, sysindexes x, sysindexkeys xk where o.type in ('U') and x.id = o.id  and o.id = xk.id and x.indid = xk.indid and xk.keyno &lt; = x.keycnt and (db_name() = @Catalog or (@Catalog is null)) and (user_name()= @Owner or (@Owner is null)) and (o.name = @Table or (@Table is null)) and (x.name = @Name or (@Name is null)) order by table_name, index_name</PopulationString>
-    <MaximumVersion>09.99.9999</MaximumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-    <CollectionName>Indexes</CollectionName>
-    <NumberOfRestrictions>4</NumberOfRestrictions>
-    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>EXEC sys.sp_indexes_managed @Catalog, @Owner, @Table, @Name</PopulationString>
-    <MinimumVersion>10.00.0000</MinimumVersion>
-  </MetaDataCollections>
-  <MetaDataCollections>
-   <CollectionName>UserDefinedTypes</CollectionName>
-    <NumberOfRestrictions>2</NumberOfRestrictions>
-    <NumberOfIdentifierParts>1</NumberOfIdentifierParts>
-    <PopulationMechanism>SQLCommand</PopulationMechanism>
-    <PopulationString>select assemblies.name as assembly_name, types.assembly_class as udt_name, ASSEMBLYPROPERTY(assemblies.name, 'VersionMajor') as version_major, ASSEMBLYPROPERTY(assemblies.name, 'VersionMinor') as version_minor, ASSEMBLYPROPERTY(assemblies.name, 'VersionBuild') as version_build, ASSEMBLYPROPERTY(assemblies.name, 'VersionRevision') as version_revision, ASSEMBLYPROPERTY(assemblies.name, 'CultureInfo') as culture_info, ASSEMBLYPROPERTY(assemblies.name, 'PublicKey') as public_key, is_fixed_length, max_length, Create_Date, Permission_set_desc from sys.assemblies as assemblies  join sys.assembly_types as types on assemblies.assembly_id = types.assembly_id where (assemblies.name = @AssemblyName or (@AssemblyName is null)) and (types.assembly_class = @UDTName or (@UDTName is null))</PopulationString>
-    <MinimumVersion>09.00.0000</MinimumVersion>
-  </MetaDataCollections>
-  <Restrictions>
-    <CollectionName>Users</CollectionName>
-    <RestrictionName>User_Name</RestrictionName>
-    <ParameterName>@Name</ParameterName>
-    <RestrictionDefault>name</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Databases</CollectionName>
-    <RestrictionName>Name</RestrictionName>
-    <ParameterName>@Name</ParameterName>
-    <RestrictionDefault>Name</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Tables</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>TABLE_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Tables</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>TABLE_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Tables</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Name</ParameterName>
-    <RestrictionDefault>TABLE_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Tables</CollectionName>
-    <RestrictionName>TableType</RestrictionName>
-    <ParameterName>@TableType</ParameterName>
-    <RestrictionDefault>TABLE_TYPE</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Columns</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>TABLE_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Columns</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>TABLE_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Columns</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>TABLE_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Columns</CollectionName>
-    <RestrictionName>Column</RestrictionName>
-    <ParameterName>@Column</ParameterName>
-    <RestrictionDefault>COLUMN_NAME</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>AllColumns</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>TABLE_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>AllColumns</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>TABLE_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>AllColumns</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>TABLE_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>AllColumns</CollectionName>
-    <RestrictionName>Column</RestrictionName>
-    <ParameterName>@Column</ParameterName>
-    <RestrictionDefault>COLUMN_NAME</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ColumnSetColumns</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>TABLE_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ColumnSetColumns</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>TABLE_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ColumnSetColumns</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>TABLE_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>StructuredTypeMembers</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>TYPE_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>StructuredTypeMembers</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>TYPE_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>StructuredTypeMembers</CollectionName>
-    <RestrictionName>Type</RestrictionName>
-    <ParameterName>@Type</ParameterName>
-    <RestrictionDefault>TYPE_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>StructuredTypeMembers</CollectionName>
-    <RestrictionName>Member</RestrictionName>
-    <ParameterName>@Member</ParameterName>
-    <RestrictionDefault>MEMBER_NAME</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Views</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>TABLE_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Views</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>TABLE_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Views</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>TABLE_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ViewColumns</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>VIEW_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ViewColumns</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>VIEW_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ViewColumns</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>VIEW_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ViewColumns</CollectionName>
-    <RestrictionName>Column</RestrictionName>
-    <ParameterName>@Column</ParameterName>
-    <RestrictionDefault>COLUMN_NAME</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-    <MinimumVersion>08.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ProcedureParameters</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>SPECIFIC_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ProcedureParameters</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>SPECIFIC_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ProcedureParameters</CollectionName>
-    <RestrictionName>Name</RestrictionName>
-    <ParameterName>@Name</ParameterName>
-    <RestrictionDefault>SPECIFIC_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ProcedureParameters</CollectionName>
-    <RestrictionName>Parameter</RestrictionName>
-    <ParameterName>@Parameter</ParameterName>
-    <RestrictionDefault>PARAMETER_NAME</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Procedures</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>SPECIFIC_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Procedures</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>SPECIFIC_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-</Restrictions>
-  <Restrictions>
-    <CollectionName>Procedures</CollectionName>
-    <RestrictionName>Name</RestrictionName>
-    <ParameterName>@Name</ParameterName>
-    <RestrictionDefault>SPECIFIC_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Procedures</CollectionName>
-    <RestrictionName>Type</RestrictionName>
-    <ParameterName>@Type</ParameterName>
-    <RestrictionDefault>ROUTINE_TYPE</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-    <MinimumVersion>08.00.0000</MinimumVersion>
-</Restrictions>
-  <Restrictions>
-    <CollectionName>IndexColumns</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>db_name()</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>IndexColumns</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>user_name()</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>IndexColumns</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>o.name</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>IndexColumns</CollectionName>
-    <RestrictionName>ConstraintName</RestrictionName>
-    <ParameterName>@ConstraintName</ParameterName>
-    <RestrictionDefault>x.name</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>IndexColumns</CollectionName>
-    <RestrictionName>Column</RestrictionName>
-    <ParameterName>@Column</ParameterName>
-    <RestrictionDefault>c.name</RestrictionDefault>
-    <RestrictionNumber>5</RestrictionNumber>
-  </Restrictions>
- <Restrictions>
-    <CollectionName>Indexes</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>db_name()</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Indexes</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>user_name()</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Indexes</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>o.name</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>Indexes</CollectionName>
-    <RestrictionName>Name</RestrictionName>
-    <ParameterName>@Name</ParameterName>
-    <RestrictionDefault>x.name</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>UserDefinedTypes</CollectionName>
-    <RestrictionName>assembly_name</RestrictionName>
-    <ParameterName>@AssemblyName</ParameterName>
-    <RestrictionDefault>assemblies.name</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-    <MinimumVersion>09.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>UserDefinedTypes</CollectionName>
-    <RestrictionName>udt_name</RestrictionName>
-    <ParameterName>@UDTName</ParameterName>
-    <RestrictionDefault>types.assembly_class</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-    <MinimumVersion>09.00.000.0</MinimumVersion>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ForeignKeys</CollectionName>
-    <RestrictionName>Catalog</RestrictionName>
-    <ParameterName>@Catalog</ParameterName>
-    <RestrictionDefault>CONSTRAINT_CATALOG</RestrictionDefault>
-    <RestrictionNumber>1</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ForeignKeys</CollectionName>
-    <RestrictionName>Owner</RestrictionName>
-    <ParameterName>@Owner</ParameterName>
-    <RestrictionDefault>CONSTRAINT_SCHEMA</RestrictionDefault>
-    <RestrictionNumber>2</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ForeignKeys</CollectionName>
-    <RestrictionName>Table</RestrictionName>
-    <ParameterName>@Table</ParameterName>
-    <RestrictionDefault>TABLE_NAME</RestrictionDefault>
-    <RestrictionNumber>3</RestrictionNumber>
-  </Restrictions>
-  <Restrictions>
-    <CollectionName>ForeignKeys</CollectionName>
-    <RestrictionName>Name</RestrictionName>
-    <ParameterName>@Name</ParameterName>
-    <RestrictionDefault>CONSTRAINT_NAME</RestrictionDefault>
-    <RestrictionNumber>4</RestrictionNumber>
-  </Restrictions>
-  <DataSourceInformation>
-    <CompositeIdentifierSeparatorPattern>\.</CompositeIdentifierSeparatorPattern>
-    <DataSourceProductName>Microsoft SQL Server</DataSourceProductName>
-    <GroupByBehavior>2</GroupByBehavior>
-    <IdentifierPattern>(^\[\p{Lo}\p{Lu}\p{Ll}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Nd}@$#_]*$)|(^\[[^\]\0]|\]\]+\]$)|(^\"[^\"\0]|\"\"+\"$)</IdentifierPattern>
-    <IdentifierCase>1</IdentifierCase>
-    <OrderByColumnsInSelect>false</OrderByColumnsInSelect>
-    <ParameterMarkerFormat>{0}</ParameterMarkerFormat>
-    <ParameterMarkerPattern>@[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)</ParameterMarkerPattern>
-    <ParameterNameMaxLength>128</ParameterNameMaxLength>
-    <ParameterNamePattern>^[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)</ParameterNamePattern>
-    <QuotedIdentifierPattern>(([^\[]|\]\])*)</QuotedIdentifierPattern>
-    <QuotedIdentifierCase>1</QuotedIdentifierCase>
-    <StatementSeparatorPattern>;</StatementSeparatorPattern>
-    <StringLiteralPattern>'(([^']|'')*)'</StringLiteralPattern>
-    <SupportedJoinOperators>15</SupportedJoinOperators>
-  </DataSourceInformation>
-<DataTypes>
-<TypeName>smallint</TypeName>
-<ProviderDbType>16</ProviderDbType>
-<ColumnSize>5</ColumnSize>
-<CreateFormat>smallint</CreateFormat>
-<DataType>System.Int16</DataType>
-<IsAutoIncrementable>true</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>true</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>int</TypeName>
-<ProviderDbType>8</ProviderDbType>
-<ColumnSize>10</ColumnSize>
-<CreateFormat>int</CreateFormat>
-<DataType>System.Int32</DataType>
-<IsAutoIncrementable>true</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>true</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>real</TypeName>
-<ProviderDbType>13</ProviderDbType>
-<ColumnSize>7</ColumnSize>
-<CreateFormat>real</CreateFormat>
-<DataType>System.Single</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>float</TypeName>
-<ProviderDbType>6</ProviderDbType>
-<ColumnSize>53</ColumnSize>
-<CreateFormat>float({0})</CreateFormat>
-<CreateParameters>number of bits used to store the mantissa</CreateParameters>
-<DataType>System.Double</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>money</TypeName>
-<ProviderDbType>9</ProviderDbType>
-<ColumnSize>19</ColumnSize>
-<CreateFormat>money</CreateFormat>
-<DataType>System.Decimal</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>false</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>true</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>smallmoney</TypeName>
-<ProviderDbType>17</ProviderDbType>
-<ColumnSize>10</ColumnSize>
-<CreateFormat>smallmoney</CreateFormat>
-<DataType>System.Decimal</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>false</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>true</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>bit</TypeName>
-<ProviderDbType>2</ProviderDbType>
-<ColumnSize>1</ColumnSize>
-<CreateFormat>bit</CreateFormat>
-<DataType>System.Boolean</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>false</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-</DataTypes>
-<DataTypes>
-<TypeName>tinyint</TypeName>
-<ProviderDbType>20</ProviderDbType>
-<ColumnSize>3</ColumnSize>
-<CreateFormat>tinyint</CreateFormat>
-<DataType>System.SByte</DataType>
-<IsAutoIncrementable>true</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>true</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>true</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>bigint</TypeName>
-<ProviderDbType>0</ProviderDbType>
-<ColumnSize>19</ColumnSize>
-<CreateFormat>bigint</CreateFormat>
-<DataType>System.Int64</DataType>
-<IsAutoIncrementable>true</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>true</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-</DataTypes>
-<DataTypes>
-<TypeName>varbinary</TypeName>
-<ProviderDbType>21</ProviderDbType>
-<ColumnSize>8000</ColumnSize>
-<CreateFormat>varbinary({0})</CreateFormat>
-<CreateParameters>max length</CreateParameters>
-<DataType>System.Byte[]</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<MaximumVersion>08.99.999.9</MaximumVersion>
-<LiteralPrefix>0x</LiteralPrefix>
-</DataTypes>
-<DataTypes>
-<TypeName>timestamp</TypeName>
-<ProviderDbType>19</ProviderDbType>
-<ColumnSize>8</ColumnSize>
-<CreateFormat>timestamp</CreateFormat>
-<DataType>System.Byte[]</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>false</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>true</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>false</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<LiteralPrefix>0x</LiteralPrefix>
-</DataTypes>
-<DataTypes>
-<TypeName>binary</TypeName>
-<ProviderDbType>1</ProviderDbType>
-<ColumnSize>8000</ColumnSize>
-<CreateFormat>binary({0})</CreateFormat>
-<CreateParameters>length</CreateParameters>
-<DataType>System.Byte[]</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<LiteralPrefix>0x</LiteralPrefix>
-</DataTypes>
-<DataTypes>
-<TypeName>image</TypeName>
-<ProviderDbType>7</ProviderDbType>
-<ColumnSize>2147483647</ColumnSize>
-<CreateFormat>image</CreateFormat>
-<DataType>System.Byte[]</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>true</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>false</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<LiteralPrefix>0x</LiteralPrefix>
-</DataTypes>
-<DataTypes>
-<TypeName>char</TypeName>
-<ProviderDbType>3</ProviderDbType>
-<ColumnSize>8000</ColumnSize>
-<CreateFormat>char</CreateFormat>
-<CreateParameters>length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MaximumVersion>08.99.999.9</MaximumVersion>
-<LiteralPrefix>'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>text</TypeName>
-<ProviderDbType>18</ProviderDbType>
-<ColumnSize>2147483647</ColumnSize>
-<CreateFormat>text</CreateFormat>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>true</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>false</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<LiteralPrefix>'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>varchar</TypeName>
-<ProviderDbType>22</ProviderDbType>
-<ColumnSize>8000</ColumnSize>
-<CreateFormat>varchar({0})</CreateFormat>
-<CreateParameters>max length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MaximumVersion>08.99.999.9</MaximumVersion>
-<LiteralPrefix>'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>nchar</TypeName>
-<ProviderDbType>10</ProviderDbType>
-<ColumnSize>4000</ColumnSize>
-<CreateFormat>nchar({0})</CreateFormat>
-<CreateParameters>length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MaximumVersion>08.99.999.9</MaximumVersion>
-<LiteralPrefix>N'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>ntext</TypeName>
-<ProviderDbType>11</ProviderDbType>
-<ColumnSize>1073741823</ColumnSize>
-<CreateFormat>ntext</CreateFormat>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>true</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>false</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<LiteralPrefix>N'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>nvarchar</TypeName>
-<ProviderDbType>12</ProviderDbType>
-<ColumnSize>4000</ColumnSize>
-<CreateFormat>nvarchar({0})</CreateFormat>
-<CreateParameters>max length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MaximumVersion>08.99.999.9</MaximumVersion>
-<LiteralPrefix>N'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>decimal</TypeName>
-<ProviderDbType>5</ProviderDbType>
-<ColumnSize>38</ColumnSize>
-<CreateFormat>decimal({0}, {1})</CreateFormat>
-<CreateParameters>precision,scale</CreateParameters>
-<DataType>System.Decimal</DataType>
-<IsAutoIncrementable>true</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-<MaximumScale>38</MaximumScale>
-<MinimumScale>0</MinimumScale>
-</DataTypes>
-<DataTypes>
-<TypeName>numeric</TypeName>
-<ProviderDbType>5</ProviderDbType>
-<ColumnSize>38</ColumnSize>
-<CreateFormat>numeric({0}, {1})</CreateFormat>
-<CreateParameters>precision,scale</CreateParameters>
-<DataType>System.Decimal</DataType>
-<IsAutoIncrementable>true</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsUnsigned>false</IsUnsigned>
-<MaximumScale>38</MaximumScale>
-<MinimumScale>0</MinimumScale>
-</DataTypes>
-<DataTypes>
-<TypeName>datetime</TypeName>
-<ProviderDbType>4</ProviderDbType>
-<ColumnSize>23</ColumnSize>
-<CreateFormat>datetime</CreateFormat>
-<DataType>System.DateTime</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<LiteralPrefix>{ts '</LiteralPrefix>
-<LiteralSuffix>'}</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>smalldatetime</TypeName>
-<ProviderDbType>15</ProviderDbType>
-<ColumnSize>16</ColumnSize>
-<CreateFormat>smalldatetime</CreateFormat>
-<DataType>System.DateTime</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<LiteralPrefix>{ts '</LiteralPrefix>
-<LiteralSuffix>'}</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>sql_variant</TypeName>
-<ProviderDbType>23</ProviderDbType>
-<CreateFormat>sql_variant</CreateFormat>
-<DataType>System.Object</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<IsLiteralSupported>false</IsLiteralSupported>
-</DataTypes>
-<DataTypes>
-<TypeName>xml</TypeName>
-<ProviderDbType>25</ProviderDbType>
-<ColumnSize>2147483647</ColumnSize>
-<CreateFormat>xml</CreateFormat>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>false</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>true</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>false</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<MinimumVersion>09.00.000.0</MinimumVersion>
-<IsLiteralSupported>false</IsLiteralSupported>
-</DataTypes>
-<DataTypes>
-<TypeName>varchar</TypeName>
-<ProviderDbType>22</ProviderDbType>
-<ColumnSize>2147483647</ColumnSize>
-<CreateFormat>varchar({0})</CreateFormat>
-<CreateParameters>max length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MinimumVersion>09.00.000.0</MinimumVersion>
-<LiteralPrefix>'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>char</TypeName>
-<ProviderDbType>3</ProviderDbType>
-<ColumnSize>2147483647</ColumnSize>
-<CreateFormat>char({0})</CreateFormat>
-<CreateParameters>length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MinimumVersion>09.00.000.0</MinimumVersion>
-<LiteralPrefix>'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>nchar</TypeName>
-<ProviderDbType>10</ProviderDbType>
-<ColumnSize>1073741823</ColumnSize>
-<CreateFormat>nchar({0})</CreateFormat>
-<CreateParameters>length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MinimumVersion>09.00.000.0</MinimumVersion>
-<LiteralPrefix>N'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>nvarchar</TypeName>
-<ProviderDbType>12</ProviderDbType>
-<ColumnSize>1073741823</ColumnSize>
-<CreateFormat>nvarchar({0})</CreateFormat>
-<CreateParameters>max length</CreateParameters>
-<DataType>System.String</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MinimumVersion>09.00.000.0</MinimumVersion>
-<LiteralPrefix>N'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>varbinary</TypeName>
-<ProviderDbType>21</ProviderDbType>
-<ColumnSize>1073741823</ColumnSize>
-<CreateFormat>varbinary({0})</CreateFormat>
-<CreateParameters>max length</CreateParameters>
-<DataType>System.Byte[]</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<MinimumVersion>09.00.000.0</MinimumVersion>
-<LiteralPrefix>0x</LiteralPrefix>
-</DataTypes>
-<DataTypes>
-<TypeName>uniqueidentifier</TypeName>
-<ProviderDbType>14</ProviderDbType>
-<ColumnSize>16</ColumnSize>
-<CreateFormat>uniqueidentifier</CreateFormat>
-<DataType>System.Guid</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>false</IsSearchableWithLike>
-<LiteralPrefix>'</LiteralPrefix>
-<LiteralSuffix>'</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>date</TypeName>
-<ProviderDbType>31</ProviderDbType>
-<ColumnSize>3</ColumnSize>
-<CreateFormat>date</CreateFormat>
-<DataType>System.DateTime</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>false</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>true</IsFixedLength>
-<IsFixedPrecisionScale>true</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MinimumVersion>10.00.000.0</MinimumVersion>
-<LiteralPrefix>{ts '</LiteralPrefix>
-<LiteralSuffix>'}</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>time</TypeName>
-<ProviderDbType>32</ProviderDbType>
-<ColumnSize>5</ColumnSize>
-<CreateFormat>time({0})</CreateFormat>
-<CreateParameters>scale</CreateParameters>
-<DataType>System.TimeSpan</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>false</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MaximumScale>7</MaximumScale>
-<MinimumScale>0</MinimumScale>
-<MinimumVersion>10.00.000.0</MinimumVersion>
-<LiteralPrefix>{ts '</LiteralPrefix>
-<LiteralSuffix>'}</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>datetime2</TypeName>
-<ProviderDbType>33</ProviderDbType>
-<ColumnSize>8</ColumnSize>
-<CreateFormat>datetime2({0})</CreateFormat>
-<CreateParameters>scale</CreateParameters>
-<DataType>System.DateTime</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MaximumScale>7</MaximumScale>
-<MinimumScale>0</MinimumScale>
-<MinimumVersion>10.00.000.0</MinimumVersion>
-<LiteralPrefix>{ts '</LiteralPrefix>
-<LiteralSuffix>'}</LiteralSuffix>
-</DataTypes>
-<DataTypes>
-<TypeName>datetimeoffset</TypeName>
-<ProviderDbType>34</ProviderDbType>
-<ColumnSize>10</ColumnSize>
-<CreateFormat>datetimeoffset({0})</CreateFormat>
-<CreateParameters>scale</CreateParameters>
-<DataType>System.DateTimeOffset</DataType>
-<IsAutoIncrementable>false</IsAutoIncrementable>
-<IsBestMatch>true</IsBestMatch>
-<IsCaseSensitive>false</IsCaseSensitive>
-<IsConcurrencyType>false</IsConcurrencyType>
-<IsFixedLength>false</IsFixedLength>
-<IsFixedPrecisionScale>false</IsFixedPrecisionScale>
-<IsLong>false</IsLong>
-<IsNullable>true</IsNullable>
-<IsSearchable>true</IsSearchable>
-<IsSearchableWithLike>true</IsSearchableWithLike>
-<MaximumScale>7</MaximumScale>
-<MinimumScale>0</MinimumScale>
-<MinimumVersion>10.00.000.0</MinimumVersion>
-<LiteralPrefix>{ts '</LiteralPrefix>
-<LiteralSuffix>'}</LiteralSuffix>
-</DataTypes>
- <ReservedWords>
-  <ReservedWord>ADD</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXCEPT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PERCENT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ALL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXEC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PLAN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ALTER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXECUTE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PRECISION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>AND</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXISTS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PRIMARY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ANY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXIT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PRINT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>AS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FETCH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PROC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ASC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FILE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PROCEDURE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>AUTHORIZATION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FILLFACTOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PUBLIC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BACKUP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RAISERROR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BEGIN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FOREIGN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>READ</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BETWEEN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FREETEXT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>READTEXT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BREAK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FREETEXTTABLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RECONFIGURE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BROWSE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FROM</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>REFERENCES</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BULK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FULL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>REPLICATION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FUNCTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RESTORE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CASCADE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GOTO</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RESTRICT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CASE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GRANT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RETURN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CHECK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GROUP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>REVOKE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CHECKPOINT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>HAVING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RIGHT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CLOSE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>HOLDLOCK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROLLBACK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CLUSTERED</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IDENTITY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROWCOUNT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COALESCE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IDENTITY_INSERT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROWGUIDCOL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COLLATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IDENTITYCOL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RULE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COLUMN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IF</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SAVE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COMMIT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SCHEMA</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COMPUTE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INDEX</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SELECT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONSTRAINT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INNER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SESSION_USER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONTAINS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INSERT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SET</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONTAINSTABLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INTERSECT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SETUSER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONTINUE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INTO</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SHUTDOWN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONVERT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SOME</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CREATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>JOIN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>STATISTICS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CROSS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>KEY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SYSTEM_USER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURRENT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>KILL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TABLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURRENT_DATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LEFT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TEXTSIZE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURRENT_TIME</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LIKE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>THEN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURRENT_TIMESTAMP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LINENO</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TO</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURRENT_USER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LOAD</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TOP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURSOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NATIONAL </ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRAN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DATABASE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NOCHECK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRANSACTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DBCC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NONCLUSTERED</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRIGGER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DEALLOCATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NOT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRUNCATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DECLARE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NULL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TSEQUAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DEFAULT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NULLIF</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UNION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DELETE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OF</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UNIQUE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DENY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OFF</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UPDATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DESC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OFFSETS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UPDATETEXT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DISK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ON</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>USE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DISTINCT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OPEN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>USER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DISTRIBUTED</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OPENDATASOURCE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>VALUES</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DOUBLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OPENQUERY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>VARYING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DROP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OPENROWSET</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>VIEW</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DUMMY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OPENXML</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WAITFOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DUMP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OPTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WHEN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ELSE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WHERE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>END</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ORDER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WHILE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ERRLVL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OUTER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WITH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ESCAPE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OVER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WRITETEXT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ABSOLUTE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FOUND</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PRESERVE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ACTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FREE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PRIOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ADMIN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GENERAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PRIVILEGES</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>AFTER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GET</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>READS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>AGGREGATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GLOBAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>REAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ALIAS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GO</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RECURSIVE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ALLOCATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>GROUPING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>REF</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ARE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>HOST</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>REFERENCING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ARRAY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>HOUR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RELATIVE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ASSERTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IGNORE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RESULT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>AT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>IMMEDIATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>RETURNS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BEFORE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INDICATOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BINARY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INITIALIZE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROLLUP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BIT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INITIALLY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROUTINE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BLOB</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INOUT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROW</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BOOLEAN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INPUT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ROWS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BOTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SAVEPOINT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BREADTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INTEGER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SCROLL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CALL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INTERVAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SCOPE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CASCADED</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ISOLATION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SEARCH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CAST</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ITERATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SECOND</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CATALOG</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LANGUAGE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SECTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CHAR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LARGE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SEQUENCE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CHARACTER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LAST</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SESSION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CLASS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LATERAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SETS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CLOB</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LEADING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SIZE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COLLATION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LESS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SMALLINT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COMPLETION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LEVEL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SPACE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONNECT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LIMIT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SPECIFIC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONNECTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LOCAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SPECIFICTYPE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONSTRAINTS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LOCALTIME</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SQL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CONSTRUCTOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LOCALTIMESTAMP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SQLEXCEPTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CORRESPONDING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LOCATOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SQLSTATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CUBE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MAP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SQLWARNING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURRENT_PATH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MATCH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>START</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CURRENT_ROLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MINUTE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>STATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CYCLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MODIFIES</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>STATEMENT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DATA</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MODIFY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>STATIC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MODULE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>STRUCTURE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DAY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MONTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TEMPORARY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DEC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NAMES</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TERMINATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DECIMAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NATURAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>THAN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DEFERRABLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NCHAR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TIME</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DEFERRED</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NCLOB</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TIMESTAMP</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DEPTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NEW</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TIMEZONE_HOUR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DEREF</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NEXT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TIMEZONE_MINUTE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DESCRIBE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NO</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRAILING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DESCRIPTOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NONE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRANSLATION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DESTROY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>NUMERIC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TREAT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DESTRUCTOR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OBJECT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRUE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DETERMINISTIC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OLD</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UNDER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DICTIONARY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ONLY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UNKNOWN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DIAGNOSTICS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OPERATION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UNNEST</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DISCONNECT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ORDINALITY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>USAGE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DOMAIN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OUT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>USING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>DYNAMIC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OUTPUT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>VALUE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EACH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PAD</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>VARCHAR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>END-EXEC</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PARAMETER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>VARIABLE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EQUALS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PARAMETERS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WHENEVER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EVERY</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PARTIAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WITHOUT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXCEPTION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PATH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WORK</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXTERNAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>POSTFIX</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>WRITE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FALSE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PREFIX</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>YEAR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FIRST</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PREORDER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ZONE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FLOAT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PREPARE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>ADA</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>AVG</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>BIT_LENGTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CHAR_LENGTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>CHARACTER_LENGTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>COUNT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>EXTRACT</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>FORTRAN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INCLUDE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>INSENSITIVE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>LOWER</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MAX</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>MIN</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OCTET_LENGTH</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>OVERLAPS</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>PASCAL</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>POSITION</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SQLCA</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SQLCODE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SQLERROR</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SUBSTRING</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>SUM</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRANSLATE</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>TRIM</ReservedWord>
-  </ReservedWords>
-  <ReservedWords>
-  <ReservedWord>UPPER</ReservedWord>
-  </ReservedWords>
-</NewDataSet>
diff --git a/src/libraries/System.Data.SqlClient/src/System.Data.SqlClient.TypeForwards.cs b/src/libraries/System.Data.SqlClient/src/System.Data.SqlClient.TypeForwards.cs
deleted file mode 100644 (file)
index 1a726d0..0000000
+++ /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.
-
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlDbType))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.StatementCompletedEventArgs))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.StatementCompletedEventHandler))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.INullable))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlBinary))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlBoolean))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlByte))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlBytes))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlChars))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlCompareOptions))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlDateTime))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlDecimal))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlDouble))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlGuid))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlInt16))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlInt32))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlInt64))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlMoney))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlNullValueException))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlSingle))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlString))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlTruncateException))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlTypeException))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Data.SqlTypes.SqlXml))]
diff --git a/src/libraries/System.Data.SqlClient/src/System.Data.SqlClient.csproj b/src/libraries/System.Data.SqlClient/src/System.Data.SqlClient.csproj
deleted file mode 100644 (file)
index 9af8152..0000000
+++ /dev/null
@@ -1,565 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <AssemblyName>System.Data.SqlClient</AssemblyName>
-    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
-    <NoWarn>$(NoWarn);CS1573;nullable</NoWarn>
-    <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(OSGroup)' == 'AnyOS'">SR.PlatformNotSupported_DataSqlClient</GeneratePlatformNotSupportedAssemblyMessage>
-    <AssemblyVersion Condition="'$(TargetFramework)' == 'netstandard2.0'">4.6.0.0</AssemblyVersion>
-    <DefineConstants Condition="'$(TargetsNetCoreApp)' != 'true'">$(DefineConstants);NETSTANDARD2_0</DefineConstants>
-    <DefineConstants Condition="'$(TargetFramework)' == '$(NetCoreAppCurrent)'">$(DefineConstants);FEATURE_TCPKEEPALIVE</DefineConstants>
-    <Nullable>annotations</Nullable>
-    <DefineConstants Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">$(DefineConstants);INTERNAL_NULLABLE_ATTRIBUTES</DefineConstants>
-    <Configurations>$(NetCoreAppCurrent)-Debug;$(NetCoreAppCurrent)-Release;$(NetCoreAppCurrent)-Unix-Debug;$(NetCoreAppCurrent)-Unix-Release;$(NetCoreAppCurrent)-Windows_NT-Debug;$(NetCoreAppCurrent)-Windows_NT-Release;netcoreapp2.1-Debug;netcoreapp2.1-Release;netcoreapp2.1-Unix-Debug;netcoreapp2.1-Unix-Release;netcoreapp2.1-Windows_NT-Debug;netcoreapp2.1-Windows_NT-Release;netstandard2.0-Unix-Debug;netstandard2.0-Unix-Release;netstandard2.0-Windows_NT-Debug;netstandard2.0-Windows_NT-Release;</Configurations>
-  </PropertyGroup>
-  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0' or '$(TargetsNetCoreApp)' == 'true'">
-    <Compile Include="System.Data.SqlClient.TypeForwards.cs" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(OSGroup)' != 'AnyOS' and '$(TargetsNetCoreApp)' == 'true'">
-    <Compile Include="System\Data\SqlClient\PoolBlockingPeriod.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SqlFacetAttribute.cs" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(OSGroup)' != 'AnyOS'">
-    <Compile Include="Microsoft\SqlServer\Server\ITypedGetters.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\ITypedGettersV3.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\ITypedSetters.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\ITypedSettersV3.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\ExtendedClrTypeCode.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\MemoryRecordBuffer.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\MetadataUtilsSmi.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiEventSink.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiEventSink_Default.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiGettersStream.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiMetaData.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiMetaDataProperty.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiRecordBuffer.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiSettersStream.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiTypedGetterSetter.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiXetterAccessMap.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SmiXetterTypeCode.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SqlDataRecord.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\SqlRecordBuffer.cs" />
-    <Compile Include="Microsoft\SqlServer\Server\ValueUtilsSmi.cs" />
-    <Compile Include="System\Data\DataException.cs" />
-    <Compile Include="System\Data\OperationAbortedException.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDbColumn.cs" />
-    <Compile Include="System\Data\Common\ActivityCorrelator.cs" />
-    <Compile Include="$(CommonPath)System\Data\Common\AdapterUtil.cs">
-      <Link>System\Data\Common\AdapterUtil.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\Common\AdapterUtil.Drivers.cs">
-      <Link>System\Data\Common\AdapterUtil.Drivers.cs</Link>
-    </Compile>
-    <Compile Include="System\Data\Common\AdapterUtil.SqlClient.cs" />
-    <Compile Include="System\Data\Common\SR.cs" />
-    <Compile Include="System\Data\Common\DbConnectionOptions.cs" />
-    <Compile Include="$(CommonPath)System\Data\Common\DbConnectionOptions.Common.cs">
-      <Link>System\Data\Common\DbConnectionOptions.Common.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\Common\DbConnectionPoolKey.cs">
-      <Link>System\Data\Common\DbConnectionPoolKey.cs</Link>
-    </Compile>
-    <Compile Include="System\Data\Common\DbConnectionStringCommon.cs" />
-    <Compile Include="$(CommonPath)System\Data\Common\FieldNameLookup.cs">
-      <Link>System\Data\Common\FieldNameLookup.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\Common\BasicFieldNameLookup.cs">
-      <Link>System\Data\Common\BasicFieldNameLookup.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\Common\MultipartIdentifier.cs">
-      <Link>System\Data\Common\MultipartIdentifier.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\Common\NameValuePair.cs">
-      <Link>System\Data\Common\NameValuePair.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\ProviderBase\DbConnectionInternal.cs">
-      <Link>Common\System\Data\ProviderBase\DbConnectionInternal.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\ProviderBase\DbConnectionFactory.cs">
-      <Link>Common\System\Data\ProviderBase\DbConnectionFactory.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\ProviderBase\DbConnectionPoolGroup.cs">
-      <Link>Common\System\Data\ProviderBase\DbConnectionPoolGroup.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\ProviderBase\TimeoutTimer.cs">
-      <Link>Common\System\Data\ProviderBase\TimeoutTimer.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\ProviderBase\DbReferenceCollection.cs">
-      <Link>Common\System\Data\ProviderBase\DbReferenceCollection.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\ProviderBase\DbMetaDataFactory.cs">
-      <Link>Common\System\Data\ProviderBase\DbMetaDataFactory.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Data\ProviderBase\DbConnectionClosed.cs">
-      <Link>Common\System\Data\ProviderBase\DbConnectionClosed.cs</Link>
-    </Compile>
-    <Compile Include="System\Data\ProviderBase\DbConnectionClosed.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionFactory.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionInternal.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionPool.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionPoolGroupProviderInfo.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionPoolIdentity.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionPoolOptions.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionPoolProviderInfo.cs" />
-    <Compile Include="System\Data\Sql\IBinarySerialize.cs" />
-    <Compile Include="System\Data\Sql\InvalidUdtException.cs" />
-    <Compile Include="System\Data\Sql\SqlFunctionAttribute.cs" />
-    <Compile Include="System\Data\Sql\SqlMetaData.cs" />
-    <Compile Include="System\Data\Sql\SqlMethodAttribute.cs" />
-    <Compile Include="System\Data\Sql\SqlNorm.cs" />
-    <Compile Include="System\Data\Sql\SqlNotificationRequest.cs" />
-    <Compile Include="System\Data\Sql\SqlSer.cs" />
-    <Compile Include="System\Data\Sql\SqlUserDefinedAggregateAttribute.cs" />
-    <Compile Include="System\Data\Sql\SqlUserDefinedTypeAttribute.cs" />
-    <Compile Include="System\Data\SqlClient\ApplicationIntent.cs" />
-    <Compile Include="System\Data\SqlClient\LocalDBAPI.cs" />
-    <Compile Include="System\Data\SqlClient\ParameterPeekAheadValue.cs" />
-    <Compile Include="System\Data\SqlClient\RowsCopiedEventArgs.cs" />
-    <Compile Include="System\Data\SqlClient\RowsCopiedEventHandler.cs" />
-    <Compile Include="System\Data\SqlClient\SortOrder.cs" />
-    <Compile Include="System\Data\SqlClient\SqlBuffer.cs" />
-    <Compile Include="System\Data\SqlClient\SqlBulkCopy.cs" />
-    <Compile Include="System\Data\SqlClient\SqlBulkCopyColumnMapping.cs" />
-    <Compile Include="System\Data\SqlClient\SqlBulkCopyColumnMappingCollection.cs" />
-    <Compile Include="System\Data\SqlClient\SqlBulkCopyOptions.cs" />
-    <Compile Include="System\Data\SqlClient\SqlCachedBuffer.cs" />
-    <Compile Include="System\Data\SqlClient\SqlClientDiagnosticListenerExtensions.cs" />
-    <Compile Include="System\Data\SqlClient\SqlClientFactory.cs" />
-    <Compile Include="System\Data\SqlClient\SqlClientMetaDataCollectionNames.cs" />
-    <Compile Include="System\Data\SqlClient\SqlCommand.cs" />
-    <Compile Include="System\Data\SqlClient\SqlCommandBuilder.cs" />
-    <Compile Include="System\Data\SqlClient\SqlCommandSet.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnection.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionFactory.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionHelper.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionPoolGroupProviderInfo.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionPoolKey.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionPoolProviderInfo.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionString.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionStringBuilder.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionTimeoutErrorInternal.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDataAdapter.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDataReader.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDependency.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDependencyListener.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDependencyUtils.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDependencyUtils.AppDomain.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDelegatedTransaction.cs" />
-    <Compile Include="System\Data\SqlClient\SqlEnums.cs" />
-    <Compile Include="System\Data\SqlClient\SqlError.cs" />
-    <Compile Include="System\Data\SqlClient\SqlErrorCollection.cs" />
-    <Compile Include="System\Data\SqlClient\SqlException.cs" />
-    <Compile Include="System\Data\SqlClient\SqlInfoMessageEvent.cs" />
-    <Compile Include="System\Data\SqlClient\SqlInfoMessageEventHandler.cs" />
-    <Compile Include="System\Data\SqlClient\SqlInternalConnection.cs" />
-    <Compile Include="System\Data\SqlClient\SqlInternalConnectionTds.cs" />
-    <Compile Include="System\Data\SqlClient\SqlInternalTransaction.cs" />
-    <Compile Include="System\Data\SqlClient\SqlMetadataFactory.cs" />
-    <Compile Include="System\Data\SqlClient\SqlNotificationEventArgs.cs" />
-    <Compile Include="System\Data\SqlClient\SqlNotificationInfo.cs" />
-    <Compile Include="System\Data\SqlClient\SqlNotificationSource.cs" />
-    <Compile Include="System\Data\SqlClient\SqlNotificationType.cs" />
-    <Compile Include="System\Data\SqlClient\OnChangedEventHandler.cs" />
-    <Compile Include="System\Data\SqlClient\SqlParameter.cs" />
-    <Compile Include="System\Data\SqlClient\SqlParameterCollection.cs" />
-    <Compile Include="System\Data\SqlClient\SqlParameterCollectionHelper.cs" />
-    <Compile Include="System\Data\SqlClient\SqlParameterHelper.cs" />
-    <Compile Include="System\Data\SqlClient\SqlReferenceCollection.cs" />
-    <Compile Include="System\Data\SqlClient\SqlRowUpdatedEvent.cs" />
-    <Compile Include="System\Data\SqlClient\SqlRowUpdatedEventHandler.cs" />
-    <Compile Include="System\Data\SqlClient\SqlRowUpdatingEvent.cs" />
-    <Compile Include="System\Data\SqlClient\SqlRowUpdatingEventHandler.cs" />
-    <Compile Include="System\Data\SqlClient\SqlSequentialStream.cs" />
-    <Compile Include="System\Data\SqlClient\SqlSequentialTextReader.cs" />
-    <Compile Include="System\Data\SqlClient\SqlStatistics.cs" />
-    <Compile Include="System\Data\SqlClient\SqlStream.cs" />
-    <Compile Include="System\Data\SqlClient\SqlTransaction.cs" />
-    <Compile Include="System\Data\SqlClient\SqlUdtInfo.cs" />
-    <Compile Include="System\Data\SqlClient\SqlUtil.cs" />
-    <Compile Include="System\Data\SqlClient\TdsEnums.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParameterSetter.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParser.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParser.RegisterEncoding.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParserHelperClasses.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParserSessionPool.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParserStateObject.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParserStaticMethods.cs" />
-    <Compile Include="System\Data\SqlClient\TdsRecordBufferSetter.cs" />
-    <Compile Include="System\Data\SqlClient\TdsValueSetter.cs" />
-    <Compile Include="System\Data\SqlTypes\SqlTypeWorkarounds.cs" />
-    <Compile Include="$(CommonPath)System\Data\Common\SQLResource.cs">
-      <Link>System\Data\SQLTypes\SQLResource.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\NotImplemented.cs" />
-    <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs">
-      <Link>Common\System\Threading\Tasks\TaskToApm.cs</Link>
-    </Compile>
-    <Compile Include="System\Data\SqlClient\SNI\SNIError.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNIHandle.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNILoadHandle.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNIMarsConnection.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNIMarsHandle.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNIMarsQueuedPacket.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNINpHandle.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNIPacket.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNIProxy.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNITcpHandle.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SslOverTdsStream.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNICommon.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SspiClientContextStatus.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SSRP.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParserStateObjectManaged.cs" />
-    <Compile Include="Interop\SNINativeMethodWrapper.Common.cs" />
-    <Compile Include="System\Data\SqlClient\SqlCredential.cs" />
-  </ItemGroup>
-  <!-- SqlFileStream Unix Netcoreapp only -->
-  <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true' and '$(TargetsUnix)' == 'true'">
-    <Compile Include="System\Data\SqlClient\SqlFileStream.Unsupported.cs" />
-  </ItemGroup>
-  <!-- SqlFileStream Windows Netcoreapp only -->
-  <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true' and '$(TargetsWindows)' == 'true'">
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileTypes.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.FileTypes.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetFileType_SafeHandle.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.GetFileType_SafeHandle.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.SetThreadErrorMode.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.SetThreadErrorMode.cs</Link>
-    </Compile>
-    <Compile Include="$(CoreLibSharedDir)System\IO\PathInternal.Windows.cs">
-      <Link>System\IO\PathInternal.Windows.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Runtime\InteropServices\SuppressGCTransitionAttribute.internal.cs" Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
-      <Link>Common\System\Runtime\InteropServices\SuppressGCTransitionAttribute.internal.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs">
-      <Link>Common\System\Text\ValueStringBuilder.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Interop.Errors.cs">
-      <Link>Common\Interop\Windows\Interop.Errors.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Interop.UNICODE_STRING.cs">
-      <Link>Common\Interop\Windows\Interop.UNICODE_STRING.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs">
-      <Link>Common\Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.IoControlCodeAccess.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.IoControlCodeAccess.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CTL_CODE.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.CTL_CODE.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.DeviceIoControl.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.DeviceIoControl.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FileOperations.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.FileOperations.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.IoControlTransferType.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.IoControlTransferType.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.FILE_FULL_EA_INFORMATION.cs">
-      <Link>Common\Interop\Windows\NtDll\Interop.FILE_FULL_EA_INFORMATION.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.IO_STATUS_BLOCK.cs">
-      <Link>Common\Interop\Windows\NtDll\Interop.IO_STATUS_BLOCK.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.NtCreateFile.cs">
-      <Link>Common\Interop\Windows\NtDll\Interop.NtCreateFile.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.RtlNtStatusToDosError.cs">
-      <Link>Common\Interop\Windows\Interop.RtlNtStatusToDosError.cs</Link>
-    </Compile>
-    <Compile Include="System\Data\SqlClient\SqlFileStream.Windows.cs" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(OSGroup)' != 'AnyOS' and '$(TargetsNetCoreApp)' == 'true'">
-    <Compile Include="System\Data\Common\DbConnectionStringCommon.NetCoreApp.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionPool.NetCoreApp.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionString.NetCoreApp.cs" />
-    <Compile Include="System\Data\SqlClient\SqlConnectionStringBuilder.NetCoreApp.cs" />
-    <Compile Include="System\Data\SqlClient\SqlDelegatedTransaction.NetCoreApp.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParser.NetCoreApp.cs" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(OSGroup)' != 'AnyOS' and '$(TargetsNetCoreApp)' != 'true'">
-    <Compile Include="System\Data\SqlClient\SqlDelegatedTransaction.NetStandard.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParser.NetStandard.cs" />
-  </ItemGroup>
-  <!-- Manage the SNI toggle for Windows netstandard and UWP -->
-  <ItemGroup Condition="('$(TargetFramework)' == 'netstandard2.0' or '$(TargetsNetCoreApp)' == 'true') and '$(TargetsWindows)' == 'true'">
-    <!-- Manage the SNI toggle for Windows netstandard and UWP -->
-    <Compile Include="System\Data\SqlClient\SNI\SNITcpHandle.Windows.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParserStateObjectFactory.Windows.cs" />
-    <Compile Include="System\Data\SqlClient\PacketHandle.Windows.cs" />
-    <Compile Include="System\Data\SqlClient\SessionHandle.Windows.cs" />
-    <AdditionalFiles Include="$(MSBuildProjectDirectory)/*.analyzerdata.windows" />
-  </ItemGroup>
-  <ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(IsPartialFacadeAssembly)' != 'true'">
-    <Compile Include="System\Data\SqlClient\TdsParserStateObjectNative.cs" />
-    <Compile Include="Interop\SNINativeMethodWrapper.Windows.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParserSafeHandles.cs" />
-    <Compile Include="System\Data\SqlClient\LocalDBAPI.Windows.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\LocalDB.Windows.cs" />
-    <Compile Include="System\Data\ProviderBase\DbConnectionPoolIdentity.Windows.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParser.Windows.cs" />
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.LoadLibraryEx.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.LoadLibraryEx.cs</Link>
-    </Compile>
-  </ItemGroup>
-  <ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(IsPartialFacadeAssembly)' != 'true'">
-    <Compile Include="System\Data\SqlClient\LocalDBAPI.Common.cs" />
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FreeLibrary.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.FreeLibrary.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetProcAddress.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.GetProcAddress.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs">
-      <Link>Common\Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs</Link>
-    </Compile>
-  </ItemGroup>
-  <!-- Windows dependencies for Integrated Authentication for MANAGED_SNI build -->
-  <ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(IsPartialFacadeAssembly)' != 'true' ">
-    <Compile Include="$(CommonPath)System\Net\Security\SecurityBufferType.Windows.cs">
-      <Link>Common\System\Net\Security\SecurityBufferType.Windows.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\SecurityBuffer.Windows.cs">
-      <Link>Common\System\Net\Security\SecurityBuffer.Windows.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SChannel\Interop.SecPkgContext_ApplicationProtocol.cs">
-      <Link>Common\Interop\Windows\SChannel\Interop.SecPkgContext_ApplicationProtocol.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\NegotiateStreamPal.Windows.cs">
-      <Link>Common\System\Net\Security\NegotiateStreamPal.Windows.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SafeDeleteContext.cs">
-      <Link>Common\Interop\Windows\sspicliSafeDeleteContext.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SecuritySafeHandles.cs">
-      <Link>Common\Interop\Windows\SspiCli\SecuritySafeHandles.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\Interop.SSPI.cs">
-      <Link>Common\Interop\Windows\SspiCli\Interop.SSPI.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\SecurityContextTokenHandle.cs">
-      <Link>Common\System\Net\Security\SecurityContextTokenHandle.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs">
-      <Link>Common\Interop\Windows\Interop.Libraries.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SChannel\Interop.SECURITY_STATUS.cs">
-      <Link>Common\Interop\Windows\SChannel\Interop.SECURITY_STATUS.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SecPkgContext_Bindings.cs">
-      <Link>Common\Interop\Windows\SspiCli\SecPkgContext_Bindings.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\DebugCriticalHandleZeroOrMinusOneIsInvalid.cs">
-      <Link>Common\System\Net\DebugCriticalHandleZeroOrMinusOneIsInvalid.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\NetEventSource.Security.cs">
-      <Link>Common\System\Net\Security\NetEventSource.Security.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs">
-      <Link>Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\GlobalSSPI.cs">
-      <Link>Common\Interop\Windows\SspiCli\GlobalSSPI.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\ISSPIInterface.cs">
-      <Link>Common\Interop\Windows\SspiCli\ISSPIInterface.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SecurityPackageInfoClass.cs">
-      <Link>Common\Interop\Windows\SspiCli\SecurityPackageInfoClass.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SecurityPackageInfo.cs">
-      <Link>Common\Interop\Windows\SspiCli\SecurityPackageInfo.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SSPIAuthType.cs">
-      <Link>Common\Interop\Windows\SspiCli\SSPIAuthType.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SSPISecureChannelType.cs">
-      <Link>Common\Interop\Windows\SspiCli\SSPISecureChannelType.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SSPIWrapper.cs">
-      <Link>Common\Interop\Windows\SspiCli\SSPIWrapper.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\NetEventSource.Security.Windows.cs">
-      <Link>Common\System\Net\Security\NetEventSource.Security.Windows.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SecPkgContext_Sizes.cs">
-      <Link>Common\Interop\Windows\SspiCli\SecPkgContext_Sizes.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SecPkgContext_StreamSizes.cs">
-      <Link>Common\Interop\Windows\SspiCli\SecPkgContext_StreamSizes.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\SecPkgContext_NegotiationInfoW.cs">
-      <Link>Common\Interop\Windows\SspiCli\SecPkgContext_NegotiationInfoW.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SChannel\SecPkgContext_ConnectionInfo.cs">
-      <Link>Common\Interop\Windows\SChannel\SecPkgContext_ConnectionInfo.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SChannel\SecPkgContext_CipherInfo.cs">
-      <Link>Common\Interop\Windows\SChannel\SecPkgContext_CipherInfo.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\NegotiationInfoClass.cs">
-      <Link>Common\Interop\Windows\SspiCli\NegotiationInfoClass.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.certificates.cs">
-      <Link>Common\Interop\Windows\Crypt32\Interop.certificates.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.certificates_types.cs">
-      <Link>Common\Interop\Windows\Crypt32\Interop.certificates_types.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\ContextFlagsAdapterPal.Windows.cs">
-      <Link>Common\System\Net\ContextFlagsAdapterPal.Windows.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\SecurityStatusAdapterPal.Windows.cs">
-      <Link>Common\System\Net\SecurityStatusAdapterPal.Windows.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Collections\Generic\BidirectionalDictionary.cs">
-      <Link>Common\System\Collections\Generic\BidirectionalDictionary.cs</Link>
-    </Compile>
-  </ItemGroup>
-  <!-- Common (Windows and Unix) dependencies for MANAGED_SNI build -->
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(OSGroup)' != 'AnyOS'">
-    <Reference Include="System.Memory" />
-    <Compile Include="$(CommonPath)System\Net\ContextFlagsPal.cs">
-      <Link>Common\System\Net\ContextFlagsPal.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\SecurityStatusPal.cs">
-      <Link>Common\System\Net\SecurityStatusPal.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\DebugSafeHandle.cs">
-      <Link>Common\System\Net\DebugSafeHandle.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\DebugCriticalHandleMinusOneIsInvalid.cs">
-      <Link>Common\System\Net\DebugCriticalHandleMinusOneIsInvalid.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs">
-      <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Logging\DebugThreadTracking.cs">
-      <Link>Common\System\Net\Logging\DebugThreadTracking.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\InternalException.cs">
-      <Link>Common\System\Net\InternalException.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\NegotiationInfoClass.cs">
-      <Link>Common\System\Net\NegotiationInfoClass.cs</Link>
-    </Compile>
-  </ItemGroup>
-  <ItemGroup Condition=" '$(TargetsWindows)' != 'true' And '$(IsPartialFacadeAssembly)' != 'true' and '$(OSGroup)' != 'AnyOS'">
-    <Compile Include="System\Data\ProviderBase\DbConnectionPoolIdentity.Unix.cs" />
-    <Compile Include="Interop\SNINativeMethodWrapper.Unix.cs" />
-    <Compile Include="$(CommonPath)System\Net\Security\NegotiateStreamPal.Unix.cs">
-      <Link>Common\System\Net\Security\NegotiateStreamPal.Unix.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\Unix\SafeDeleteContext.cs">
-      <Link>Common\System\Net\Security\Unix\SafeDeleteContext.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\Unix\SafeFreeCredentials.cs">
-      <Link>Common\System\Net\Security\Unix\SafeFreeCredentials.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\GssSafeHandles.cs">
-      <Link>Common\Microsoft\Win32\SafeHandles\GssSafeHandles.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Unix\System.Net.Security.Native\Interop.NetSecurityNative.cs">
-      <Link>Common\Interop\Unix\System.Net.Security.Native\Interop.NetSecurityNative.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Unix\System.Net.Security.Native\Interop.NetSecurityNative.IsNtlmInstalled.cs">
-      <Link>Common\Interop\Unix\System.Net.Security.Native\Interop.NetSecurityNative.IsNtlmInstalled.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\Unix\SafeFreeNegoCredentials.cs">
-      <Link>Common\System\Net\Security\Unix\SafeFreeNegoCredentials.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\Unix\SecChannelBindings.cs">
-      <Link>Common\System\Net\Security\Unix\SecChannelBindings.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs">
-      <Link>Common\Interop\Unix\Interop.Libraries.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Unix\System.Net.Security.Native\Interop.GssBuffer.cs">
-      <Link>Common\Interop\Unix\System.Net.Security.Native\Interop.GssBuffer.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\Security\Unix\SafeDeleteNegoContext.cs">
-      <Link>Common\System\Net\Security\Unix\SafeDeleteNegoContext.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)Interop\Unix\System.Net.Security.Native\Interop.GssApiException.cs">
-      <Link>Common\Interop\Unix\System.Net.Security.Native\Interop.GssApiException.cs</Link>
-    </Compile>
-    <Compile Include="$(CommonPath)System\Net\ContextFlagsAdapterPal.Unix.cs">
-      <Link>Common\System\Net\ContextFlagsAdapterPal.Unix.cs</Link>
-    </Compile>
-    <Compile Include="System\Data\SqlClient\TdsParserStateObjectFactory.Managed.cs" />
-    <Compile Include="System\Data\SqlClient\TdsParser.Unix.cs" />
-    <Compile Include="System\Data\SqlClient\LocalDBAPI.Unix.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\LocalDB.Unix.cs" />
-    <Compile Include="System\Data\SqlClient\SNI\SNITcpHandle.Unix.cs" />
-    <Compile Include="System\Data\SqlClient\PacketHandle.Unix.cs" />
-    <Compile Include="System\Data\SqlClient\SessionHandle.Unix.cs" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(TargetsWindows)' == 'true' And '$(IsPartialFacadeAssembly)' != 'true'">
-    <Reference Include="Microsoft.Win32.Registry" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
-    <Reference Condition="'$(TargetFramework)' != 'netstandard2.0'" Include="System.Data.Common" />
-    <Reference Include="System.Globalization" />
-    <Reference Include="System.IO" />
-    <Reference Include="System.ObjectModel" />
-    <Reference Include="System.Resources.ResourceManager" />
-    <Reference Include="System.Runtime" />
-    <Reference Include="System.Threading.Tasks" />
-    <Reference Include="System.Xml.ReaderWriter" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(OSGroup)' != 'AnyOS'">
-    <Reference Include="Microsoft.Win32.Primitives" />
-    <Reference Include="System.Buffers" />
-    <Reference Include="System.Collections" />
-    <Reference Include="System.Collections.Concurrent" />
-    <Reference Include="System.ComponentModel" />
-    <Reference Include="System.ComponentModel.Primitives" />
-    <Reference Include="System.Diagnostics.Debug" />
-    <Reference Include="System.Diagnostics.DiagnosticSource" />
-    <Reference Include="System.Diagnostics.Process" />
-    <Reference Include="System.Diagnostics.Tools" />
-    <Reference Include="System.Diagnostics.Tracing" />
-    <Reference Include="System.Linq" />
-    <Reference Include="System.Runtime.Extensions" />
-    <Reference Include="System.Runtime.InteropServices" />
-    <Reference Include="System.Runtime.InteropServices.RuntimeInformation" />
-    <Reference Include="System.Security.Claims" />
-    <Reference Include="System.Security.Principal" />
-    <Reference Include="System.Security.Principal.Windows" />
-    <Reference Include="System.Text.Encoding.CodePages" />
-    <Reference Include="System.Text.Encoding.Extensions" />
-    <Reference Include="System.Text.RegularExpressions" />
-    <Reference Include="System.Threading" />
-    <Reference Include="System.Threading.Thread" />
-    <Reference Include="System.Threading.ThreadPool" />
-    <Reference Include="System.Threading.Timer" />
-    <Reference Include="System.IO.Pipes" />
-    <Reference Include="System.Security.Cryptography.X509Certificates" />
-    <Reference Include="System.Net.Sockets" />
-    <Reference Include="System.Net.Security" />
-    <Reference Include="System.Net.Primitives" />
-    <Reference Include="System.Net.NameResolution" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
-    <Reference Include="System.Transactions.Local" />
-    <Reference Include="System.Collections.NonGeneric" />
-    <Reference Include="System.ComponentModel.TypeConverter" />
-  </ItemGroup>
-  <ItemGroup>
-    <EmbeddedResource Include="Resources\System.Data.SqlClient.SqlMetaData.xml">
-      <LogicalName>System.Data.SqlClient.SqlMetaData.xml</LogicalName>
-    </EmbeddedResource>
-  </ItemGroup>
-  <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
-    <Reference Include="System.Runtime.Extensions" />
-    <Reference Include="System.Data.Common" />
-    <Reference Include="System.ComponentModel.Primitives" />
-    <Reference Include="System.Xml.ReaderWriter" />
-    <Reference Include="System.Runtime.InteropServices" />
-  </ItemGroup>
-  <Import Project=".\GenerateThisAssemblyCs.targets" Condition="'$(IsPartialFacadeAssembly)' != 'true'" />
-</Project>
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Common/ActivityCorrelator.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Common/ActivityCorrelator.cs
deleted file mode 100644 (file)
index d355b9b..0000000
+++ /dev/null
@@ -1,89 +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.Globalization;
-
-namespace System.Data.Common
-{
-    /// <summary>
-    /// This class defines the data structure for ActivityId used for correlated tracing between client (bid trace event) and server (XEvent).
-    /// It also includes all the APIs used to access the ActivityId. Note: ActivityId is thread based which is stored in TLS.
-    /// </summary>
-
-    internal static class ActivityCorrelator
-    {
-        internal class ActivityId
-        {
-            internal Guid Id { get; private set; }
-            internal uint Sequence { get; private set; }
-
-            internal ActivityId()
-            {
-                this.Id = Guid.NewGuid();
-                this.Sequence = 0; // the first event will start 1
-            }
-
-            // copy-constructor
-            internal ActivityId(ActivityId activity)
-            {
-                this.Id = activity.Id;
-                this.Sequence = activity.Sequence;
-            }
-
-            internal void Increment()
-            {
-                unchecked
-                {
-                    ++this.Sequence;
-                }
-            }
-
-            public override string ToString()
-            {
-                return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", this.Id, this.Sequence);
-            }
-        }
-
-        // Declare the ActivityId which will be stored in TLS. The Id is unique for each thread.
-        // The Sequence number will be incremented when each event happens.
-        // Correlation along threads is consistent with the current XEvent mechanism at server.
-        [ThreadStatic]
-        private static ActivityId t_tlsActivity;
-
-        /// <summary>
-        /// Get the current ActivityId
-        /// </summary>
-        internal static ActivityId Current
-        {
-            get
-            {
-                if (t_tlsActivity == null)
-                {
-                    t_tlsActivity = new ActivityId();
-                }
-
-                return new ActivityId(t_tlsActivity);
-            }
-        }
-
-        /// <summary>
-        /// Increment the sequence number and generate the new ActivityId
-        /// </summary>
-        /// <returns>ActivityId</returns>
-        internal static ActivityId Next()
-        {
-            if (t_tlsActivity == null)
-            {
-                t_tlsActivity = new ActivityId();
-            }
-
-            t_tlsActivity.Increment();
-
-            return new ActivityId(t_tlsActivity);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs
deleted file mode 100644 (file)
index 991797d..0000000
+++ /dev/null
@@ -1,923 +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.Data.SqlTypes;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Runtime.CompilerServices;
-using System.Transactions;
-
-namespace System.Data.Common
-{
-    internal static partial class ADP
-    {
-        // The class ADP defines the exceptions that are specific to the Adapters.
-        // The class contains functions that take the proper informational variables and then construct
-        // the appropriate exception with an error string obtained from the resource framework.
-        // The exception is then returned to the caller, so that the caller may then throw from its
-        // location so that the catcher of the exception will have the appropriate call stack.
-        // This class is used so that there will be compile time checking of error messages.
-        internal static Exception ExceptionWithStackTrace(Exception e)
-        {
-            try
-            {
-                throw e;
-            }
-            catch (Exception caught)
-            {
-                return caught;
-            }
-        }
-
-        //
-        // COM+ exceptions
-        //
-        internal static IndexOutOfRangeException IndexOutOfRange(int value)
-        {
-            IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
-            return e;
-        }
-        internal static IndexOutOfRangeException IndexOutOfRange()
-        {
-            IndexOutOfRangeException e = new IndexOutOfRangeException();
-            return e;
-        }
-        internal static TimeoutException TimeoutException(string error)
-        {
-            TimeoutException e = new TimeoutException(error);
-            return e;
-        }
-        internal static InvalidOperationException InvalidOperation(string error, Exception inner)
-        {
-            InvalidOperationException e = new InvalidOperationException(error, inner);
-            return e;
-        }
-        internal static OverflowException Overflow(string error)
-        {
-            return Overflow(error, null);
-        }
-        internal static OverflowException Overflow(string error, Exception inner)
-        {
-            OverflowException e = new OverflowException(error, inner);
-            return e;
-        }
-        internal static TypeLoadException TypeLoad(string error)
-        {
-            TypeLoadException e = new TypeLoadException(error);
-            TraceExceptionAsReturnValue(e);
-            return e;
-        }
-        internal static PlatformNotSupportedException DbTypeNotSupported(string dbType)
-        {
-            PlatformNotSupportedException e = new PlatformNotSupportedException(SR.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType));
-            return e;
-        }
-        internal static InvalidCastException InvalidCast()
-        {
-            InvalidCastException e = new InvalidCastException();
-            return e;
-        }
-        internal static IOException IO(string error)
-        {
-            IOException e = new IOException(error);
-            return e;
-        }
-        internal static IOException IO(string error, Exception inner)
-        {
-            IOException e = new IOException(error, inner);
-            return e;
-        }
-        internal static ObjectDisposedException ObjectDisposed(object instance)
-        {
-            ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
-            return e;
-        }
-
-        internal static Exception DataTableDoesNotExist(string collectionName)
-        {
-            return Argument(SR.GetString(SR.MDF_DataTableDoesNotExist, collectionName));
-        }
-
-        internal static InvalidOperationException MethodCalledTwice(string method)
-        {
-            InvalidOperationException e = new InvalidOperationException(SR.GetString(SR.ADP_CalledTwice, method));
-            return e;
-        }
-
-
-        // IDbCommand.CommandType
-        internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value)
-        {
-#if DEBUG
-            switch (value)
-            {
-                case CommandType.Text:
-                case CommandType.StoredProcedure:
-                case CommandType.TableDirect:
-                    Debug.Fail("valid CommandType " + value.ToString());
-                    break;
-            }
-#endif
-            return InvalidEnumerationValue(typeof(CommandType), (int)value);
-        }
-
-        // IDbConnection.BeginTransaction, OleDbTransaction.Begin
-        internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value)
-        {
-#if DEBUG
-            switch (value)
-            {
-                case IsolationLevel.Unspecified:
-                case IsolationLevel.Chaos:
-                case IsolationLevel.ReadUncommitted:
-                case IsolationLevel.ReadCommitted:
-                case IsolationLevel.RepeatableRead:
-                case IsolationLevel.Serializable:
-                case IsolationLevel.Snapshot:
-                    Debug.Fail("valid IsolationLevel " + value.ToString());
-                    break;
-            }
-#endif
-            return InvalidEnumerationValue(typeof(IsolationLevel), (int)value);
-        }
-
-
-        // IDataParameter.Direction
-        internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
-        {
-#if DEBUG
-            switch (value)
-            {
-                case ParameterDirection.Input:
-                case ParameterDirection.Output:
-                case ParameterDirection.InputOutput:
-                case ParameterDirection.ReturnValue:
-                    Debug.Fail("valid ParameterDirection " + value.ToString());
-                    break;
-            }
-#endif
-            return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
-        }
-
-        internal static Exception TooManyRestrictions(string collectionName)
-        {
-            return Argument(SR.GetString(SR.MDF_TooManyRestrictions, collectionName));
-        }
-
-
-        // IDbCommand.UpdateRowSource
-        internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value)
-        {
-#if DEBUG
-            switch (value)
-            {
-                case UpdateRowSource.None:
-                case UpdateRowSource.OutputParameters:
-                case UpdateRowSource.FirstReturnedRecord:
-                case UpdateRowSource.Both:
-                    Debug.Fail("valid UpdateRowSource " + value.ToString());
-                    break;
-            }
-#endif
-            return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value);
-        }
-
-        //
-        // DbConnectionOptions, DataAccess
-        //
-        internal static ArgumentException InvalidMinMaxPoolSizeValues()
-        {
-            return ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues));
-        }
-
-
-        //
-        // DbConnection
-        //
-        internal static InvalidOperationException NoConnectionString()
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString));
-        }
-
-        internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "")
-        {
-            return NotImplemented.ByDesignWithMessage(methodName);
-        }
-
-        internal static Exception QueryFailed(string collectionName, Exception e)
-        {
-            return InvalidOperation(SR.GetString(SR.MDF_QueryFailed, collectionName), e);
-        }
-
-
-        //
-        // : DbConnectionOptions, DataAccess, SqlClient
-        //
-        internal static Exception InvalidConnectionOptionValueLength(string key, int limit)
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit));
-        }
-        internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey)
-        {
-            return Argument(SR.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
-        }
-
-
-        //
-        // DbConnectionPool and related
-        //
-        internal static Exception PooledOpenTimeout()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout));
-        }
-
-        internal static Exception NonPooledOpenTimeout()
-        {
-            return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout));
-        }
-
-        //
-        // DbProviderException
-        //
-        internal static InvalidOperationException TransactionConnectionMismatch()
-        {
-            return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch));
-        }
-        internal static InvalidOperationException TransactionRequired(string method)
-        {
-            return Provider(SR.GetString(SR.ADP_TransactionRequired, method));
-        }
-
-
-        internal static Exception CommandTextRequired(string method)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method));
-        }
-
-        internal static Exception NoColumns()
-        {
-            return Argument(SR.GetString(SR.MDF_NoColumns));
-        }
-
-        internal static InvalidOperationException ConnectionRequired(string method)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method));
-        }
-        internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
-        }
-
-        internal static Exception OpenReaderExists()
-        {
-            return OpenReaderExists(null);
-        }
-
-        internal static Exception OpenReaderExists(Exception e)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e);
-        }
-
-
-        //
-        // DbDataReader
-        //
-        internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
-        }
-
-        internal static Exception InvalidXml()
-        {
-            return Argument(SR.GetString(SR.MDF_InvalidXml));
-        }
-
-        internal static Exception NegativeParameter(string parameterName)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_NegativeParameter, parameterName));
-        }
-
-        internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName)
-        {
-            return Argument(SR.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName));
-        }
-
-        //
-        // SqlMetaData, SqlTypes, SqlClient
-        //
-        internal static Exception InvalidMetaDataValue()
-        {
-            return ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue));
-        }
-
-        internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
-        }
-
-        internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName)
-        {
-            return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName));
-        }
-
-        internal static Exception CollectionNameIsNotUnique(string collectionName)
-        {
-            return Argument(SR.GetString(SR.MDF_CollectionNameISNotUnique, collectionName));
-        }
-
-
-        //
-        // : IDbCommand
-        //
-        internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "")
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property);
-        }
-        internal static Exception UninitializedParameterSize(int index, Type dataType)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
-        }
-
-        internal static Exception UnableToBuildCollection(string collectionName)
-        {
-            return Argument(SR.GetString(SR.MDF_UnableToBuildCollection, collectionName));
-        }
-
-        internal static Exception PrepareParameterType(DbCommand cmd)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name));
-        }
-
-        internal static Exception UndefinedCollection(string collectionName)
-        {
-            return Argument(SR.GetString(SR.MDF_UndefinedCollection, collectionName));
-        }
-
-        internal static Exception UnsupportedVersion(string collectionName)
-        {
-            return Argument(SR.GetString(SR.MDF_UnsupportedVersion, collectionName));
-        }
-
-        internal static Exception AmbigousCollectionName(string collectionName)
-        {
-            return Argument(SR.GetString(SR.MDF_AmbigousCollectionName, collectionName));
-        }
-
-        internal static Exception PrepareParameterSize(DbCommand cmd)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name));
-        }
-        internal static Exception PrepareParameterScale(DbCommand cmd, string type)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type));
-        }
-
-        internal static Exception MissingDataSourceInformationColumn()
-        {
-            return Argument(SR.GetString(SR.MDF_MissingDataSourceInformationColumn));
-        }
-
-        internal static Exception IncorrectNumberOfDataSourceInformationRows()
-        {
-            return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows));
-        }
-
-        internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
-        }
-
-        //
-        // : ConnectionUtil
-        //
-        internal static Exception ClosedConnectionError()
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError));
-        }
-        internal static Exception ConnectionAlreadyOpen(ConnectionState state)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
-        }
-        internal static Exception TransactionPresent()
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_TransactionPresent));
-        }
-        internal static Exception LocalTransactionPresent()
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_LocalTransactionPresent));
-        }
-        internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
-        }
-        internal static Exception EmptyDatabaseName()
-        {
-            return Argument(SR.GetString(SR.ADP_EmptyDatabaseName));
-        }
-
-        internal enum ConnectionError
-        {
-            BeginGetConnectionReturnsNull,
-            GetConnectionReturnsNull,
-            ConnectionOptionsMissing,
-            CouldNotSwitchToClosedPreviouslyOpenedState,
-        }
-
-        internal static Exception MissingRestrictionColumn()
-        {
-            return Argument(SR.GetString(SR.MDF_MissingRestrictionColumn));
-        }
-
-        internal static Exception InternalConnectionError(ConnectionError internalError)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError));
-        }
-
-        internal static Exception InvalidConnectRetryCountValue()
-        {
-            return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryCountValue));
-        }
-
-        internal static Exception MissingRestrictionRow()
-        {
-            return Argument(SR.GetString(SR.MDF_MissingRestrictionRow));
-        }
-
-        internal static Exception InvalidConnectRetryIntervalValue()
-        {
-            return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue));
-        }
-
-        //
-        // : DbDataReader
-        //
-        internal static InvalidOperationException AsyncOperationPending()
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_PendingAsyncOperation));
-        }
-
-        //
-        // : Stream
-        //
-        internal static IOException ErrorReadingFromStream(Exception internalException)
-        {
-            return IO(SR.GetString(SR.SqlMisc_StreamErrorMessage), internalException);
-        }
-
-        internal static ArgumentException InvalidDataType(TypeCode typecode)
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidDataType, typecode.ToString()));
-        }
-
-        internal static ArgumentException UnknownDataType(Type dataType)
-        {
-            return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName));
-        }
-
-        internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype)
-        {
-            return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
-        }
-        internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode)
-        {
-            return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
-        }
-        internal static ArgumentException InvalidOffsetValue(int value)
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
-        }
-        internal static ArgumentException InvalidSizeValue(int value)
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
-        }
-        internal static ArgumentException ParameterValueOutOfRange(decimal value)
-        {
-            return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
-        }
-        internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value)
-        {
-            return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString()));
-        }
-
-        internal static ArgumentException VersionDoesNotSupportDataType(string typeName)
-        {
-            return Argument(SR.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName));
-        }
-        internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner)
-        {
-            Debug.Assert(null != value, "null value on conversion failure");
-            Debug.Assert(null != inner, "null inner on conversion failure");
-
-            Exception e;
-            string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
-            if (inner is ArgumentException)
-            {
-                e = new ArgumentException(message, inner);
-            }
-            else if (inner is FormatException)
-            {
-                e = new FormatException(message, inner);
-            }
-            else if (inner is InvalidCastException)
-            {
-                e = new InvalidCastException(message, inner);
-            }
-            else if (inner is OverflowException)
-            {
-                e = new OverflowException(message, inner);
-            }
-            else
-            {
-                e = inner;
-            }
-            return e;
-        }
-
-        //
-        // : IDataParameterCollection
-        //
-        internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection)
-        {
-            return CollectionIndexInt32(index, collection.GetType(), collection.Count);
-        }
-        internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType)
-        {
-            return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
-        }
-        internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType)
-        {
-            return CollectionNullValue(parameter, collection.GetType(), parameterType);
-        }
-
-        internal static Exception UndefinedPopulationMechanism(string populationMechanism)
-        {
-            throw new NotImplementedException();
-        }
-
-        internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue)
-        {
-            return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
-        }
-
-        //
-        // : IDbTransaction
-        //
-        internal static Exception ParallelTransactionsNotSupported(DbConnection obj)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
-        }
-        internal static Exception TransactionZombied(DbTransaction obj)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name));
-        }
-
-        // global constant strings
-        internal const string Parameter = "Parameter";
-        internal const string ParameterName = "ParameterName";
-        internal const string ParameterSetPosition = "set_Position";
-
-        internal const int DefaultCommandTimeout = 30;
-        internal const float FailoverTimeoutStep = 0.08F;    // fraction of timeout to use for fast failover connections
-
-        internal const int CharSize = sizeof(char);
-
-        internal static Delegate FindBuilder(MulticastDelegate mcd)
-        {
-            if (null != mcd)
-            {
-                foreach (Delegate del in mcd.GetInvocationList())
-                {
-                    if (del.Target is DbCommandBuilder)
-                        return del;
-                }
-            }
-
-            return null;
-        }
-
-        internal static void TimerCurrent(out long ticks)
-        {
-            ticks = DateTime.UtcNow.ToFileTimeUtc();
-        }
-
-        internal static long TimerCurrent()
-        {
-            return DateTime.UtcNow.ToFileTimeUtc();
-        }
-
-        internal static long TimerFromSeconds(int seconds)
-        {
-            long result = checked((long)seconds * TimeSpan.TicksPerSecond);
-            return result;
-        }
-
-        internal static long TimerFromMilliseconds(long milliseconds)
-        {
-            long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
-            return result;
-        }
-
-        internal static bool TimerHasExpired(long timerExpire)
-        {
-            bool result = TimerCurrent() > timerExpire;
-            return result;
-        }
-
-        internal static long TimerRemaining(long timerExpire)
-        {
-            long timerNow = TimerCurrent();
-            long result = checked(timerExpire - timerNow);
-            return result;
-        }
-
-        internal static long TimerRemainingMilliseconds(long timerExpire)
-        {
-            long result = TimerToMilliseconds(TimerRemaining(timerExpire));
-            return result;
-        }
-
-        internal static long TimerRemainingSeconds(long timerExpire)
-        {
-            long result = TimerToSeconds(TimerRemaining(timerExpire));
-            return result;
-        }
-
-        internal static long TimerToMilliseconds(long timerValue)
-        {
-            long result = timerValue / TimeSpan.TicksPerMillisecond;
-            return result;
-        }
-
-        private static long TimerToSeconds(long timerValue)
-        {
-            long result = timerValue / TimeSpan.TicksPerSecond;
-            return result;
-        }
-
-        internal static string MachineName()
-        {
-            return Environment.MachineName;
-        }
-
-        internal static Transaction GetCurrentTransaction()
-        {
-            return Transaction.Current;
-        }
-
-        internal static bool IsDirection(DbParameter value, ParameterDirection condition)
-        {
-#if DEBUG
-            IsDirectionValid(condition);
-#endif
-            return (condition == (condition & value.Direction));
-        }
-#if DEBUG
-        private static void IsDirectionValid(ParameterDirection value)
-        {
-            switch (value)
-            { // @perfnote: Enum.IsDefined
-                case ParameterDirection.Input:
-                case ParameterDirection.Output:
-                case ParameterDirection.InputOutput:
-                case ParameterDirection.ReturnValue:
-                    break;
-                default:
-                    throw ADP.InvalidParameterDirection(value);
-            }
-        }
-#endif
-
-        internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType)
-        {
-            if ((value == null) || (value == DBNull.Value))
-            {
-                isNull = true;
-                isSqlType = false;
-            }
-            else
-            {
-                INullable nullable = (value as INullable);
-                if (nullable != null)
-                {
-                    isNull = nullable.IsNull;
-                    // Duplicated from DataStorage.cs
-                    // For back-compat, SqlXml is not in this list
-                    isSqlType = ((value is SqlBinary) ||
-                                (value is SqlBoolean) ||
-                                (value is SqlByte) ||
-                                (value is SqlBytes) ||
-                                (value is SqlChars) ||
-                                (value is SqlDateTime) ||
-                                (value is SqlDecimal) ||
-                                (value is SqlDouble) ||
-                                (value is SqlGuid) ||
-                                (value is SqlInt16) ||
-                                (value is SqlInt32) ||
-                                (value is SqlInt64) ||
-                                (value is SqlMoney) ||
-                                (value is SqlSingle) ||
-                                (value is SqlString));
-                }
-                else
-                {
-                    isNull = false;
-                    isSqlType = false;
-                }
-            }
-        }
-
-        private static Version s_systemDataVersion;
-
-        internal static Version GetAssemblyVersion()
-        {
-            // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
-            if (s_systemDataVersion == null)
-            {
-                s_systemDataVersion = new Version(ThisAssembly.InformationalVersion);
-            }
-
-            return s_systemDataVersion;
-        }
-
-
-        internal static readonly string[] AzureSqlServerEndpoints = {SR.GetString(SR.AZURESQL_GenericEndpoint),
-                                                                     SR.GetString(SR.AZURESQL_GermanEndpoint),
-                                                                     SR.GetString(SR.AZURESQL_UsGovEndpoint),
-                                                                     SR.GetString(SR.AZURESQL_ChinaEndpoint)};
-
-        // This method assumes dataSource parameter is in TCP connection string format.
-        internal static bool IsAzureSqlServerEndpoint(string dataSource)
-        {
-            // remove server port
-            int i = dataSource.LastIndexOf(',');
-            if (i >= 0)
-            {
-                dataSource = dataSource.Substring(0, i);
-            }
-
-            // check for the instance name
-            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;
-        }
-
-        internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
-        {
-#if DEBUG
-            switch (value)
-            {
-                case DataRowVersion.Default:
-                case DataRowVersion.Current:
-                case DataRowVersion.Original:
-                case DataRowVersion.Proposed:
-                    Debug.Fail($"Invalid DataRowVersion {value}");
-                    break;
-            }
-#endif
-            return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
-        }
-
-        internal static ArgumentException SingleValuedProperty(string propertyName, string value)
-        {
-            ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_SingleValuedProperty, propertyName, value));
-            TraceExceptionAsReturnValue(e);
-            return e;
-        }
-
-        internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2)
-        {
-            ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_DoubleValuedProperty, propertyName, value1, value2));
-            TraceExceptionAsReturnValue(e);
-            return e;
-        }
-
-        internal static ArgumentException InvalidPrefixSuffix()
-        {
-            ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidPrefixSuffix));
-            TraceExceptionAsReturnValue(e);
-            return e;
-        }
-
-        internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value)
-        {
-            Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString());
-
-            return InvalidEnumerationValue(typeof(CommandBehavior), (int)value);
-        }
-
-        internal static void ValidateCommandBehavior(CommandBehavior value)
-        {
-            if (((int)value < 0) || (0x3F < (int)value))
-            {
-                throw InvalidCommandBehavior(value);
-            }
-        }
-
-        internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method)
-        {
-            return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
-        }
-
-        internal static ArgumentException BadParameterName(string parameterName)
-        {
-            ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_BadParameterName, parameterName));
-            TraceExceptionAsReturnValue(e);
-            return e;
-        }
-
-        internal static Exception DeriveParametersNotSupported(IDbCommand value)
-        {
-            return DataAdapter(SR.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
-        }
-
-        internal static Exception NoStoredProcedureExists(string sproc)
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc));
-        }
-
-        //
-        // DbProviderException
-        //
-        internal static InvalidOperationException TransactionCompletedButNotDisposed()
-        {
-            return Provider(SR.GetString(SR.ADP_TransactionCompletedButNotDisposed));
-        }
-
-        internal static ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value)
-        {
-            return InvalidEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), (int)value);
-        }
-
-        internal static ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value, string method)
-        {
-            return NotSupportedEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), value.ToString(), method);
-        }
-
-        internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value)
-        {
-            ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message);
-            TraceExceptionAsReturnValue(e);
-            return e;
-        }
-
-        internal static ArgumentException InvalidArgumentLength(string argumentName, int limit)
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidArgumentLength, argumentName, limit));
-        }
-
-        internal static ArgumentException MustBeReadOnly(string argumentName)
-        {
-            return Argument(SR.GetString(SR.ADP_MustBeReadOnly, argumentName));
-        }
-
-        internal static InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential()
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential));
-        }
-
-        internal static ArgumentException InvalidMixedArgumentOfSecureAndClearCredential()
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential));
-        }
-
-        internal static InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity()
-        {
-            return InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
-        }
-
-        internal static ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity()
-        {
-            return Argument(SR.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
-        }
-        internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity));
-        }
-        internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword));
-        }
-        internal static Exception InvalidMixedUsageOfCredentialAndAccessToken()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidMixedUsageOfCredentialAndAccessToken));
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs
deleted file mode 100644 (file)
index 28ebc83..0000000
+++ /dev/null
@@ -1,110 +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.Generic;
-using System.Globalization;
-
-
-namespace System.Data.Common
-{
-    internal partial class DbConnectionOptions
-    {
-        // instances of this class are intended to be immutable, i.e readonly
-        // used by pooling classes so it is much easier to verify correctness
-        // when not worried about the class being modified during execution
-
-        public DbConnectionOptions(string connectionString, Dictionary<string, string> synonyms)
-        {
-            _parsetable = new Dictionary<string, string>();
-            _usersConnectionString = ((null != connectionString) ? connectionString : "");
-
-            // first pass on parsing, initial syntax check
-            if (0 < _usersConnectionString.Length)
-            {
-                _keyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, false);
-                _hasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
-            }
-        }
-
-        protected DbConnectionOptions(DbConnectionOptions connectionOptions)
-        { // Clone used by SqlConnectionString
-            _usersConnectionString = connectionOptions._usersConnectionString;
-            _hasPasswordKeyword = connectionOptions._hasPasswordKeyword;
-            _parsetable = connectionOptions._parsetable;
-            _keyChain = connectionOptions._keyChain;
-        }
-
-        public bool IsEmpty => _keyChain == null;
-
-        internal bool TryGetParsetableValue(string key, out string value) => _parsetable.TryGetValue(key, out value);
-
-        // same as Boolean, but with SSPI thrown in as valid yes
-        public bool ConvertValueToIntegratedSecurity()
-        {
-            string value;
-            return _parsetable.TryGetValue(KEY.Integrated_Security, out value) && value != null ?
-                ConvertValueToIntegratedSecurityInternal(value) :
-                false;
-        }
-
-        internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
-        {
-            if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
-                return true;
-            else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
-                return false;
-            else
-            {
-                string tmp = stringValue.Trim();  // Remove leading & trailing whitespace.
-                if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
-                    return true;
-                else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
-                    return false;
-                else
-                {
-                    throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
-                }
-            }
-        }
-
-        public int ConvertValueToInt32(string keyName, int defaultValue)
-        {
-            string value;
-            return _parsetable.TryGetValue(keyName, out value) && value != null ?
-                ConvertToInt32Internal(keyName, value) :
-                defaultValue;
-        }
-
-        internal static int ConvertToInt32Internal(string keyname, string stringValue)
-        {
-            try
-            {
-                return int.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
-            }
-            catch (FormatException e)
-            {
-                throw ADP.InvalidConnectionOptionValue(keyname, e);
-            }
-            catch (OverflowException e)
-            {
-                throw ADP.InvalidConnectionOptionValue(keyname, e);
-            }
-        }
-
-        public string ConvertValueToString(string keyName, string defaultValue)
-        {
-            string value;
-            return _parsetable.TryGetValue(keyName, out value) && value != null ? value : defaultValue;
-        }
-
-        public bool ContainsKey(string keyword)
-        {
-            return _parsetable.ContainsKey(keyword);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.NetCoreApp.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.NetCoreApp.cs
deleted file mode 100644 (file)
index ac026e0..0000000
+++ /dev/null
@@ -1,143 +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.Data.SqlClient;
-
-namespace System.Data.Common
-{
-    internal static partial class DbConnectionStringBuilderUtil
-    {
-        #region <<PoolBlockingPeriod Utility>>
-        internal static bool TryConvertToPoolBlockingPeriod(string value, out PoolBlockingPeriod result)
-        {
-            Debug.Assert(Enum.GetNames(typeof(PoolBlockingPeriod)).Length == 3, "PoolBlockingPeriod enum has changed, update needed");
-            Debug.Assert(null != value, "TryConvertToPoolBlockingPeriod(null,...)");
-
-            if (StringComparer.OrdinalIgnoreCase.Equals(value, nameof(PoolBlockingPeriod.Auto)))
-            {
-                result = PoolBlockingPeriod.Auto;
-                return true;
-            }
-            else if (StringComparer.OrdinalIgnoreCase.Equals(value, nameof(PoolBlockingPeriod.AlwaysBlock)))
-            {
-                result = PoolBlockingPeriod.AlwaysBlock;
-                return true;
-            }
-            else if (StringComparer.OrdinalIgnoreCase.Equals(value, nameof(PoolBlockingPeriod.NeverBlock)))
-            {
-                result = PoolBlockingPeriod.NeverBlock;
-                return true;
-            }
-            else
-            {
-                result = DbConnectionStringDefaults.PoolBlockingPeriod;
-                return false;
-            }
-        }
-
-        internal static bool IsValidPoolBlockingPeriodValue(PoolBlockingPeriod value)
-        {
-            Debug.Assert(Enum.GetNames(typeof(PoolBlockingPeriod)).Length == 3, "PoolBlockingPeriod enum has changed, update needed");
-            return (uint)value <= (uint)PoolBlockingPeriod.NeverBlock;
-        }
-
-        internal static string PoolBlockingPeriodToString(PoolBlockingPeriod value)
-        {
-            Debug.Assert(IsValidPoolBlockingPeriodValue(value));
-
-            return value switch
-            {
-                PoolBlockingPeriod.AlwaysBlock => nameof(PoolBlockingPeriod.AlwaysBlock),
-                PoolBlockingPeriod.NeverBlock => nameof(PoolBlockingPeriod.NeverBlock),
-                _ => nameof(PoolBlockingPeriod.Auto),
-            };
-        }
-
-        /// <summary>
-        /// This method attempts to convert the given value to a PoolBlockingPeriod enum. The algorithm is:
-        /// * if the value is from type string, it will be matched against PoolBlockingPeriod enum names only, using ordinal, case-insensitive comparer
-        /// * if the value is from type PoolBlockingPeriod, it will be used as is
-        /// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum
-        /// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException
-        ///
-        /// in any case above, if the conerted value is out of valid range, the method raises ArgumentOutOfRangeException.
-        /// </summary>
-        /// <returns>PoolBlockingPeriod value in the valid range</returns>
-        internal static PoolBlockingPeriod ConvertToPoolBlockingPeriod(string keyword, object value)
-        {
-            Debug.Assert(null != value, "ConvertToPoolBlockingPeriod(null)");
-            string sValue = (value as string);
-            PoolBlockingPeriod result;
-            if (null != sValue)
-            {
-                // We could use Enum.TryParse<PoolBlockingPeriod> here, but it accepts value combinations like
-                // "ReadOnly, ReadWrite" which are unwelcome here
-                // Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method.
-                if (TryConvertToPoolBlockingPeriod(sValue, out result))
-                {
-                    return result;
-                }
-
-                // try again after remove leading & trailing whitespaces.
-                sValue = sValue.Trim();
-                if (TryConvertToPoolBlockingPeriod(sValue, out result))
-                {
-                    return result;
-                }
-
-                // string values must be valid
-                throw ADP.InvalidConnectionOptionValue(keyword);
-            }
-            else
-            {
-                // the value is not string, try other options
-                PoolBlockingPeriod eValue;
-
-                if (value is PoolBlockingPeriod)
-                {
-                    // quick path for the most common case
-                    eValue = (PoolBlockingPeriod)value;
-                }
-                else if (value.GetType().IsEnum)
-                {
-                    // explicitly block scenarios in which user tries to use wrong enum types, like:
-                    // builder["PoolBlockingPeriod"] = EnvironmentVariableTarget.Process;
-                    // workaround: explicitly cast non-PoolBlockingPeriod enums to int
-                    throw ADP.ConvertFailed(value.GetType(), typeof(PoolBlockingPeriod), null);
-                }
-                else
-                {
-                    try
-                    {
-                        // Enum.ToObject allows only integral and enum values (enums are blocked above), rasing ArgumentException for the rest
-                        eValue = (PoolBlockingPeriod)Enum.ToObject(typeof(PoolBlockingPeriod), value);
-                    }
-                    catch (ArgumentException e)
-                    {
-                        // to be consistent with the messages we send in case of wrong type usage, replace
-                        // the error with our exception, and keep the original one as inner one for troubleshooting
-                        throw ADP.ConvertFailed(value.GetType(), typeof(PoolBlockingPeriod), e);
-                    }
-                }
-
-                // ensure value is in valid range
-                if (IsValidPoolBlockingPeriodValue(eValue))
-                {
-                    return eValue;
-                }
-                else
-                {
-                    throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue);
-                }
-            }
-        }
-        #endregion
-    }
-
-    internal static partial class DbConnectionStringDefaults
-    {
-        internal const PoolBlockingPeriod PoolBlockingPeriod = System.Data.SqlClient.PoolBlockingPeriod.Auto;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs
deleted file mode 100644 (file)
index 47422c6..0000000
+++ /dev/null
@@ -1,367 +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.Data.SqlClient;
-using System.Reflection;
-
-
-namespace System.Data.Common
-{
-    internal static partial class DbConnectionStringBuilderUtil
-    {
-        internal static bool ConvertToBoolean(object value)
-        {
-            Debug.Assert(null != value, "ConvertToBoolean(null)");
-            string svalue = (value as string);
-            if (null != svalue)
-            {
-                if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
-                    return true;
-                else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
-                    return false;
-                else
-                {
-                    string tmp = svalue.Trim();  // Remove leading & trailing whitespace.
-                    if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
-                        return true;
-                    else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
-                        return false;
-                }
-                return bool.Parse(svalue);
-            }
-            try
-            {
-                return Convert.ToBoolean(value);
-            }
-            catch (InvalidCastException e)
-            {
-                throw ADP.ConvertFailed(value.GetType(), typeof(bool), e);
-            }
-        }
-
-        internal static bool ConvertToIntegratedSecurity(object value)
-        {
-            Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)");
-            string svalue = (value as string);
-            if (null != svalue)
-            {
-                if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes"))
-                    return true;
-                else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no"))
-                    return false;
-                else
-                {
-                    string tmp = svalue.Trim();  // Remove leading & trailing whitespace.
-                    if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes"))
-                        return true;
-                    else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no"))
-                        return false;
-                }
-                return bool.Parse(svalue);
-            }
-            try
-            {
-                return Convert.ToBoolean(value);
-            }
-            catch (InvalidCastException e)
-            {
-                throw ADP.ConvertFailed(value.GetType(), typeof(bool), e);
-            }
-        }
-
-        internal static int ConvertToInt32(object value)
-        {
-            try
-            {
-                return Convert.ToInt32(value);
-            }
-            catch (InvalidCastException e)
-            {
-                throw ADP.ConvertFailed(value.GetType(), typeof(int), e);
-            }
-        }
-
-        internal static string ConvertToString(object value)
-        {
-            try
-            {
-                return Convert.ToString(value);
-            }
-            catch (InvalidCastException e)
-            {
-                throw ADP.ConvertFailed(value.GetType(), typeof(string), e);
-            }
-        }
-
-        private const string ApplicationIntentReadWriteString = "ReadWrite";
-        private const string ApplicationIntentReadOnlyString = "ReadOnly";
-
-        internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result)
-        {
-            Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
-            Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)");
-
-            if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadOnlyString))
-            {
-                result = ApplicationIntent.ReadOnly;
-                return true;
-            }
-            else if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadWriteString))
-            {
-                result = ApplicationIntent.ReadWrite;
-                return true;
-            }
-            else
-            {
-                result = DbConnectionStringDefaults.ApplicationIntent;
-                return false;
-            }
-        }
-
-        internal static bool IsValidApplicationIntentValue(ApplicationIntent value)
-        {
-            Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed");
-            return value == ApplicationIntent.ReadOnly || value == ApplicationIntent.ReadWrite;
-        }
-
-        internal static string ApplicationIntentToString(ApplicationIntent value)
-        {
-            Debug.Assert(IsValidApplicationIntentValue(value));
-            if (value == ApplicationIntent.ReadOnly)
-            {
-                return ApplicationIntentReadOnlyString;
-            }
-            else
-            {
-                return ApplicationIntentReadWriteString;
-            }
-        }
-
-        /// <summary>
-        /// This method attempts to convert the given value tp ApplicationIntent enum. The algorithm is:
-        /// * if the value is from type string, it will be matched against ApplicationIntent enum names only, using ordinal, case-insensitive comparer
-        /// * if the value is from type ApplicationIntent, it will be used as is
-        /// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum
-        /// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException
-        ///
-        /// in any case above, if the converted value is out of valid range, the method raises ArgumentOutOfRangeException.
-        /// </summary>
-        /// <returns>application intent value in the valid range</returns>
-        internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value)
-        {
-            Debug.Assert(null != value, "ConvertToApplicationIntent(null)");
-            string sValue = (value as string);
-            ApplicationIntent result;
-            if (null != sValue)
-            {
-                // We could use Enum.TryParse<ApplicationIntent> here, but it accepts value combinations like
-                // "ReadOnly, ReadWrite" which are unwelcome here
-                // Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method.
-
-                if (TryConvertToApplicationIntent(sValue, out result))
-                {
-                    return result;
-                }
-
-                // try again after remove leading & trailing whitespace.
-                sValue = sValue.Trim();
-                if (TryConvertToApplicationIntent(sValue, out result))
-                {
-                    return result;
-                }
-
-                // string values must be valid
-                throw ADP.InvalidConnectionOptionValue(keyword);
-            }
-            else
-            {
-                // the value is not string, try other options
-                ApplicationIntent eValue;
-
-                if (value is ApplicationIntent)
-                {
-                    // quick path for the most common case
-                    eValue = (ApplicationIntent)value;
-                }
-                else if (value.GetType().GetTypeInfo().IsEnum)
-                {
-                    // explicitly block scenarios in which user tries to use wrong enum types, like:
-                    // builder["ApplicationIntent"] = EnvironmentVariableTarget.Process;
-                    // workaround: explicitly cast non-ApplicationIntent enums to int
-                    throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), null);
-                }
-                else
-                {
-                    try
-                    {
-                        // Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest
-                        eValue = (ApplicationIntent)Enum.ToObject(typeof(ApplicationIntent), value);
-                    }
-                    catch (ArgumentException e)
-                    {
-                        // to be consistent with the messages we send in case of wrong type usage, replace
-                        // the error with our exception, and keep the original one as inner one for troubleshooting
-                        throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), e);
-                    }
-                }
-
-                // ensure value is in valid range
-                if (IsValidApplicationIntentValue(eValue))
-                {
-                    return eValue;
-                }
-                else
-                {
-                    throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue);
-                }
-            }
-        }
-    }
-
-    internal static partial class DbConnectionStringDefaults
-    {
-        // all
-        // internal const string NamedConnection = "";
-
-        // SqlClient
-        internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite;
-        internal const string ApplicationName = "Core .Net SqlClient Data Provider";
-        internal const string AttachDBFilename = "";
-        internal const int ConnectTimeout = 15;
-        internal const string CurrentLanguage = "";
-        internal const string DataSource = "";
-        internal const bool Encrypt = false;
-        internal const bool Enlist = true;
-        internal const string FailoverPartner = "";
-        internal const string InitialCatalog = "";
-        internal const bool IntegratedSecurity = false;
-        internal const int LoadBalanceTimeout = 0; // default of 0 means don't use
-        internal const bool MultipleActiveResultSets = false;
-        internal const bool MultiSubnetFailover = false;
-        internal const int MaxPoolSize = 100;
-        internal const int MinPoolSize = 0;
-        internal const int PacketSize = 8000;
-        internal const string Password = "";
-        internal const bool PersistSecurityInfo = false;
-        internal const bool Pooling = true;
-        internal const bool TrustServerCertificate = false;
-        internal const string TypeSystemVersion = "Latest";
-        internal const string UserID = "";
-        internal const bool UserInstance = false;
-        internal const bool Replication = false;
-        internal const string WorkstationID = "";
-        internal const string TransactionBinding = "Implicit Unbind";
-        internal const int ConnectRetryCount = 1;
-        internal const int ConnectRetryInterval = 10;
-    }
-
-
-    internal static partial class DbConnectionStringKeywords
-    {
-        // all
-        // internal const string NamedConnection = "Named Connection";
-
-        // SqlClient
-        internal const string ApplicationIntent = "ApplicationIntent";
-        internal const string ApplicationName = "Application Name";
-        internal const string AsynchronousProcessing = "Asynchronous Processing";
-        internal const string AttachDBFilename = "AttachDbFilename";
-        internal const string ConnectTimeout = "Connect Timeout";
-        internal const string ConnectionReset = "Connection Reset";
-        internal const string ContextConnection = "Context Connection";
-        internal const string CurrentLanguage = "Current Language";
-        internal const string Encrypt = "Encrypt";
-        internal const string FailoverPartner = "Failover Partner";
-        internal const string InitialCatalog = "Initial Catalog";
-        internal const string MultipleActiveResultSets = "MultipleActiveResultSets";
-        internal const string MultiSubnetFailover = "MultiSubnetFailover";
-        internal const string NetworkLibrary = "Network Library";
-        internal const string PacketSize = "Packet Size";
-        internal const string Replication = "Replication";
-        internal const string TransactionBinding = "Transaction Binding";
-        internal const string TrustServerCertificate = "TrustServerCertificate";
-        internal const string TypeSystemVersion = "Type System Version";
-        internal const string UserInstance = "User Instance";
-        internal const string WorkstationID = "Workstation ID";
-        internal const string ConnectRetryCount = "ConnectRetryCount";
-        internal const string ConnectRetryInterval = "ConnectRetryInterval";
-
-        // common keywords (OleDb, OracleClient, SqlClient)
-        internal const string DataSource = "Data Source";
-        internal const string IntegratedSecurity = "Integrated Security";
-        internal const string Password = "Password";
-        internal const string Driver = "Driver";
-        internal const string PersistSecurityInfo = "Persist Security Info";
-        internal const string UserID = "User ID";
-
-        // managed pooling (OracleClient, SqlClient)
-        internal const string Enlist = "Enlist";
-        internal const string LoadBalanceTimeout = "Load Balance Timeout";
-        internal const string MaxPoolSize = "Max Pool Size";
-        internal const string Pooling = "Pooling";
-        internal const string MinPoolSize = "Min Pool Size";
-#if NETCOREAPP
-        internal const string PoolBlockingPeriod = "PoolBlockingPeriod";
-#endif
-    }
-
-    internal static class DbConnectionStringSynonyms
-    {
-        //internal const string AsynchronousProcessing = Async;
-        internal const string Async = "async";
-
-        //internal const string ApplicationName        = APP;
-        internal const string APP = "app";
-
-        //internal const string AttachDBFilename       = EXTENDEDPROPERTIES+","+INITIALFILENAME;
-        internal const string EXTENDEDPROPERTIES = "extended properties";
-        internal const string INITIALFILENAME = "initial file name";
-
-        //internal const string ConnectTimeout         = CONNECTIONTIMEOUT+","+TIMEOUT;
-        internal const string CONNECTIONTIMEOUT = "connection timeout";
-        internal const string TIMEOUT = "timeout";
-
-        //internal const string CurrentLanguage        = LANGUAGE;
-        internal const string LANGUAGE = "language";
-
-        //internal const string OraDataSource          = SERVER;
-        //internal const string SqlDataSource          = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS;
-        internal const string ADDR = "addr";
-        internal const string ADDRESS = "address";
-        internal const string SERVER = "server";
-        internal const string NETWORKADDRESS = "network address";
-
-        //internal const string InitialCatalog         = DATABASE;
-        internal const string DATABASE = "database";
-
-        //internal const string IntegratedSecurity     = TRUSTEDCONNECTION;
-        internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in Everett
-
-        //internal const string LoadBalanceTimeout     = ConnectionLifetime;
-        internal const string ConnectionLifetime = "connection lifetime";
-
-        //internal const string NetworkLibrary         = NET+","+NETWORK;
-        internal const string NET = "net";
-        internal const string NETWORK = "network";
-
-
-        //internal const string Password               = Pwd;
-        internal const string Pwd = "pwd";
-
-        //internal const string PersistSecurityInfo    = PERSISTSECURITYINFO;
-        internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
-
-        //internal const string UserID                 = UID+","+User;
-        internal const string UID = "uid";
-        internal const string User = "user";
-
-        //internal const string WorkstationID          = WSID;
-        internal const string WSID = "wsid";
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Common/SR.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Common/SR.cs
deleted file mode 100644 (file)
index 15078bc..0000000
+++ /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.
-
-namespace System
-{
-    internal static partial class SR
-    {
-        internal static string GetString(string value)
-        {
-            return value;
-        }
-
-        internal static string GetString(string format, params object[] args)
-        {
-            return SR.Format(format, args);
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/DataException.cs b/src/libraries/System.Data.SqlClient/src/System/Data/DataException.cs
deleted file mode 100644 (file)
index 9fab61f..0000000
+++ /dev/null
@@ -1,48 +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.Data
-{
-    // These functions are major point of localization.
-    // We need to have a rules to enforce consistency there.
-    // The dangerous point there are the string arguments of the exported (internal) methods.
-    // This string can be argument, table or constraint name but never text of exception itself.
-    // Make an invariant that all texts of exceptions coming from resources only.
-
-
-    internal static class ExceptionBuilder
-    {
-        // The class defines the exceptions that are specific to the DataSet.
-        // The class contains functions that take the proper informational variables and then construct
-        // the appropriate exception with an error string obtained from the resource Data.txt.
-        // The exception is then returned to the caller, so that the caller may then throw from its
-        // location so that the catcher of the exception will have the appropriate call stack.
-        // This class is used so that there will be compile time checking of error messages.
-        // The resource Data.txt will ensure proper string text based on the appropriate
-        // locale.
-
-        internal static void TraceExceptionAsReturnValue(Exception e)
-        {
-        }
-
-        //
-        // COM+ exceptions
-        //
-        internal static ArgumentException _Argument(string error)
-        {
-            ArgumentException e = new ArgumentException(error);
-            ExceptionBuilder.TraceExceptionAsReturnValue(e);
-            return e;
-        }
-        public static Exception InvalidOffsetLength()
-        {
-            return _Argument(SR.GetString(SR.Data_InvalidOffsetLength));
-        }
-    }// ExceptionBuilder
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/OperationAbortedException.cs b/src/libraries/System.Data.SqlClient/src/System/Data/OperationAbortedException.cs
deleted file mode 100644 (file)
index b33054f..0000000
+++ /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.Runtime.Serialization;
-
-namespace System.Data
-{
-    [Serializable]
-    [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
-    public sealed class OperationAbortedException : SystemException
-    {
-        private OperationAbortedException(string message, Exception innerException) : base(message, innerException)
-        {
-            HResult = unchecked((int)0x80131936);
-        }
-
-        private OperationAbortedException(SerializationInfo info, StreamingContext context) : base(info, context)
-        {
-        }
-
-        internal static OperationAbortedException Aborted(Exception inner)
-        {
-            OperationAbortedException e;
-            if (inner == null)
-            {
-                e = new OperationAbortedException(SR.GetString(SR.ADP_OperationAborted), null);
-            }
-            else
-            {
-                e = new OperationAbortedException(SR.GetString(SR.ADP_OperationAbortedExceptionMessage), inner);
-            }
-            return e;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs
deleted file mode 100644 (file)
index 74f48b8..0000000
+++ /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.Data.Common;
-using System.Transactions;
-
-namespace System.Data.ProviderBase
-{
-    internal abstract partial class DbConnectionClosed : DbConnectionInternal
-    {
-        protected override void Activate(Transaction transaction) => throw ADP.ClosedConnectionError();
-
-        public override void EnlistTransaction(Transaction transaction) => throw ADP.ClosedConnectionError();
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs
deleted file mode 100644 (file)
index 3904540..0000000
+++ /dev/null
@@ -1,186 +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.Data.Common;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.ProviderBase
-{
-    internal abstract partial class DbConnectionFactory
-    {
-
-        internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
-        {
-            Debug.Assert(null != owningConnection, "null owningConnection?");
-
-            DbConnectionPoolGroup poolGroup;
-            DbConnectionPool connectionPool;
-            connection = null;
-
-            //  Work around race condition with clearing the pool between GetConnectionPool obtaining pool
-            //  and GetConnection on the pool checking the pool state.  Clearing the pool in this window
-            //  will switch the pool into the ShuttingDown state, and GetConnection will return null.
-            //  There is probably a better solution involving locking the pool/group, but that entails a major
-            //  re-design of the connection pooling synchronization, so is postponed for now.
-
-            // Use retriesLeft to prevent CPU spikes with incremental sleep
-            // start with one msec, double the time every retry
-            // max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries)
-            int retriesLeft = 10;
-            int timeBetweenRetriesMilliseconds = 1;
-
-            do
-            {
-                poolGroup = GetConnectionPoolGroup(owningConnection);
-                // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread.
-                connectionPool = GetConnectionPool(owningConnection, poolGroup);
-                if (null == connectionPool)
-                {
-                    // If GetConnectionPool returns null, we can be certain that
-                    // this connection should not be pooled via DbConnectionPool
-                    // or have a disabled pool entry.
-                    poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled
-
-                    if (retry != null)
-                    {
-                        Task<DbConnectionInternal> newTask;
-                        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
-                        lock (s_pendingOpenNonPooled)
-                        {
-                            // look for an available task slot (completed or empty)
-                            int idx;
-                            for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++)
-                            {
-                                Task task = s_pendingOpenNonPooled[idx];
-                                if (task == null)
-                                {
-                                    s_pendingOpenNonPooled[idx] = GetCompletedTask();
-                                    break;
-                                }
-                                else if (task.IsCompleted)
-                                {
-                                    break;
-                                }
-                            }
-
-                            // if didn't find one, pick the next one in round-robin fashion
-                            if (idx == s_pendingOpenNonPooled.Length)
-                            {
-                                idx = (int)(s_pendingOpenNonPooledNext % s_pendingOpenNonPooled.Length);
-                                unchecked
-                                {
-                                    s_pendingOpenNonPooledNext++;
-                                }
-                            }
-
-                            // now that we have an antecedent task, schedule our work when it is completed.
-                            // If it is a new slot or a completed task, this continuation will start right away.
-                            newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) =>
-                            {
-                                Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction();
-                                try
-                                {
-                                    ADP.SetCurrentTransaction(retry.Task.AsyncState as Transactions.Transaction);
-                                    var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
-                                    if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
-                                    {
-                                        oldConnection.PrepareForReplaceConnection();
-                                        oldConnection.Dispose();
-                                    }
-                                    return newConnection;
-                                }
-                                finally
-                                {
-                                    ADP.SetCurrentTransaction(originalTransaction);
-                                }
-                            }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
-
-                            // Place this new task in the slot so any future work will be queued behind it
-                            s_pendingOpenNonPooled[idx] = newTask;
-                        }
-
-                        // Set up the timeout (if needed)
-                        if (owningConnection.ConnectionTimeout > 0)
-                        {
-                            int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000;
-                            cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds);
-                        }
-
-                        // once the task is done, propagate the final results to the original caller
-                        newTask.ContinueWith((task) =>
-                        {
-                            cancellationTokenSource.Dispose();
-                            if (task.IsCanceled)
-                            {
-                                retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout()));
-                            }
-                            else if (task.IsFaulted)
-                            {
-                                retry.TrySetException(task.Exception.InnerException);
-                            }
-                            else
-                            {
-                                if (!retry.TrySetResult(task.Result))
-                                {
-                                    // The outer TaskCompletionSource was already completed
-                                    // Which means that we don't know if someone has messed with the outer connection in the middle of creation
-                                    // So the best thing to do now is to destroy the newly created connection
-                                    task.Result.DoomThisConnection();
-                                    task.Result.Dispose();
-                                }
-                            }
-                        }, TaskScheduler.Default);
-
-                        return false;
-                    }
-
-                    connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
-                }
-                else
-                {
-                    if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection)
-                    {
-                        Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection");
-                        connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection);
-                    }
-                    else
-                    {
-                        if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection))
-                        {
-                            return false;
-                        }
-                    }
-
-                    if (connection == null)
-                    {
-                        // connection creation failed on semaphore waiting or if max pool reached
-                        if (connectionPool.IsRunning)
-                        {
-                            // If GetConnection failed while the pool is running, the pool timeout occurred.
-                            throw ADP.PooledOpenTimeout();
-                        }
-                        else
-                        {
-                            // We've hit the race condition, where the pool was shut down after we got it from the group.
-                            // Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated
-                            //  before retrying.
-                            Threading.Thread.Sleep(timeBetweenRetriesMilliseconds);
-                            timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration
-                        }
-                    }
-                }
-            } while (connection == null && retriesLeft-- > 0);
-
-            if (connection == null)
-            {
-                // exhausted all retries or timed out - give up
-                throw ADP.PooledOpenTimeout();
-            }
-
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs
deleted file mode 100644 (file)
index 2073910..0000000
+++ /dev/null
@@ -1,469 +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.Data.Common;
-using System.Diagnostics;
-using System.Threading;
-using System.Transactions;
-
-
-namespace System.Data.ProviderBase
-{
-    internal abstract partial class DbConnectionInternal
-    {
-        private bool _isInStasis;
-
-        private Transaction _enlistedTransaction;      // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
-
-        // _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
-        // However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
-        // This field should only be assigned a value at the same time _enlistedTransaction is updated.
-        // Also, this reference should not be disposed, since we aren't taking ownership of it.
-        private Transaction _enlistedTransactionOriginal;
-
-        protected internal Transaction EnlistedTransaction
-        {
-            get
-            {
-                return _enlistedTransaction;
-            }
-            set
-            {
-                Transaction currentEnlistedTransaction = _enlistedTransaction;
-                if (((null == currentEnlistedTransaction) && (null != value))
-                    || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value)))
-                {  // WebData 20000024
-
-                    // Pay attention to the order here:
-                    // 1) defect from any notifications
-                    // 2) replace the transaction
-                    // 3) re-enlist in notifications for the new transaction
-
-                    // SQLBUDT #230558 we need to use a clone of the transaction
-                    // when we store it, or we'll end up keeping it past the
-                    // duration of the using block of the TransactionScope
-                    Transaction valueClone = null;
-                    Transaction previousTransactionClone = null;
-                    try
-                    {
-                        if (null != value)
-                        {
-                            valueClone = value.Clone();
-                        }
-
-                        // NOTE: rather than take locks around several potential round-
-                        // trips to the server, and/or virtual function calls, we simply
-                        // presume that you aren't doing something illegal from multiple
-                        // threads, and check once we get around to finalizing things
-                        // inside a lock.
-
-                        lock (this)
-                        {
-                            // NOTE: There is still a race condition here, when we are
-                            // called from EnlistTransaction (which cannot re-enlist)
-                            // instead of EnlistDistributedTransaction (which can),
-                            // however this should have been handled by the outer
-                            // connection which checks to ensure that it's OK.  The
-                            // only case where we have the race condition is multiple
-                            // concurrent enlist requests to the same connection, which
-                            // is a bit out of line with something we should have to
-                            // support.
-
-                            // enlisted transaction can be nullified in Dispose call without lock
-                            previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
-                            _enlistedTransactionOriginal = value;
-                            value = valueClone;
-                            valueClone = null; // we've stored it, don't dispose it.
-                        }
-                    }
-                    finally
-                    {
-                        // we really need to dispose our clones; they may have
-                        // native resources and GC may not happen soon enough.
-                        // VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
-                        if (null != previousTransactionClone &&
-                                !object.ReferenceEquals(previousTransactionClone, _enlistedTransaction))
-                        {
-                            previousTransactionClone.Dispose();
-                        }
-                        if (null != valueClone && !object.ReferenceEquals(valueClone, _enlistedTransaction))
-                        {
-                            valueClone.Dispose();
-                        }
-                    }
-
-                    // I don't believe that we need to lock to protect the actual
-                    // enlistment in the transaction; it would only protect us
-                    // against multiple concurrent calls to enlist, which really
-                    // isn't supported anyway.
-
-                    if (null != value)
-                    {
-                        TransactionOutcomeEnlist(value);
-                    }
-                }
-            }
-        }
-
-        /// <summary>
-        /// Get boolean value that indicates whether the enlisted transaction has been disposed.
-        /// </summary>
-        /// <value>
-        /// True if there is an enlisted transaction, and it has been disposed.
-        /// False if there is an enlisted transaction that has not been disposed, or if the transaction reference is null.
-        /// </value>
-        /// <remarks>
-        /// This method must be called while holding a lock on the DbConnectionInternal instance.
-        /// </remarks>
-        protected bool EnlistedTransactionDisposed
-        {
-            get
-            {
-                // Until the Transaction.Disposed property is public it is necessary to access a member
-                // that throws if the object is disposed to determine if in fact the transaction is disposed.
-                try
-                {
-                    bool disposed;
-
-                    Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal;
-                    if (currentEnlistedTransactionOriginal != null)
-                    {
-                        disposed = currentEnlistedTransactionOriginal.TransactionInformation == null;
-                    }
-                    else
-                    {
-                        // Don't expect to get here in the general case,
-                        // Since this getter is called by CheckEnlistedTransactionBinding
-                        // after checking for a non-null enlisted transaction (and it does so under lock).
-                        disposed = false;
-                    }
-
-                    return disposed;
-                }
-                catch (ObjectDisposedException)
-                {
-                    return true;
-                }
-            }
-        }
-
-        internal bool IsTxRootWaitingForTxEnd
-        {
-            get
-            {
-                return _isInStasis;
-            }
-        }
-
-        protected virtual bool UnbindOnTransactionCompletion
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        // Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
-        protected internal virtual bool IsNonPoolableTransactionRoot
-        {
-            get
-            {
-                return false; // if you want to have delegated transactions that are non-poolable, you better override this...
-            }
-        }
-
-        internal virtual bool IsTransactionRoot
-        {
-            get
-            {
-                return false; // if you want to have delegated transactions, you better override this...
-            }
-        }
-
-        protected virtual bool ReadyToPrepareTransaction
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        protected abstract void Activate(Transaction transaction);
-
-        internal void ActivateConnection(Transaction transaction)
-        {
-            // Internal method called from the connection pooler so we don't expose
-            // the Activate method publicly.
-
-            Activate(transaction);
-        }
-
-        internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
-        {
-            // The implementation here is the implementation required for the
-            // "open" internal connections, since our own private "closed"
-            // singleton internal connection objects override this method to
-            // prevent anything funny from happening (like disposing themselves
-            // or putting them into a connection pool)
-            //
-            // Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose
-            // for cleaning up after DbConnection.Close
-            //     protected override void Deactivate() { // override DbConnectionInternal.Close
-            //         // do derived class connection deactivation for both pooled & non-pooled connections
-            //     }
-            //     public override void Dispose() { // override DbConnectionInternal.Close
-            //         // do derived class cleanup
-            //         base.Dispose();
-            //     }
-            //
-            // overriding DbConnection.Close is also possible, but must provider for their own synchronization
-            //     public override void Close() { // override DbConnection.Close
-            //         base.Close();
-            //         // do derived class outer connection for both pooled & non-pooled connections
-            //         // user must do their own synchronization here
-            //     }
-            //
-            //     if the DbConnectionInternal derived class needs to close the connection it should
-            //     delegate to the DbConnection if one exists or directly call dispose
-            //         DbConnection owningObject = (DbConnection)Owner;
-            //         if (null != owningObject) {
-            //             owningObject.Close(); // force the closed state on the outer object.
-            //         }
-            //         else {
-            //             Dispose();
-            //         }
-            //
-            ////////////////////////////////////////////////////////////////
-            // DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING!
-            ////////////////////////////////////////////////////////////////
-            Debug.Assert(null != owningObject, "null owningObject");
-            Debug.Assert(null != connectionFactory, "null connectionFactory");
-
-
-            // 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
-            // block doesn't really help because a ThreadAbort during the finally block
-            // would just revert the connection to a bad state.
-            // Open->Closed: guarantee internal connection is returned to correct pool
-            if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this))
-            {
-                // Lock to prevent race condition with cancellation
-                lock (this)
-                {
-                    object lockToken = ObtainAdditionalLocksForClose();
-                    try
-                    {
-                        PrepareForCloseConnection();
-
-                        DbConnectionPool connectionPool = Pool;
-
-                        // Detach from enlisted transactions that are no longer active on close
-                        DetachCurrentTransactionIfEnded();
-
-                        // The singleton closed classes won't have owners and
-                        // connection pools, and we won't want to put them back
-                        // into the pool.
-                        if (null != connectionPool)
-                        {
-                            connectionPool.PutObject(this, owningObject);   // PutObject calls Deactivate for us...
-                                                                            // NOTE: Before we leave the PutObject call, another
-                                                                            // thread may have already popped the connection from
-                                                                            // the pool, so don't expect to be able to verify it.
-                        }
-                        else
-                        {
-                            Deactivate();   // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up...
-
-                            // To prevent an endless recursion, we need to clear
-                            // the owning object before we call dispose so that
-                            // we can't get here a second time... Ordinarily, I
-                            // would call setting the owner to null a hack, but
-                            // this is safe since we're about to dispose the
-                            // object and it won't have an owner after that for
-                            // certain.
-                            _owningObject.Target = null;
-
-                            if (IsTransactionRoot)
-                            {
-                                SetInStasis();
-                            }
-                            else
-                            {
-                                Dispose();
-                            }
-                        }
-                    }
-                    finally
-                    {
-                        ReleaseAdditionalLocksForClose(lockToken);
-                        // if a ThreadAbort puts us here then its possible the outer connection will not reference
-                        // this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope.
-                        connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
-                    }
-                }
-            }
-        }
-
-        internal virtual void DelegatedTransactionEnded()
-        {
-            // Called by System.Transactions when the delegated transaction has
-            // completed.  We need to make closed connections that are in stasis
-            // available again, or disposed closed/leaked non-pooled connections.
-
-            // IMPORTANT NOTE: You must have taken a lock on the object before
-            // you call this method to prevent race conditions with Clear and
-            // ReclaimEmancipatedObjects.
-
-
-            if (1 == _pooledCount)
-            {
-                // When _pooledCount is 1, it indicates a closed, pooled,
-                // connection so it is ready to put back into the pool for
-                // general use.
-
-                TerminateStasis(true);
-
-                Deactivate(); // call it one more time just in case
-
-                DbConnectionPool pool = Pool;
-
-                if (null == pool)
-                {
-                    throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool);      // pooled connection does not have a pool
-                }
-                pool.PutObjectFromTransactedPool(this);
-            }
-            else if (-1 == _pooledCount && !_owningObject.IsAlive)
-            {
-                // When _pooledCount is -1 and the owning object no longer exists,
-                // it indicates a closed (or leaked), non-pooled connection so
-                // it is safe to dispose.
-
-                TerminateStasis(false);
-
-                Deactivate(); // call it one more time just in case
-
-                // it's a non-pooled connection, we need to dispose of it
-                // once and for all, or the server will have fits about us
-                // leaving connections open until the client-side GC kicks
-                // in.
-                Dispose();
-            }
-            // When _pooledCount is 0, the connection is a pooled connection
-            // that is either open (if the owning object is alive) or leaked (if
-            // the owning object is not alive)  In either case, we can't muck
-            // with the connection here.
-        }
-
-        public virtual void Dispose()
-        {
-            _connectionPool = null;
-            _connectionIsDoomed = true;
-            _enlistedTransactionOriginal = null; // should not be disposed
-
-            // Dispose of the _enlistedTransaction since it is a clone
-            // of the original reference.
-            // VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event)
-            Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null);
-            if (enlistedTransaction != null)
-            {
-                enlistedTransaction.Dispose();
-            }
-        }
-
-        public abstract void EnlistTransaction(Transaction transaction);
-
-        // Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
-        //  This is a separate method because cleanup can be triggered in multiple ways for a delegated
-        //  transaction.
-        protected virtual void CleanupTransactionOnCompletion(Transaction transaction)
-        {
-        }
-
-        internal void DetachCurrentTransactionIfEnded()
-        {
-            Transaction enlistedTransaction = EnlistedTransaction;
-            if (enlistedTransaction != null)
-            {
-                bool transactionIsDead;
-                try
-                {
-                    transactionIsDead = (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
-                }
-                catch (TransactionException)
-                {
-                    // If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
-                    transactionIsDead = true;
-                }
-                if (transactionIsDead)
-                {
-                    DetachTransaction(enlistedTransaction, true);
-                }
-            }
-        }
-
-        // Detach transaction from connection.
-        internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing)
-        {
-            // 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
-            // be the exception, not the rule.
-            lock (this)
-            {
-                // Detach if detach-on-end behavior, or if outer connection was closed
-                DbConnection owner = (DbConnection)Owner;
-                if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner)
-                {
-                    Transaction currentEnlistedTransaction = _enlistedTransaction;
-                    if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction))
-                    {
-                        EnlistedTransaction = null;
-
-                        if (IsTxRootWaitingForTxEnd)
-                        {
-                            DelegatedTransactionEnded();
-                        }
-                    }
-                }
-            }
-        }
-
-        // Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
-        internal void CleanupConnectionOnTransactionCompletion(Transaction transaction)
-        {
-            DetachTransaction(transaction, false);
-
-            DbConnectionPool pool = Pool;
-            if (null != pool)
-            {
-                pool.TransactionEnded(transaction, this);
-            }
-        }
-
-        private void TransactionCompletedEvent(object sender, TransactionEventArgs e)
-        {
-            Transaction transaction = e.Transaction;
-
-            CleanupTransactionOnCompletion(transaction);
-
-            CleanupConnectionOnTransactionCompletion(transaction);
-        }
-
-        private void TransactionOutcomeEnlist(Transaction transaction)
-        {
-            transaction.TransactionCompleted += new TransactionCompletedEventHandler(TransactionCompletedEvent);
-        }
-
-        internal void SetInStasis()
-        {
-            _isInStasis = true;
-        }
-
-        private void TerminateStasis(bool returningToPool)
-        {
-            _isInStasis = false;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.NetCoreApp.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.NetCoreApp.cs
deleted file mode 100644 (file)
index be97b8c..0000000
+++ /dev/null
@@ -1,53 +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.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.ProviderBase
-{
-    internal sealed partial class DbConnectionPool
-    {
-        partial void CheckPoolBlockingPeriod(Exception e)
-        {
-            if (!IsBlockingPeriodEnabled())
-            {
-                throw e;
-            }
-        }
-
-        private bool IsBlockingPeriodEnabled()
-        {
-            var poolGroupConnectionOptions = _connectionPoolGroup.ConnectionOptions as SqlConnectionString;
-            if (poolGroupConnectionOptions == null)
-            {
-                return true;
-            }
-            var policy = poolGroupConnectionOptions.PoolBlockingPeriod;
-
-            switch (policy)
-            {
-                case System.Data.SqlClient.PoolBlockingPeriod.Auto:
-                    {
-                        return !ADP.IsAzureSqlServerEndpoint(poolGroupConnectionOptions.DataSource);
-                    }
-                case System.Data.SqlClient.PoolBlockingPeriod.AlwaysBlock:
-                    {
-                        return true; //Enabled
-                    }
-                case System.Data.SqlClient.PoolBlockingPeriod.NeverBlock:
-                    {
-                        return false; //Disabled
-                    }
-                default:
-                    {
-                        //we should never get into this path.
-                        Debug.Fail("Unknown PoolBlockingPeriod. Please specify explicit results in above switch case statement.");
-                        return true;
-                    }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs
deleted file mode 100644 (file)
index 876cec1..0000000
+++ /dev/null
@@ -1,1628 +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.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Collections.Concurrent;
-using System.Transactions;
-
-namespace System.Data.ProviderBase
-{
-    internal sealed partial class DbConnectionPool
-    {
-        private enum State
-        {
-            Initializing,
-            Running,
-            ShuttingDown,
-        }
-
-        // This class is a way to stash our cloned Tx key for later disposal when it's no longer needed.
-        // We can't get at the key in the dictionary without enumerating entries, so we stash an extra
-        // copy as part of the value.
-        private sealed class TransactedConnectionList : List<DbConnectionInternal>
-        {
-            private readonly Transaction _transaction;
-            internal TransactedConnectionList(int initialAllocation, Transaction tx) : base(initialAllocation)
-            {
-                _transaction = tx;
-            }
-
-            internal void Dispose()
-            {
-                if (null != _transaction)
-                {
-                    _transaction.Dispose();
-                }
-            }
-        }
-
-        private sealed class PendingGetConnection
-        {
-            public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions userOptions)
-            {
-                DueTime = dueTime;
-                Owner = owner;
-                Completion = completion;
-            }
-            public long DueTime { get; private set; }
-            public DbConnection Owner { get; private set; }
-            public TaskCompletionSource<DbConnectionInternal> Completion { get; private set; }
-            public DbConnectionOptions UserOptions { get; private set; }
-        }
-
-        private sealed class TransactedConnectionPool
-        {
-            private readonly Dictionary<Transaction, TransactedConnectionList> _transactedCxns;
-
-            private readonly DbConnectionPool _pool;
-
-            private static int _objectTypeCount; // Bid counter
-            internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
-
-            internal TransactedConnectionPool(DbConnectionPool pool)
-            {
-                Debug.Assert(null != pool, "null pool?");
-
-                _pool = pool;
-                _transactedCxns = new Dictionary<Transaction, TransactedConnectionList>();
-            }
-
-            internal int ObjectID
-            {
-                get
-                {
-                    return _objectID;
-                }
-            }
-
-            internal DbConnectionPool Pool
-            {
-                get
-                {
-                    return _pool;
-                }
-            }
-
-            internal DbConnectionInternal GetTransactedObject(Transaction transaction)
-            {
-                Debug.Assert(null != transaction, "null transaction?");
-
-                DbConnectionInternal transactedObject = null;
-
-                TransactedConnectionList connections;
-                bool txnFound = false;
-
-                lock (_transactedCxns)
-                {
-                    txnFound = _transactedCxns.TryGetValue(transaction, out connections);
-                }
-
-                // NOTE: GetTransactedObject is only used when AutoEnlist = True and the ambient transaction
-                //   (Sys.Txns.Txn.Current) is still valid/non-null. This, in turn, means that we don't need
-                //   to worry about a pending asynchronous TransactionCompletedEvent to trigger processing in
-                //   TransactionEnded below and potentially wipe out the connections list underneath us. It
-                //   is similarly alright if a pending addition to the connections list in PutTransactedObject
-                //   below is not completed prior to the lock on the connections object here...getting a new
-                //   connection is probably better than unnecessarily locking
-                if (txnFound)
-                {
-                    Debug.Assert(connections != null);
-
-                    // synchronize multi-threaded access with PutTransactedObject (TransactionEnded should
-                    //   not be a concern, see comments above)
-                    lock (connections)
-                    {
-                        int i = connections.Count - 1;
-                        if (0 <= i)
-                        {
-                            transactedObject = connections[i];
-                            connections.RemoveAt(i);
-                        }
-                    }
-                }
-
-                return transactedObject;
-            }
-
-            internal void PutTransactedObject(Transaction transaction, DbConnectionInternal transactedObject)
-            {
-                Debug.Assert(null != transaction, "null transaction?");
-                Debug.Assert(null != transactedObject, "null transactedObject?");
-
-                TransactedConnectionList connections;
-                bool txnFound = false;
-
-                // NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
-                //   around the order in which PutTransactionObject and TransactionEnded are called.
-
-                lock (_transactedCxns)
-                {
-                    // Check if a transacted pool has been created for this transaction
-                    if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
-                    {
-                        Debug.Assert(connections != null);
-
-                        // synchronize multi-threaded access with GetTransactedObject
-                        lock (connections)
-                        {
-                            Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
-                            connections.Add(transactedObject);
-                        }
-                    }
-                }
-
-                // CONSIDER: the following code is more complicated than it needs to be to avoid cloning the
-                //   transaction and allocating memory within a lock. Is that complexity really necessary?
-                if (!txnFound)
-                {
-                    // create the transacted pool, making sure to clone the associated transaction
-                    //   for use as a key in our internal dictionary of transactions and connections
-                    Transaction transactionClone = null;
-                    TransactedConnectionList newConnections = null;
-
-                    try
-                    {
-                        transactionClone = transaction.Clone();
-                        newConnections = new TransactedConnectionList(2, transactionClone); // start with only two connections in the list; most times we won't need that many.
-
-                        lock (_transactedCxns)
-                        {
-                            // NOTE: in the interim between the locks on the transacted pool (this) during
-                            //   execution of this method, another thread (threadB) may have attempted to
-                            //   add a different connection to the transacted pool under the same
-                            //   transaction. As a result, threadB may have completed creating the
-                            //   transacted pool while threadA was processing the above instructions.
-                            if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
-                            {
-                                Debug.Assert(connections != null);
-
-                                // synchronize multi-threaded access with GetTransactedObject
-                                lock (connections)
-                                {
-                                    Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
-                                    connections.Add(transactedObject);
-                                }
-                            }
-                            else
-                            {
-                                // add the connection/transacted object to the list
-                                newConnections.Add(transactedObject);
-
-                                _transactedCxns.Add(transactionClone, newConnections);
-                                transactionClone = null; // we've used it -- don't throw it or the TransactedConnectionList that references it away.
-                            }
-                        }
-                    }
-                    finally
-                    {
-                        if (null != transactionClone)
-                        {
-                            if (newConnections != null)
-                            {
-                                // another thread created the transaction pool and thus the new
-                                //   TransactedConnectionList was not used, so dispose of it and
-                                //   the transaction clone that it incorporates.
-                                newConnections.Dispose();
-                            }
-                            else
-                            {
-                                // memory allocation for newConnections failed...clean up unused transactionClone
-                                transactionClone.Dispose();
-                            }
-                        }
-                    }
-                }
-            }
-
-            internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject)
-            {
-                TransactedConnectionList connections;
-                int entry = -1;
-
-                // NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
-                //   around the order in which PutTransactionObject and TransactionEnded are called. As
-                //   such, it is possible that the transaction does not yet have a pool created.
-
-                // TODO: is this a plausible and/or likely scenario? Do we need to have a mechanism to ensure
-                // TODO:   that the pending creation of a transacted pool for this transaction is aborted when
-                // TODO:   PutTransactedObject finally gets some CPU time?
-
-                lock (_transactedCxns)
-                {
-                    if (_transactedCxns.TryGetValue(transaction, out connections))
-                    {
-                        Debug.Assert(connections != null);
-
-                        bool shouldDisposeConnections = false;
-
-                        // Lock connections to avoid conflict with GetTransactionObject
-                        lock (connections)
-                        {
-                            entry = connections.IndexOf(transactedObject);
-
-                            if (entry >= 0)
-                            {
-                                connections.RemoveAt(entry);
-                            }
-
-                            // Once we've completed all the ended notifications, we can
-                            // safely remove the list from the transacted pool.
-                            if (0 >= connections.Count)
-                            {
-                                _transactedCxns.Remove(transaction);
-
-                                // we really need to dispose our connection list; it may have
-                                // native resources via the tx and GC may not happen soon enough.
-                                shouldDisposeConnections = true;
-                            }
-                        }
-
-                        if (shouldDisposeConnections)
-                        {
-                            connections.Dispose();
-                        }
-                    }
-                }
-
-                // If (and only if) we found the connection in the list of
-                // connections, we'll put it back...
-                if (0 <= entry)
-                {
-                    Pool.PutObjectFromTransactedPool(transactedObject);
-                }
-            }
-
-        }
-
-        private sealed class PoolWaitHandles
-        {
-            private readonly Semaphore _poolSemaphore;
-            private readonly ManualResetEvent _errorEvent;
-
-            // Using a Mutex requires ThreadAffinity because SQL CLR can swap
-            // the underlying Win32 thread associated with a managed thread in preemptive mode.
-            // Using an AutoResetEvent does not have that complication.
-            private readonly Semaphore _creationSemaphore;
-
-            private readonly WaitHandle[] _handlesWithCreate;
-            private readonly WaitHandle[] _handlesWithoutCreate;
-
-            internal PoolWaitHandles()
-            {
-                _poolSemaphore = new Semaphore(0, MAX_Q_SIZE);
-                _errorEvent = new ManualResetEvent(false);
-                _creationSemaphore = new Semaphore(1, 1);
-
-                _handlesWithCreate = new WaitHandle[] { _poolSemaphore, _errorEvent, _creationSemaphore };
-                _handlesWithoutCreate = new WaitHandle[] { _poolSemaphore, _errorEvent };
-            }
-
-
-            internal Semaphore CreationSemaphore
-            {
-                get { return _creationSemaphore; }
-            }
-
-            internal ManualResetEvent ErrorEvent
-            {
-                get { return _errorEvent; }
-            }
-
-            internal Semaphore PoolSemaphore
-            {
-                get { return _poolSemaphore; }
-            }
-
-            internal WaitHandle[] GetHandles(bool withCreate)
-            {
-                return withCreate ? _handlesWithCreate : _handlesWithoutCreate;
-            }
-        }
-
-        private const int MAX_Q_SIZE = (int)0x00100000;
-
-        // The order of these is important; we want the WaitAny call to be signaled
-        // for a free object before a creation signal.  Only the index first signaled
-        // object is returned from the WaitAny call.
-        private const int SEMAPHORE_HANDLE = (int)0x0;
-        private const int ERROR_HANDLE = (int)0x1;
-        private const int CREATION_HANDLE = (int)0x2;
-        private const int BOGUS_HANDLE = (int)0x3;
-
-
-        private const int ERROR_WAIT_DEFAULT = 5 * 1000; // 5 seconds
-
-        // we do want a testable, repeatable set of generated random numbers
-        private static readonly Random s_random = new Random(5101977); // Value obtained from Dave Driver
-
-        private readonly int _cleanupWait;
-        private readonly DbConnectionPoolIdentity _identity;
-
-        private readonly DbConnectionFactory _connectionFactory;
-        private readonly DbConnectionPoolGroup _connectionPoolGroup;
-        private readonly DbConnectionPoolGroupOptions _connectionPoolGroupOptions;
-        private readonly DbConnectionPoolProviderInfo _connectionPoolProviderInfo;
-
-        private State _state;
-
-        private readonly ConcurrentStack<DbConnectionInternal> _stackOld = new ConcurrentStack<DbConnectionInternal>();
-        private readonly ConcurrentStack<DbConnectionInternal> _stackNew = new ConcurrentStack<DbConnectionInternal>();
-
-        private readonly ConcurrentQueue<PendingGetConnection> _pendingOpens = new ConcurrentQueue<PendingGetConnection>();
-        private int _pendingOpensWaiting = 0;
-
-        private readonly WaitCallback _poolCreateRequest;
-
-        private int _waitCount;
-        private readonly PoolWaitHandles _waitHandles;
-
-        private Exception _resError;
-        private volatile bool _errorOccurred;
-
-        private int _errorWait;
-        private Timer _errorTimer;
-
-        private Timer _cleanupTimer;
-
-        private readonly TransactedConnectionPool _transactedConnectionPool;
-
-        private readonly List<DbConnectionInternal> _objectList;
-        private int _totalObjects;
-
-
-        // only created by DbConnectionPoolGroup.GetConnectionPool
-        internal DbConnectionPool(
-                            DbConnectionFactory connectionFactory,
-                            DbConnectionPoolGroup connectionPoolGroup,
-                            DbConnectionPoolIdentity identity,
-                            DbConnectionPoolProviderInfo connectionPoolProviderInfo)
-        {
-            Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup");
-
-            if ((null != identity) && identity.IsRestricted)
-            {
-                throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken);
-            }
-
-            _state = State.Initializing;
-
-            lock (s_random)
-            { // Random.Next is not thread-safe
-                _cleanupWait = s_random.Next(12, 24) * 10 * 1000; // 2-4 minutes in 10 sec intervals
-            }
-
-            _connectionFactory = connectionFactory;
-            _connectionPoolGroup = connectionPoolGroup;
-            _connectionPoolGroupOptions = connectionPoolGroup.PoolGroupOptions;
-            _connectionPoolProviderInfo = connectionPoolProviderInfo;
-            _identity = identity;
-
-            _waitHandles = new PoolWaitHandles();
-
-            _errorWait = ERROR_WAIT_DEFAULT;
-            _errorTimer = null;  // No error yet.
-
-            _objectList = new List<DbConnectionInternal>(MaxPoolSize);
-
-            _transactedConnectionPool = new TransactedConnectionPool(this); // initialize irrespective of platform
-
-            _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback
-            _state = State.Running;
-
-            //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls
-            // StartBackgroundCallbacks after pool is actually in the collection
-        }
-
-        private int CreationTimeout
-        {
-            get { return PoolGroupOptions.CreationTimeout; }
-        }
-
-        internal int Count
-        {
-            get { return _totalObjects; }
-        }
-
-        internal DbConnectionFactory ConnectionFactory
-        {
-            get { return _connectionFactory; }
-        }
-
-        internal bool ErrorOccurred
-        {
-            get { return _errorOccurred; }
-        }
-
-        private bool HasTransactionAffinity
-        {
-            get { return PoolGroupOptions.HasTransactionAffinity; }
-        }
-
-        internal TimeSpan LoadBalanceTimeout
-        {
-            get { return PoolGroupOptions.LoadBalanceTimeout; }
-        }
-
-        private bool NeedToReplenish
-        {
-            get
-            {
-                if (State.Running != _state) // Don't allow connection create when not running.
-                    return false;
-
-                int totalObjects = Count;
-
-                if (totalObjects >= MaxPoolSize)
-                    return false;
-
-                if (totalObjects < MinPoolSize)
-                    return true;
-
-                int freeObjects = (_stackNew.Count + _stackOld.Count);
-                int waitingRequests = _waitCount;
-                bool needToReplenish = (freeObjects < waitingRequests) || ((freeObjects == waitingRequests) && (totalObjects > 1));
-
-                return needToReplenish;
-            }
-        }
-
-        internal DbConnectionPoolIdentity Identity
-        {
-            get { return _identity; }
-        }
-
-        internal bool IsRunning
-        {
-            get { return State.Running == _state; }
-        }
-
-        private int MaxPoolSize
-        {
-            get { return PoolGroupOptions.MaxPoolSize; }
-        }
-
-        private int MinPoolSize
-        {
-            get { return PoolGroupOptions.MinPoolSize; }
-        }
-
-        internal DbConnectionPoolGroup PoolGroup
-        {
-            get { return _connectionPoolGroup; }
-        }
-
-        internal DbConnectionPoolGroupOptions PoolGroupOptions
-        {
-            get { return _connectionPoolGroupOptions; }
-        }
-
-        internal DbConnectionPoolProviderInfo ProviderInfo
-        {
-            get { return _connectionPoolProviderInfo; }
-        }
-
-        internal bool UseLoadBalancing
-        {
-            get { return PoolGroupOptions.UseLoadBalancing; }
-        }
-
-        private bool UsingIntegrateSecurity
-        {
-            get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); }
-        }
-
-        private void CleanupCallback(object state)
-        {
-            // Called when the cleanup-timer ticks over.
-
-            // This is the automatic pruning method.  Every period, we will
-            // perform a two-step process:
-            //
-            // First, for each free object above MinPoolSize, we will obtain a
-            // semaphore representing one object and destroy one from old stack.
-            // We will continue this until we either reach MinPoolSize, we are
-            // unable to obtain a free object, or we have exhausted all the
-            // objects on the old stack.
-            //
-            // Second we move all free objects on the new stack to the old stack.
-            // So, every period the objects on the old stack are destroyed and
-            // the objects on the new stack are pushed to the old stack.  All
-            // objects that are currently out and in use are not on either stack.
-            //
-            // With this logic, objects are pruned from the pool if unused for
-            // at least one period but not more than two periods.
-
-
-            // Destroy free objects that put us above MinPoolSize from old stack.
-            while (Count > MinPoolSize)
-            { // While above MinPoolSize...
-                if (_waitHandles.PoolSemaphore.WaitOne(0))
-                {
-                    // We obtained a objects from the semaphore.
-                    DbConnectionInternal obj;
-
-                    if (_stackOld.TryPop(out obj))
-                    {
-                        Debug.Assert(obj != null, "null connection is not expected");
-                        // If we obtained one from the old stack, destroy it.
-
-                        // Transaction roots must survive even aging out (TxEnd event will clean them up).
-                        bool shouldDestroy = true;
-                        lock (obj)
-                        {    // Lock to prevent race condition window between IsTransactionRoot and shouldDestroy assignment
-                            if (obj.IsTransactionRoot)
-                            {
-                                shouldDestroy = false;
-                            }
-                        }
-
-                        // !!!!!!!!!! WARNING !!!!!!!!!!!!!
-                        //   ONLY touch obj after lock release if shouldDestroy is false!!!  Otherwise, it may be destroyed
-                        //   by transaction-end thread!
-
-                        // Note that there is a minor race condition between this task and the transaction end event, if the latter runs
-                        //  between the lock above and the SetInStasis call below. The reslult is that the stasis counter may be
-                        //  incremented without a corresponding decrement (the transaction end task is normally expected
-                        //  to decrement, but will only do so if the stasis flag is set when it runs). I've minimized the size
-                        //  of the window, but we aren't totally eliminating it due to SetInStasis needing to do bid tracing, which
-                        //  we don't want to do under this lock, if possible. It should be possible to eliminate this race condition with
-                        //  more substantial re-architecture of the pool, but we don't have the time to do that work for the current release.
-
-                        if (shouldDestroy)
-                        {
-                            DestroyObject(obj);
-                        }
-                        else
-                        {
-                            obj.SetInStasis();
-                        }
-                    }
-                    else
-                    {
-                        // Else we exhausted the old stack (the object the
-                        // semaphore represents is on the new stack), so break.
-                        _waitHandles.PoolSemaphore.Release(1);
-                        break;
-                    }
-                }
-                else
-                {
-                    break;
-                }
-            }
-
-            // Push to the old-stack.  For each free object, move object from
-            // new stack to old stack.
-            if (_waitHandles.PoolSemaphore.WaitOne(0))
-            {
-                while (true)
-                {
-                    DbConnectionInternal obj;
-
-                    if (!_stackNew.TryPop(out obj))
-                        break;
-
-                    Debug.Assert(obj != null, "null connection is not expected");
-                    Debug.Assert(!obj.IsEmancipated, "pooled object not in pool");
-                    Debug.Assert(obj.CanBePooled, "pooled object is not poolable");
-
-                    _stackOld.Push(obj);
-                }
-                _waitHandles.PoolSemaphore.Release(1);
-            }
-
-            // Queue up a request to bring us up to MinPoolSize
-            QueuePoolCreateRequest();
-        }
-
-        internal void Clear()
-        {
-            DbConnectionInternal obj;
-
-            // First, quickly doom everything.
-            lock (_objectList)
-            {
-                int count = _objectList.Count;
-
-                for (int i = 0; i < count; ++i)
-                {
-                    obj = _objectList[i];
-
-                    if (null != obj)
-                    {
-                        obj.DoNotPoolThisConnection();
-                    }
-                }
-            }
-
-            // Second, dispose of all the free connections.
-            while (_stackNew.TryPop(out obj))
-            {
-                Debug.Assert(obj != null, "null connection is not expected");
-                DestroyObject(obj);
-            }
-            while (_stackOld.TryPop(out obj))
-            {
-                Debug.Assert(obj != null, "null connection is not expected");
-                DestroyObject(obj);
-            }
-
-            // Finally, reclaim everything that's emancipated (which, because
-            // it's been doomed, will cause it to be disposed of as well)
-            ReclaimEmancipatedObjects();
-        }
-
-        private Timer CreateCleanupTimer() =>
-            ADP.UnsafeCreateTimer(
-                new TimerCallback(CleanupCallback),
-                null,
-                _cleanupWait,
-                _cleanupWait);
-
-        private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
-        {
-            DbConnectionInternal newObj = null;
-
-            try
-            {
-                newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions);
-                if (null == newObj)
-                {
-                    throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull);    // CreateObject succeeded, but null object
-                }
-                if (!newObj.CanBePooled)
-                {
-                    throw ADP.InternalError(ADP.InternalErrorCode.NewObjectCannotBePooled);        // CreateObject succeeded, but non-poolable object
-                }
-                newObj.PrePush(null);
-
-                lock (_objectList)
-                {
-                    if ((oldConnection != null) && (oldConnection.Pool == this))
-                    {
-                        _objectList.Remove(oldConnection);
-                    }
-                    _objectList.Add(newObj);
-                    _totalObjects = _objectList.Count;
-                }
-
-                // If the old connection belonged to another pool, we need to remove it from that
-                if (oldConnection != null)
-                {
-                    var oldConnectionPool = oldConnection.Pool;
-                    if (oldConnectionPool != null && oldConnectionPool != this)
-                    {
-                        Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down");
-                        lock (oldConnectionPool._objectList)
-                        {
-                            oldConnectionPool._objectList.Remove(oldConnection);
-                            oldConnectionPool._totalObjects = oldConnectionPool._objectList.Count;
-                        }
-                    }
-                }
-
-                // Reset the error wait:
-                _errorWait = ERROR_WAIT_DEFAULT;
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-
-                CheckPoolBlockingPeriod(e);
-
-                newObj = null; // set to null, so we do not return bad new object
-                // Failed to create instance
-                _resError = e;
-
-                // Make sure the timer starts even if ThreadAbort occurs after setting the ErrorEvent.
-
-                // timer allocation has to be done out of CER block
-                Timer t = new Timer(new TimerCallback(this.ErrorCallback), null, Timeout.Infinite, Timeout.Infinite);
-
-                bool timerIsNotDisposed;
-                try { }
-                finally
-                {
-                    _waitHandles.ErrorEvent.Set();
-                    _errorOccurred = true;
-
-                    // Enable the timer.
-                    // Note that the timer is created to allow periodic invocation. If ThreadAbort occurs in the middle of ErrorCallback,
-                    // the timer will restart. Otherwise, the timer callback (ErrorCallback) destroys the timer after resetting the error to avoid second callback.
-                    _errorTimer = t;
-                    timerIsNotDisposed = t.Change(_errorWait, _errorWait);
-                }
-
-                Debug.Assert(timerIsNotDisposed, "ErrorCallback timer has been disposed");
-
-                if (30000 < _errorWait)
-                {
-                    _errorWait = 60000;
-                }
-                else
-                {
-                    _errorWait *= 2;
-                }
-                throw;
-            }
-            return newObj;
-        }
-
-        //This method is implemented in DbConnectionPool.NetCoreApp
-        partial void CheckPoolBlockingPeriod(Exception e);
-
-        private void DeactivateObject(DbConnectionInternal obj)
-        {
-            obj.DeactivateConnection();
-
-            bool returnToGeneralPool = false;
-            bool destroyObject = false;
-            bool rootTxn = false;
-
-            if (obj.IsConnectionDoomed)
-            {
-                // the object is not fit for reuse -- just dispose of it.
-                destroyObject = true;
-            }
-            else
-            {
-                // NOTE: constructor should ensure that current state cannot be State.Initializing, so it can only
-                //   be State.Running or State.ShuttingDown
-                Debug.Assert(_state == State.Running || _state == State.ShuttingDown);
-
-                lock (obj)
-                {
-                    // A connection with a delegated transaction cannot currently
-                    // be returned to a different customer until the transaction
-                    // actually completes, so we send it into Stasis -- the SysTx
-                    // transaction object will ensure that it is owned (not lost),
-                    // and it will be certain to put it back into the pool.
-
-                    if (_state == State.ShuttingDown)
-                    {
-                        if (obj.IsTransactionRoot)
-                        {
-                            // SQLHotfix# 50003503 - connections that are affiliated with a
-                            //   root transaction and that also happen to be in a connection
-                            //   pool that is being shutdown need to be put in stasis so that
-                            //   the root transaction isn't effectively orphaned with no
-                            //   means to promote itself to a full delegated transaction or
-                            //   Commit or Rollback
-                            obj.SetInStasis();
-                            rootTxn = true;
-                        }
-                        else
-                        {
-                            // connection is being closed and the pool has been marked as shutting
-                            //   down, so destroy this object.
-                            destroyObject = true;
-                        }
-                    }
-                    else
-                    {
-                        if (obj.IsNonPoolableTransactionRoot)
-                        {
-                            obj.SetInStasis();
-                            rootTxn = true;
-                        }
-                        else if (obj.CanBePooled)
-                        {
-                            // We must put this connection into the transacted pool
-                            // while inside a lock to prevent a race condition with
-                            // the transaction asynchronously completing on a second
-                            // thread.
-
-                            Transaction transaction = obj.EnlistedTransaction;
-                            if (null != transaction)
-                            {
-                                // NOTE: we're not locking on _state, so it's possible that its
-                                //   value could change between the conditional check and here.
-                                //   Although perhaps not ideal, this is OK because the
-                                //   DelegatedTransactionEnded event will clean up the
-                                //   connection appropriately regardless of the pool state.
-                                Debug.Assert(_transactedConnectionPool != null, "Transacted connection pool was not expected to be null.");
-                                _transactedConnectionPool.PutTransactedObject(transaction, obj);
-                                rootTxn = true;
-                            }
-                            else
-                            {
-                                // return to general pool
-                                returnToGeneralPool = true;
-                            }
-                        }
-                        else
-                        {
-                            if (obj.IsTransactionRoot && !obj.IsConnectionDoomed)
-                            {
-                                // SQLHotfix# 50003503 - if the object cannot be pooled but is a transaction
-                                //   root, then we must have hit one of two race conditions:
-                                //       1) PruneConnectionPoolGroups shutdown the pool and marked this connection
-                                //          as non-poolable while we were processing within this lock
-                                //       2) The LoadBalancingTimeout expired on this connection and marked this
-                                //          connection as DoNotPool.
-                                //
-                                //   This connection needs to be put in stasis so that the root transaction isn't
-                                //   effectively orphaned with no means to promote itself to a full delegated
-                                //   transaction or Commit or Rollback
-                                obj.SetInStasis();
-                                rootTxn = true;
-                            }
-                            else
-                            {
-                                // object is not fit for reuse -- just dispose of it
-                                destroyObject = true;
-                            }
-                        }
-                    }
-                }
-            }
-
-            if (returnToGeneralPool)
-            {
-                // Only push the connection into the general pool if we didn't
-                //   already push it onto the transacted pool, put it into stasis,
-                //   or want to destroy it.
-                Debug.Assert(destroyObject == false);
-                PutNewObject(obj);
-            }
-            else if (destroyObject)
-            {
-                DestroyObject(obj);
-                QueuePoolCreateRequest();
-            }
-
-            //-------------------------------------------------------------------------------------
-            // postcondition
-
-            // ensure that the connection was processed
-            Debug.Assert(rootTxn == true || returnToGeneralPool == true || destroyObject == true);
-        }
-
-        internal void DestroyObject(DbConnectionInternal obj)
-        {
-            // A connection with a delegated transaction cannot be disposed of
-            // until the delegated transaction has actually completed.  Instead,
-            // we simply leave it alone; when the transaction completes, it will
-            // come back through PutObjectFromTransactedPool, which will call us
-            // again.
-            if (!obj.IsTxRootWaitingForTxEnd)
-            {
-                bool removed = false;
-                lock (_objectList)
-                {
-                    removed = _objectList.Remove(obj);
-                    Debug.Assert(removed, "attempt to DestroyObject not in list");
-                    _totalObjects = _objectList.Count;
-                }
-
-                obj.Dispose();
-            }
-        }
-
-        private void ErrorCallback(object state)
-        {
-            _errorOccurred = false;
-            _waitHandles.ErrorEvent.Reset();
-
-            // the error state is cleaned, destroy the timer to avoid periodic invocation
-            Timer t = _errorTimer;
-            _errorTimer = null;
-            if (t != null)
-            {
-                t.Dispose(); // Cancel timer request.
-            }
-        }
-
-
-        private Exception TryCloneCachedException()
-        // Cached exception can be of any type, so is not always cloneable.
-        // This functions clones SqlException
-        // OleDb and Odbc connections are not passing throw this code
-        {
-            if (_resError == null)
-                return null;
-
-            var sqlError = _resError as SqlClient.SqlException;
-            if (sqlError != null)
-                return sqlError.InternalClone();
-
-            return _resError;
-        }
-
-        private void WaitForPendingOpen()
-        {
-            PendingGetConnection next;
-
-            do
-            {
-                bool started = false;
-
-                try
-                {
-                    try { }
-                    finally
-                    {
-                        started = Interlocked.CompareExchange(ref _pendingOpensWaiting, 1, 0) == 0;
-                    }
-
-                    if (!started)
-                    {
-                        return;
-                    }
-
-                    while (_pendingOpens.TryDequeue(out next))
-                    {
-                        if (next.Completion.Task.IsCompleted)
-                        {
-                            continue;
-                        }
-
-                        uint delay;
-                        if (next.DueTime == Timeout.Infinite)
-                        {
-                            delay = unchecked((uint)Timeout.Infinite);
-                        }
-                        else
-                        {
-                            delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0);
-                        }
-
-                        DbConnectionInternal connection = null;
-                        bool timeout = false;
-                        Exception caughtException = null;
-
-                        try
-                        {
-                            bool allowCreate = true;
-                            bool onlyOneCheckConnection = false;
-                            ADP.SetCurrentTransaction(next.Completion.Task.AsyncState as Transactions.Transaction);
-                            timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection);
-                        }
-                        catch (Exception e)
-                        {
-                            caughtException = e;
-                        }
-
-                        if (caughtException != null)
-                        {
-                            next.Completion.TrySetException(caughtException);
-                        }
-                        else if (timeout)
-                        {
-                            next.Completion.TrySetException(ADP.ExceptionWithStackTrace(ADP.PooledOpenTimeout()));
-                        }
-                        else
-                        {
-                            Debug.Assert(connection != null, "connection should never be null in success case");
-                            if (!next.Completion.TrySetResult(connection))
-                            {
-                                // if the completion was cancelled, lets try and get this connection back for the next try
-                                PutObject(connection, next.Owner);
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    if (started)
-                    {
-                        Interlocked.Exchange(ref _pendingOpensWaiting, 0);
-                    }
-                }
-            } while (!_pendingOpens.IsEmpty);
-        }
-
-        internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
-        {
-            uint waitForMultipleObjectsTimeout = 0;
-            bool allowCreate = false;
-
-            if (retry == null)
-            {
-                waitForMultipleObjectsTimeout = (uint)CreationTimeout;
-
-                // Set the wait timeout to INFINITE (-1) if the SQL connection timeout is 0 (== infinite)
-                if (waitForMultipleObjectsTimeout == 0)
-                    waitForMultipleObjectsTimeout = unchecked((uint)Timeout.Infinite);
-
-                allowCreate = true;
-            }
-
-            if (_state != State.Running)
-            {
-                connection = null;
-                return true;
-            }
-
-            bool onlyOneCheckConnection = true;
-            if (TryGetConnection(owningObject, waitForMultipleObjectsTimeout, allowCreate, onlyOneCheckConnection, userOptions, out connection))
-            {
-                return true;
-            }
-            else if (retry == null)
-            {
-                // timed out on a sync call
-                return true;
-            }
-
-            var pendingGetConnection =
-                new PendingGetConnection(
-                    CreationTimeout == 0 ? Timeout.Infinite : ADP.TimerCurrent() + ADP.TimerFromSeconds(CreationTimeout / 1000),
-                    owningObject,
-                    retry,
-                    userOptions);
-            _pendingOpens.Enqueue(pendingGetConnection);
-
-            // it is better to StartNew too many times than not enough
-            if (_pendingOpensWaiting == 0)
-            {
-                Thread waitOpenThread = new Thread(WaitForPendingOpen);
-                waitOpenThread.IsBackground = true;
-                waitOpenThread.Start();
-            }
-
-            connection = null;
-            return false;
-        }
-
-        private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
-        {
-            DbConnectionInternal obj = null;
-            Transaction transaction = null;
-
-            // If automatic transaction enlistment is required, then we try to
-            // get the connection from the transacted connection pool first.
-            if (HasTransactionAffinity)
-            {
-                obj = GetFromTransactedPool(out transaction);
-            }
-
-            if (null == obj)
-            {
-                Interlocked.Increment(ref _waitCount);
-
-                do
-                {
-                    int waitResult = BOGUS_HANDLE;
-                    try
-                    {
-                        try
-                        {
-                        }
-                        finally
-                        {
-                            waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(allowCreate), unchecked((int)waitForMultipleObjectsTimeout));
-                        }
-
-                        // From the WaitAny docs: "If more than one object became signaled during
-                        // the call, this is the array index of the signaled object with the
-                        // smallest index value of all the signaled objects."  This is important
-                        // so that the free object signal will be returned before a creation
-                        // signal.
-
-                        switch (waitResult)
-                        {
-                            case WaitHandle.WaitTimeout:
-                                Interlocked.Decrement(ref _waitCount);
-                                connection = null;
-                                return false;
-
-                            case ERROR_HANDLE:
-                                // Throw the error that PoolCreateRequest stashed.
-                                Interlocked.Decrement(ref _waitCount);
-                                throw TryCloneCachedException();
-
-                            case CREATION_HANDLE:
-                                try
-                                {
-                                    obj = UserCreateRequest(owningObject, userOptions);
-                                }
-                                catch
-                                {
-                                    if (null == obj)
-                                    {
-                                        Interlocked.Decrement(ref _waitCount);
-                                    }
-                                    throw;
-                                }
-                                finally
-                                {
-                                    // Ensure that we release this waiter, regardless
-                                    // of any exceptions that may be thrown.
-                                    if (null != obj)
-                                    {
-                                        Interlocked.Decrement(ref _waitCount);
-                                    }
-                                }
-
-                                if (null == obj)
-                                {
-                                    // If we were not able to create an object, check to see if
-                                    // we reached MaxPoolSize.  If so, we will no longer wait on
-                                    // the CreationHandle, but instead wait for a free object or
-                                    // the timeout.
-                                    if (Count >= MaxPoolSize && 0 != MaxPoolSize)
-                                    {
-                                        if (!ReclaimEmancipatedObjects())
-                                        {
-                                            // modify handle array not to wait on creation mutex anymore
-                                            Debug.Assert(2 == CREATION_HANDLE, "creation handle changed value");
-                                            allowCreate = false;
-                                        }
-                                    }
-                                }
-                                break;
-
-                            case SEMAPHORE_HANDLE:
-                                //
-                                //    guaranteed available inventory
-                                //
-                                Interlocked.Decrement(ref _waitCount);
-                                obj = GetFromGeneralPool();
-
-                                if ((obj != null) && (!obj.IsConnectionAlive()))
-                                {
-                                    DestroyObject(obj);
-                                    obj = null;     // Setting to null in case creating a new object fails
-
-                                    if (onlyOneCheckConnection)
-                                    {
-                                        if (_waitHandles.CreationSemaphore.WaitOne(unchecked((int)waitForMultipleObjectsTimeout)))
-                                        {
-                                            try
-                                            {
-                                                obj = UserCreateRequest(owningObject, userOptions);
-                                            }
-                                            finally
-                                            {
-                                                _waitHandles.CreationSemaphore.Release(1);
-                                            }
-                                        }
-                                        else
-                                        {
-                                            // Timeout waiting for creation semaphore - return null
-                                            connection = null;
-                                            return false;
-                                        }
-                                    }
-                                }
-                                break;
-                            default:
-                                Interlocked.Decrement(ref _waitCount);
-                                throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult);
-                        }
-                    }
-                    finally
-                    {
-                        if (CREATION_HANDLE == waitResult)
-                        {
-                            _waitHandles.CreationSemaphore.Release(1);
-                        }
-                    }
-                } while (null == obj);
-            }
-
-            if (null != obj)
-            {
-                PrepareConnection(owningObject, obj, transaction);
-            }
-
-            connection = obj;
-            return true;
-        }
-
-        private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, Transaction transaction)
-        {
-            lock (obj)
-            {   // Protect against Clear and ReclaimEmancipatedObjects, which call IsEmancipated, which is affected by PrePush and PostPop
-                obj.PostPop(owningObject);
-            }
-            try
-            {
-                obj.ActivateConnection(transaction);
-            }
-            catch
-            {
-                // if Activate throws an exception
-                // put it back in the pool or have it properly disposed of
-                this.PutObject(obj, owningObject);
-                throw;
-            }
-        }
-
-        /// <summary>
-        /// Creates a new connection to replace an existing connection
-        /// </summary>
-        /// <param name="owningObject">Outer connection that currently owns <paramref name="oldConnection"/></param>
-        /// <param name="userOptions">Options used to create the new connection</param>
-        /// <param name="oldConnection">Inner connection that will be replaced</param>
-        /// <returns>A new inner connection that is attached to the <paramref name="owningObject"/></returns>
-        internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
-        {
-            DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection);
-
-            if (newConnection != null)
-            {
-                PrepareConnection(owningObject, newConnection, oldConnection.EnlistedTransaction);
-                oldConnection.PrepareForReplaceConnection();
-                oldConnection.DeactivateConnection();
-                oldConnection.Dispose();
-            }
-
-            return newConnection;
-        }
-
-        private DbConnectionInternal GetFromGeneralPool()
-        {
-            DbConnectionInternal obj = null;
-
-            if (!_stackNew.TryPop(out obj))
-            {
-                if (!_stackOld.TryPop(out obj))
-                {
-                    obj = null;
-                }
-                else
-                {
-                    Debug.Assert(obj != null, "null connection is not expected");
-                }
-            }
-            else
-            {
-                Debug.Assert(obj != null, "null connection is not expected");
-            }
-
-            // When another thread is clearing this pool,
-            // it will remove all connections in this pool which causes the
-            // following assert to fire, which really mucks up stress against
-            //  checked bits.
-
-            if (null != obj)
-            {
-            }
-            return (obj);
-        }
-
-        private DbConnectionInternal GetFromTransactedPool(out Transaction transaction)
-        {
-            transaction = ADP.GetCurrentTransaction();
-            DbConnectionInternal obj = null;
-
-            if (null != transaction && null != _transactedConnectionPool)
-            {
-                obj = _transactedConnectionPool.GetTransactedObject(transaction);
-
-                if (null != obj)
-                {
-                    if (obj.IsTransactionRoot)
-                    {
-                        try
-                        {
-                            obj.IsConnectionAlive(true);
-                        }
-                        catch
-                        {
-                            DestroyObject(obj);
-                            throw;
-                        }
-                    }
-                    else if (!obj.IsConnectionAlive())
-                    {
-                        DestroyObject(obj);
-                        obj = null;
-                    }
-                }
-            }
-            return obj;
-        }
-
-        private void PoolCreateRequest(object state)
-        {
-            // called by pooler to ensure pool requests are currently being satisfied -
-            // creation mutex has not been obtained
-
-            if (State.Running == _state)
-            {
-                // in case WaitForPendingOpen ever failed with no subsequent OpenAsync calls,
-                // start it back up again
-                if (!_pendingOpens.IsEmpty && _pendingOpensWaiting == 0)
-                {
-                    Thread waitOpenThread = new Thread(WaitForPendingOpen);
-                    waitOpenThread.IsBackground = true;
-                    waitOpenThread.Start();
-                }
-
-                // Before creating any new objects, reclaim any released objects that were
-                // not closed.
-                ReclaimEmancipatedObjects();
-
-                if (!ErrorOccurred)
-                {
-                    if (NeedToReplenish)
-                    {
-                        // Check to see if pool was created using integrated security and if so, make
-                        // sure the identity of current user matches that of user that created pool.
-                        // If it doesn't match, do not create any objects on the ThreadPool thread,
-                        // since either Open will fail or we will open a object for this pool that does
-                        // not belong in this pool.  The side effect of this is that if using integrated
-                        // security min pool size cannot be guaranteed.
-                        if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent()))
-                        {
-                            return;
-                        }
-                        int waitResult = BOGUS_HANDLE;
-                        try
-                        {
-                            try { }
-                            finally
-                            {
-                                waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(withCreate: true), CreationTimeout);
-                            }
-                            if (CREATION_HANDLE == waitResult)
-                            {
-                                DbConnectionInternal newObj;
-
-                                // Check ErrorOccurred again after obtaining mutex
-                                if (!ErrorOccurred)
-                                {
-                                    while (NeedToReplenish)
-                                    {
-                                        try
-                                        {
-                                            // Don't specify any user options because there is no outer connection associated with the new connection
-                                            newObj = CreateObject(owningObject: null, userOptions: null, oldConnection: null);
-                                        }
-                                        catch
-                                        {
-                                            // Catch all the exceptions occurring during CreateObject so that they
-                                            // don't emerge as unhandled on the thread pool and don't crash applications
-                                            // The error is handled in CreateObject and surfaced to the caller of the Connection Pool
-                                            // using the ErrorEvent. Hence it is OK to swallow all exceptions here.
-                                            break;
-                                        }
-                                        // We do not need to check error flag here, since we know if
-                                        // CreateObject returned null, we are in error case.
-                                        if (null != newObj)
-                                        {
-                                            PutNewObject(newObj);
-                                        }
-                                        else
-                                        {
-                                            break;
-                                        }
-                                    }
-                                }
-                            }
-                            else if (WaitHandle.WaitTimeout == waitResult)
-                            {
-                                // do not wait forever and potential block this worker thread
-                                // instead wait for a period of time and just requeue to try again
-                                QueuePoolCreateRequest();
-                            }
-                        }
-                        finally
-                        {
-                            if (CREATION_HANDLE == waitResult)
-                            {
-                                // reuse waitResult and ignore its value
-                                _waitHandles.CreationSemaphore.Release(1);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        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");
-
-
-            _stackNew.Push(obj);
-            _waitHandles.PoolSemaphore.Release(1);
-        }
-
-        internal void PutObject(DbConnectionInternal obj, object owningObject)
-        {
-            Debug.Assert(null != obj, "null obj?");
-
-
-            // Once a connection is closing (which is the state that we're in at
-            // this point in time) you cannot delegate a transaction to or enlist
-            // a transaction in it, so we can correctly presume that if there was
-            // not a delegated or enlisted transaction to start with, that there
-            // will not be a delegated or enlisted transaction once we leave the
-            // lock.
-
-            lock (obj)
-            {
-                // Calling PrePush prevents the object from being reclaimed
-                // once we leave the lock, because it sets _pooledCount such
-                // that it won't appear to be out of the pool.  What that
-                // means, is that we're now responsible for this connection:
-                // it won't get reclaimed if we drop the ball somewhere.
-                obj.PrePush(owningObject);
-            }
-
-            DeactivateObject(obj);
-        }
-
-        internal void PutObjectFromTransactedPool(DbConnectionInternal obj)
-        {
-            Debug.Assert(null != obj, "null pooledObject?");
-            Debug.Assert(obj.EnlistedTransaction == null, "pooledObject is still enlisted?");
-
-            // called by the transacted connection pool , once it's removed the
-            // connection from it's list.  We put the connection back in general
-            // circulation.
-
-            // NOTE: there is no locking required here because if we're in this
-            // 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.
-
-            if (_state == State.Running && obj.CanBePooled)
-            {
-                PutNewObject(obj);
-            }
-            else
-            {
-                DestroyObject(obj);
-                QueuePoolCreateRequest();
-            }
-        }
-
-        private void QueuePoolCreateRequest()
-        {
-            if (State.Running == _state)
-            {
-                // Make sure we're at quota by posting a callback to the threadpool.
-                ThreadPool.QueueUserWorkItem(_poolCreateRequest);
-            }
-        }
-
-        private bool ReclaimEmancipatedObjects()
-        {
-            bool emancipatedObjectFound = false;
-
-            List<DbConnectionInternal> reclaimedObjects = new List<DbConnectionInternal>();
-            int count;
-
-            lock (_objectList)
-            {
-                count = _objectList.Count;
-
-                for (int i = 0; i < count; ++i)
-                {
-                    DbConnectionInternal obj = _objectList[i];
-
-                    if (null != obj)
-                    {
-                        bool locked = false;
-
-                        try
-                        {
-                            Monitor.TryEnter(obj, ref locked);
-
-                            if (locked)
-                            { // avoid race condition with PrePush/PostPop and IsEmancipated
-                                if (obj.IsEmancipated)
-                                {
-                                    // Inside the lock, we want to do as little
-                                    // as possible, so we simply mark the object
-                                    // as being in the pool, but hand it off to
-                                    // an out of pool list to be deactivated,
-                                    // etc.
-                                    obj.PrePush(null);
-                                    reclaimedObjects.Add(obj);
-                                }
-                            }
-                        }
-                        finally
-                        {
-                            if (locked)
-                                Monitor.Exit(obj);
-                        }
-                    }
-                }
-            }
-
-            // NOTE: we don't want to call DeactivateObject while we're locked,
-            // because it can make roundtrips to the server and this will block
-            // object creation in the pooler.  Instead, we queue things we need
-            // to do up, and process them outside the lock.
-            count = reclaimedObjects.Count;
-
-            for (int i = 0; i < count; ++i)
-            {
-                DbConnectionInternal obj = reclaimedObjects[i];
-
-                emancipatedObjectFound = true;
-
-                obj.DetachCurrentTransactionIfEnded();
-                DeactivateObject(obj);
-            }
-            return emancipatedObjectFound;
-        }
-
-        internal void Startup()
-        {
-            _cleanupTimer = CreateCleanupTimer();
-            if (NeedToReplenish)
-            {
-                QueuePoolCreateRequest();
-            }
-        }
-
-        internal void Shutdown()
-        {
-            _state = State.ShuttingDown;
-
-            // deactivate timer callbacks
-            Timer t = _cleanupTimer;
-            _cleanupTimer = null;
-            if (null != t)
-            {
-                t.Dispose();
-            }
-        }
-
-        // TransactionEnded merely provides the plumbing for DbConnectionInternal to access the transacted pool
-        //   that is implemented inside DbConnectionPool. This method's counterpart (PutTransactedObject) should
-        //   only be called from DbConnectionPool.DeactivateObject and thus the plumbing to provide access to
-        //   other objects is unnecessary (hence the asymmetry of Ended but no Begin)
-        internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject)
-        {
-            Debug.Assert(null != transaction, "null transaction?");
-            Debug.Assert(null != transactedObject, "null transactedObject?");
-            // Note: connection may still be associated with transaction due to Explicit Unbinding requirement.
-
-            // called by the internal connection when it get's told that the
-            // transaction is completed.  We tell the transacted pool to remove
-            // the connection from it's list, then we put the connection back in
-            // general circulation.
-
-            TransactedConnectionPool transactedConnectionPool = _transactedConnectionPool;
-            if (null != transactedConnectionPool)
-            {
-                transactedConnectionPool.TransactionEnded(transaction, transactedObject);
-            }
-        }
-
-        private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null)
-        {
-            // called by user when they were not able to obtain a free object but
-            // instead obtained creation mutex
-
-            DbConnectionInternal obj = null;
-            if (ErrorOccurred)
-            {
-                throw TryCloneCachedException();
-            }
-            else
-            {
-                if ((oldConnection != null) || (Count < MaxPoolSize) || (0 == MaxPoolSize))
-                {
-                    // If we have an odd number of total objects, reclaim any dead objects.
-                    // If we did not find any objects to reclaim, create a new one.
-                    if ((oldConnection != null) || (Count & 0x1) == 0x1 || !ReclaimEmancipatedObjects())
-                        obj = CreateObject(owningObject, userOptions, oldConnection);
-                }
-                return obj;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs
deleted file mode 100644 (file)
index 4ca4ee1..0000000
+++ /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.
-
-
-
-//------------------------------------------------------------------------------
-
-
-namespace System.Data.ProviderBase
-{
-    internal class DbConnectionPoolGroupProviderInfo
-    {
-        private DbConnectionPoolGroup _poolGroup;
-
-        internal DbConnectionPoolGroup PoolGroup
-        {
-            get
-            {
-                return _poolGroup;
-            }
-            set
-            {
-                _poolGroup = value;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs
deleted file mode 100644 (file)
index e22acbf..0000000
+++ /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.Data.ProviderBase
-{
-    internal partial class DbConnectionPoolIdentity
-    {
-        internal static DbConnectionPoolIdentity GetCurrent()
-        {
-            return GetCurrentManaged();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs
deleted file mode 100644 (file)
index d488fc1..0000000
+++ /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.Data.SqlClient;
-using System.Security.Principal;
-
-namespace System.Data.ProviderBase
-{
-    internal partial class DbConnectionPoolIdentity
-    {
-        private static DbConnectionPoolIdentity s_lastIdentity = null;
-
-        internal static DbConnectionPoolIdentity GetCurrent()
-        {
-            return TdsParserStateObjectFactory.UseManagedSNI ? GetCurrentManaged() : GetCurrentNative();
-        }
-
-        private static DbConnectionPoolIdentity GetCurrentNative()
-        {
-            DbConnectionPoolIdentity current;
-            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
-            {
-                IntPtr token = identity.AccessToken.DangerousGetHandle();
-                SecurityIdentifier user = identity.User;
-                bool isNetwork = user.IsWellKnown(WellKnownSidType.NetworkSid);
-                string sidString = user.Value;
-
-                // Win32NativeMethods.IsTokenRestricted will raise exception if the native call fails
-                bool isRestricted = Win32NativeMethods.IsTokenRestrictedWrapper(token);
-
-                var lastIdentity = s_lastIdentity;
-                if ((lastIdentity != null) && (lastIdentity._sidString == sidString) && (lastIdentity._isRestricted == isRestricted) && (lastIdentity._isNetwork == isNetwork))
-                {
-                    current = lastIdentity;
-                }
-                else
-                {
-                    current = new DbConnectionPoolIdentity(sidString, isRestricted, isNetwork);
-                }
-            }
-            s_lastIdentity = current;
-            return current;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs
deleted file mode 100644 (file)
index afbacc1..0000000
+++ /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.
-
-namespace System.Data.ProviderBase
-{
-    internal sealed partial class DbConnectionPoolIdentity
-    {
-        public static readonly DbConnectionPoolIdentity NoIdentity = new DbConnectionPoolIdentity(string.Empty, false, true);
-
-        private readonly string _sidString;
-        private readonly bool _isRestricted;
-        private readonly bool _isNetwork;
-        private readonly int _hashCode;
-
-        private DbConnectionPoolIdentity(string sidString, bool isRestricted, bool isNetwork)
-        {
-            _sidString = sidString;
-            _isRestricted = isRestricted;
-            _isNetwork = isNetwork;
-            _hashCode = sidString == null ? 0 : sidString.GetHashCode();
-        }
-
-        internal bool IsRestricted
-        {
-            get { return _isRestricted; }
-        }
-
-
-        public override bool Equals(object value)
-        {
-            bool result = ((this == NoIdentity) || (this == value));
-            if (!result && (null != value))
-            {
-                DbConnectionPoolIdentity that = ((DbConnectionPoolIdentity)value);
-                result = ((_sidString == that._sidString) && (_isRestricted == that._isRestricted) && (_isNetwork == that._isNetwork));
-            }
-            return result;
-        }
-
-        public override int GetHashCode()
-        {
-            return _hashCode;
-        }
-
-        internal static DbConnectionPoolIdentity GetCurrentManaged()
-        {
-            string sidString = (!string.IsNullOrWhiteSpace(System.Environment.UserDomainName) ? System.Environment.UserDomainName + "\\" : "")
-                                + System.Environment.UserName;
-            bool isNetwork = false;
-            bool isRestricted = false;
-            return new DbConnectionPoolIdentity(sidString, isRestricted, isNetwork);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs
deleted file mode 100644 (file)
index 1d8705b..0000000
+++ /dev/null
@@ -1,73 +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.Data.ProviderBase
-{
-    internal sealed class DbConnectionPoolGroupOptions
-    {
-        private readonly bool _poolByIdentity;
-        private readonly int _minPoolSize;
-        private readonly int _maxPoolSize;
-        private readonly int _creationTimeout;
-        private readonly TimeSpan _loadBalanceTimeout;
-        private readonly bool _hasTransactionAffinity;
-        private readonly bool _useLoadBalancing;
-
-        public DbConnectionPoolGroupOptions(
-                                        bool poolByIdentity,
-                                        int minPoolSize,
-                                        int maxPoolSize,
-                                        int creationTimeout,
-                                        int loadBalanceTimeout,
-                                        bool hasTransactionAffinity
-        )
-        {
-            _poolByIdentity = poolByIdentity;
-            _minPoolSize = minPoolSize;
-            _maxPoolSize = maxPoolSize;
-            _creationTimeout = creationTimeout;
-
-            if (0 != loadBalanceTimeout)
-            {
-                _loadBalanceTimeout = new TimeSpan(0, 0, loadBalanceTimeout);
-                _useLoadBalancing = true;
-            }
-
-            _hasTransactionAffinity = hasTransactionAffinity;
-        }
-
-        public int CreationTimeout
-        {
-            get { return _creationTimeout; }
-        }
-        public bool HasTransactionAffinity
-        {
-            get { return _hasTransactionAffinity; }
-        }
-        public TimeSpan LoadBalanceTimeout
-        {
-            get { return _loadBalanceTimeout; }
-        }
-        public int MaxPoolSize
-        {
-            get { return _maxPoolSize; }
-        }
-        public int MinPoolSize
-        {
-            get { return _minPoolSize; }
-        }
-        public bool PoolByIdentity
-        {
-            get { return _poolByIdentity; }
-        }
-        public bool UseLoadBalancing
-        {
-            get { return _useLoadBalancing; }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolProviderInfo.cs b/src/libraries/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolProviderInfo.cs
deleted file mode 100644 (file)
index 9a5dce6..0000000
+++ /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.Data.ProviderBase
-{
-    internal class DbConnectionPoolProviderInfo
-    {
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/IBinarySerialize.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/IBinarySerialize.cs
deleted file mode 100644 (file)
index ee9aa74..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.Server
-{
-    // This interface is used by types that want full control over the
-    // binary serialization format.
-    public interface IBinarySerialize
-    {
-        // Read from the specified binary reader.
-        void Read(BinaryReader r);
-        // Write to the specified binary writer.
-        void Write(BinaryWriter w);
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/InvalidUdtException.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/InvalidUdtException.cs
deleted file mode 100644 (file)
index 0f0bbeb..0000000
+++ /dev/null
@@ -1,49 +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.Data.Common;
-using System.Runtime.Serialization;
-
-namespace Microsoft.SqlServer.Server
-{
-    [Serializable]
-    public sealed class InvalidUdtException : SystemException
-    {
-        private const int InvalidUdtHResult = unchecked((int)0x80131937);
-
-        internal InvalidUdtException() : base()
-        {
-            HResult = InvalidUdtHResult;
-        }
-
-        internal InvalidUdtException(string message) : base(message)
-        {
-            HResult = InvalidUdtHResult;
-        }
-
-        internal InvalidUdtException(string message, Exception innerException) : base(message, innerException)
-        {
-            HResult = InvalidUdtHResult;
-        }
-
-        private InvalidUdtException(SerializationInfo si, StreamingContext sc) : base(si, sc)
-        {
-        }
-
-        public override void GetObjectData(SerializationInfo si, StreamingContext context)
-        {
-            base.GetObjectData(si, context);
-        }
-
-        internal static InvalidUdtException Create(Type udtType, string resourceReason)
-        {
-            string reason = SR.GetString(resourceReason);
-            string message = SR.GetString(SR.SqlUdt_InvalidUdtMessage, udtType.FullName, reason);
-            InvalidUdtException e = new InvalidUdtException(message);
-            ADP.TraceExceptionAsReturnValue(e);
-            return e;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlFunctionAttribute.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlFunctionAttribute.cs
deleted file mode 100644 (file)
index 2dc71a5..0000000
+++ /dev/null
@@ -1,89 +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;
-
-namespace Microsoft.SqlServer.Server
-{
-    [Serializable]
-    public enum DataAccessKind
-    {
-        None = 0,
-        Read = 1,
-    }
-
-    [Serializable]
-    public enum SystemDataAccessKind
-    {
-        None = 0,
-        Read = 1,
-    }
-
-    // sql specific attribute
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false), Serializable]
-    public class SqlFunctionAttribute : Attribute
-    {
-        private bool _isDeterministic;
-        private DataAccessKind _dataAccess;
-        private SystemDataAccessKind _systemDataAccess;
-        private bool _isPrecise;
-        private string _name;
-        private string _tableDefinition;
-        private string _fillRowMethodName;
-
-        public SqlFunctionAttribute()
-        {
-            // default values
-            _isDeterministic = false;
-            _dataAccess = DataAccessKind.None;
-            _systemDataAccess = SystemDataAccessKind.None;
-            _isPrecise = false;
-            _name = null;
-            _tableDefinition = null;
-            _fillRowMethodName = null;
-        }
-
-        public bool IsDeterministic
-        {
-            get => _isDeterministic;
-            set => _isDeterministic = value;
-        }
-
-        public DataAccessKind DataAccess
-        {
-            get => _dataAccess;
-            set => _dataAccess = value;
-        }
-
-        public SystemDataAccessKind SystemDataAccess
-        {
-            get => _systemDataAccess;
-            set => _systemDataAccess = value;
-        }
-
-        public bool IsPrecise
-        {
-            get => _isPrecise;
-            set => _isPrecise = value;
-        }
-
-        public string Name
-        {
-            get => _name;
-            set => _name = value;
-        }
-
-        public string TableDefinition
-        {
-            get => _tableDefinition;
-            set => _tableDefinition = value;
-        }
-
-        public string FillRowMethodName
-        {
-            get => _fillRowMethodName;
-            set => _fillRowMethodName = value;
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlMetaData.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlMetaData.cs
deleted file mode 100644 (file)
index d5fb052..0000000
+++ /dev/null
@@ -1,1741 +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.Data;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Globalization;
-using System.Data.SqlTypes;
-using System.Data.SqlClient;
-
-namespace Microsoft.SqlServer.Server
-{
-    // class SqlMetaData
-    //   Simple immutable implementation of the a metadata-holding class.  Only
-    //    complexities are:
-    //        1) enforcing immutability.
-    //        2) Inferring type from a value.
-    //        3) Adjusting a value to match the metadata.
-
-    public sealed partial class SqlMetaData
-    {
-        private string _strName;
-        private long _lMaxLength;
-        private SqlDbType _sqlDbType;
-        private byte _bPrecision;
-        private byte _bScale;
-        private long _lLocale;
-        private SqlCompareOptions _eCompareOptions;
-        private string _xmlSchemaCollectionDatabase;
-        private string _xmlSchemaCollectionOwningSchema;
-        private string _xmlSchemaCollectionName;
-        private string _serverTypeName;
-        private readonly bool _bPartialLength;
-        private Type _udtType;
-        private bool _useServerDefault;
-        private bool _isUniqueKey;
-        private SortOrder _columnSortOrder;
-        private int _sortOrdinal;
-
-        // unlimited (except by implementation) max-length.
-        private const long x_lMax = -1;
-        private const long x_lServerMaxUnicode = 4000;
-        private const long x_lServerMaxANSI = 8000;
-        private const long x_lServerMaxBinary = 8000;
-        private const bool x_defaultUseServerDefault = false;
-        private const bool x_defaultIsUniqueKey = false;
-        private const SortOrder x_defaultColumnSortOrder = SortOrder.Unspecified;
-        private const int x_defaultSortOrdinal = -1;
-
-        private const SqlCompareOptions x_eDefaultStringCompareOptions = SqlCompareOptions.IgnoreCase
-                                        | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
-
-        // scalar types constructor without tvp extended properties
-        public SqlMetaData(string name, SqlDbType dbType)
-        {
-            Construct(name, dbType, x_defaultUseServerDefault,
-                    x_defaultIsUniqueKey, x_defaultColumnSortOrder, x_defaultSortOrdinal);
-        }
-
-        // scalar types constructor
-        public SqlMetaData(string name, SqlDbType dbType, bool useServerDefault,
-                    bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            Construct(name, dbType, useServerDefault,
-                    isUniqueKey, columnSortOrder, sortOrdinal);
-        }
-
-        // binary or string constructor with only max length
-        // (for string types, locale and compare options will be picked up from the thread.
-        public SqlMetaData(string name, SqlDbType dbType, long maxLength)
-        {
-            Construct(name, dbType, maxLength, x_defaultUseServerDefault,
-                    x_defaultIsUniqueKey, x_defaultColumnSortOrder, x_defaultSortOrdinal);
-        }
-
-        // binary or string constructor with only max length and tvp extended properties
-        // (for string types, locale and compare options will be picked up from the thread.
-        public SqlMetaData(string name, SqlDbType dbType, long maxLength, bool useServerDefault,
-                    bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            Construct(name, dbType, maxLength, useServerDefault,
-                    isUniqueKey, columnSortOrder, sortOrdinal);
-        }
-
-        // udt ctor without tvp extended properties
-        public SqlMetaData(string name, SqlDbType dbType, Type userDefinedType)
-        {
-            Construct(name, dbType, userDefinedType, null, x_defaultUseServerDefault,
-                    x_defaultIsUniqueKey, x_defaultColumnSortOrder, x_defaultSortOrdinal);
-        }
-
-        // udt ctor without tvp extended properties
-        public SqlMetaData(string name, SqlDbType dbType, Type userDefinedType, string serverTypeName)
-        {
-            Construct(name, dbType, userDefinedType, serverTypeName, x_defaultUseServerDefault,
-                    x_defaultIsUniqueKey, x_defaultColumnSortOrder, x_defaultSortOrdinal);
-        }
-
-        // udt ctor
-        public SqlMetaData(string name, SqlDbType dbType, Type userDefinedType, string serverTypeName,
-                    bool useServerDefault, bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            Construct(name, dbType, userDefinedType, serverTypeName, useServerDefault,
-                    isUniqueKey, columnSortOrder, sortOrdinal);
-        }
-
-        // decimal ctor without tvp extended properties
-        public SqlMetaData(string name, SqlDbType dbType, byte precision, byte scale)
-        {
-            Construct(name, dbType, precision, scale, x_defaultUseServerDefault,
-                    x_defaultIsUniqueKey, x_defaultColumnSortOrder, x_defaultSortOrdinal);
-        }
-
-        // decimal ctor
-        public SqlMetaData(string name, SqlDbType dbType, byte precision, byte scale, bool useServerDefault,
-                    bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            Construct(name, dbType, precision, scale, useServerDefault,
-                    isUniqueKey, columnSortOrder, sortOrdinal);
-        }
-
-        // string type constructor with locale and compare options, no tvp extended properties
-        public SqlMetaData(string name, SqlDbType dbType, long maxLength, long locale,
-                           SqlCompareOptions compareOptions)
-        {
-            Construct(name, dbType, maxLength, locale, compareOptions, x_defaultUseServerDefault,
-                    x_defaultIsUniqueKey, x_defaultColumnSortOrder, x_defaultSortOrdinal);
-        }
-
-        // string type constructor with locale and compare options
-        public SqlMetaData(string name, SqlDbType dbType, long maxLength, long locale,
-                           SqlCompareOptions compareOptions, bool useServerDefault,
-                           bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            Construct(name, dbType, maxLength, locale, compareOptions, useServerDefault,
-                    isUniqueKey, columnSortOrder, sortOrdinal);
-        }
-
-        // typed xml ctor
-        public SqlMetaData(string name, SqlDbType dbType, string database, string owningSchema,
-                           string objectName, bool useServerDefault, bool isUniqueKey,
-                           SortOrder columnSortOrder, int sortOrdinal)
-        {
-            Construct(name, dbType, database, owningSchema, objectName, useServerDefault,
-                        isUniqueKey, columnSortOrder, sortOrdinal);
-        }
-
-        // everything except xml schema and tvp properties ctor
-        public SqlMetaData(string name, SqlDbType dbType, long maxLength, byte precision,
-                           byte scale, long locale, SqlCompareOptions compareOptions,
-                           Type userDefinedType) :
-                           this(name, dbType, maxLength, precision, scale, locale, compareOptions,
-                                userDefinedType, x_defaultUseServerDefault, x_defaultIsUniqueKey,
-                                x_defaultColumnSortOrder, x_defaultSortOrdinal)
-        {
-        }
-
-        // everything except xml schema ctor
-        public SqlMetaData(string name, SqlDbType dbType, long maxLength, byte precision,
-                           byte scale, long localeId, SqlCompareOptions compareOptions,
-                           Type userDefinedType, bool useServerDefault,
-                           bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            switch (dbType)
-            {
-                case SqlDbType.BigInt:
-                case SqlDbType.Image:
-                case SqlDbType.Timestamp:
-                case SqlDbType.Bit:
-                case SqlDbType.DateTime:
-                case SqlDbType.SmallDateTime:
-                case SqlDbType.Real:
-                case SqlDbType.Int:
-                case SqlDbType.Money:
-                case SqlDbType.SmallMoney:
-                case SqlDbType.Float:
-                case SqlDbType.UniqueIdentifier:
-                case SqlDbType.SmallInt:
-                case SqlDbType.TinyInt:
-                case SqlDbType.Xml:
-                case SqlDbType.Date:
-                    Construct(name, dbType, useServerDefault, isUniqueKey, columnSortOrder, sortOrdinal);
-                    break;
-                case SqlDbType.Binary:
-                case SqlDbType.VarBinary:
-                    Construct(name, dbType, maxLength, useServerDefault, isUniqueKey, columnSortOrder, sortOrdinal);
-                    break;
-                case SqlDbType.Char:
-                case SqlDbType.NChar:
-                case SqlDbType.NVarChar:
-                case SqlDbType.VarChar:
-                    Construct(name, dbType, maxLength, localeId, compareOptions, useServerDefault, isUniqueKey, columnSortOrder, sortOrdinal);
-                    break;
-                case SqlDbType.NText:
-                case SqlDbType.Text:
-                    // We should ignore user's max length and use Max instead to avoid exception
-                    Construct(name, dbType, Max, localeId, compareOptions, useServerDefault, isUniqueKey, columnSortOrder, sortOrdinal);
-                    break;
-                case SqlDbType.Decimal:
-                case SqlDbType.Time:
-                case SqlDbType.DateTime2:
-                case SqlDbType.DateTimeOffset:
-                    Construct(name, dbType, precision, scale, useServerDefault, isUniqueKey, columnSortOrder, sortOrdinal);
-                    break;
-                case SqlDbType.Variant:
-                    Construct(name, dbType, useServerDefault, isUniqueKey, columnSortOrder, sortOrdinal);
-                    break;
-                case SqlDbType.Udt:
-                    Construct(name, dbType, userDefinedType, "", useServerDefault, isUniqueKey, columnSortOrder, sortOrdinal);
-                    break;
-                default:
-                    SQL.InvalidSqlDbTypeForConstructor(dbType);
-                    break;
-            }
-        }
-
-        public SqlMetaData(string name, SqlDbType dbType, string database, string owningSchema, string objectName)
-        {
-            Construct(name, dbType, database, owningSchema, objectName, x_defaultUseServerDefault, x_defaultIsUniqueKey,
-                    x_defaultColumnSortOrder, x_defaultSortOrdinal);
-        }
-
-        // Most general constructor, should be able to initialize all SqlMetaData fields.(Used by SqlParameter)
-        internal SqlMetaData(string name,
-                              SqlDbType sqlDBType,
-                              long maxLength,
-                              byte precision,
-                              byte scale,
-                              long localeId,
-                              SqlCompareOptions compareOptions,
-                              string xmlSchemaCollectionDatabase,
-                              string xmlSchemaCollectionOwningSchema,
-                              string xmlSchemaCollectionName,
-                              bool partialLength,
-                              Type udtType)
-        {
-            AssertNameIsValid(name);
-
-            _strName = name;
-            _sqlDbType = sqlDBType;
-            _lMaxLength = maxLength;
-            _bPrecision = precision;
-            _bScale = scale;
-            _lLocale = localeId;
-            _eCompareOptions = compareOptions;
-            _xmlSchemaCollectionDatabase = xmlSchemaCollectionDatabase;
-            _xmlSchemaCollectionOwningSchema = xmlSchemaCollectionOwningSchema;
-            _xmlSchemaCollectionName = xmlSchemaCollectionName;
-            _bPartialLength = partialLength;
-
-            _udtType = udtType;
-        }
-
-        // Private constructor used to initialize default instance array elements.
-        // DO NOT EXPOSE OUTSIDE THIS CLASS!  It performs no validation.
-        private SqlMetaData(string name,
-                             SqlDbType sqlDbType,
-                             long maxLength,
-                             byte precision,
-                             byte scale,
-                             long localeId,
-                             SqlCompareOptions compareOptions,
-                             bool partialLength)
-        {
-            AssertNameIsValid(name);
-
-            _strName = name;
-            _sqlDbType = sqlDbType;
-            _lMaxLength = maxLength;
-            _bPrecision = precision;
-            _bScale = scale;
-            _lLocale = localeId;
-            _eCompareOptions = compareOptions;
-            _bPartialLength = partialLength;
-            _udtType = null;
-        }
-
-        public SqlCompareOptions CompareOptions
-        {
-            get => _eCompareOptions;
-        }
-
-        public DbType DbType
-        {
-            get => sxm_rgSqlDbTypeToDbType[(int)_sqlDbType];
-        }
-
-        public bool IsUniqueKey
-        {
-            get => _isUniqueKey;
-        }
-
-        public long LocaleId
-        {
-            get => _lLocale;
-        }
-
-        public static long Max
-        {
-            get => x_lMax;
-        }
-
-        public long MaxLength
-        {
-            get => _lMaxLength;
-        }
-
-        public string Name
-        {
-            get => _strName;
-        }
-
-        public byte Precision
-        {
-            get => _bPrecision;
-        }
-
-        public byte Scale
-        {
-            get => _bScale;
-        }
-
-        public SortOrder SortOrder
-        {
-            get => _columnSortOrder;
-        }
-
-        public int SortOrdinal
-        {
-            get => _sortOrdinal;
-        }
-
-        public SqlDbType SqlDbType
-        {
-            get => _sqlDbType;
-        }
-
-        public Type Type
-        {
-            get => _udtType;
-        }
-
-        public string TypeName
-        {
-            get
-            {
-                if (_serverTypeName != null)
-                {
-                    return _serverTypeName;
-                }
-                else if (SqlDbType == SqlDbType.Udt)
-                {
-                    return UdtTypeName;
-                }
-                else
-                {
-                    return sxm_rgDefaults[(int)SqlDbType].Name;
-                }
-            }
-        }
-
-        internal string ServerTypeName
-        {
-            get => _serverTypeName;
-        }
-
-        public bool UseServerDefault
-        {
-            get => _useServerDefault;
-        }
-
-        public string XmlSchemaCollectionDatabase
-        {
-            get => _xmlSchemaCollectionDatabase;
-        }
-
-        public string XmlSchemaCollectionName
-        {
-            get => _xmlSchemaCollectionName;
-        }
-
-        public string XmlSchemaCollectionOwningSchema
-        {
-            get => _xmlSchemaCollectionOwningSchema;
-        }
-
-        internal bool IsPartialLength
-        {
-            get => _bPartialLength;
-        }
-
-        internal string UdtTypeName
-        {
-            get
-            {
-                if (SqlDbType != SqlDbType.Udt)
-                {
-                    return null;
-                }
-                else if (_udtType == null)
-                {
-                    return null;
-                }
-                else
-                {
-                    return _udtType.FullName;
-                }
-            }
-        }
-
-        // Construction for all types that do not have variable attributes
-        private void Construct(string name, SqlDbType dbType, bool useServerDefault,
-                    bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            AssertNameIsValid(name);
-
-            ValidateSortOrder(columnSortOrder, sortOrdinal);
-
-            // Check for absence of explicitly-allowed types to avoid unexpected additions when new types are added
-            if (!(SqlDbType.BigInt == dbType ||
-                    SqlDbType.Bit == dbType ||
-                    SqlDbType.DateTime == dbType ||
-                    SqlDbType.Date == dbType ||
-                    SqlDbType.DateTime2 == dbType ||
-                    SqlDbType.DateTimeOffset == dbType ||
-                    SqlDbType.Decimal == dbType ||
-                    SqlDbType.Float == dbType ||
-                    SqlDbType.Image == dbType ||
-                    SqlDbType.Int == dbType ||
-                    SqlDbType.Money == dbType ||
-                    SqlDbType.NText == dbType ||
-                    SqlDbType.Real == dbType ||
-                    SqlDbType.SmallDateTime == dbType ||
-                    SqlDbType.SmallInt == dbType ||
-                    SqlDbType.SmallMoney == dbType ||
-                    SqlDbType.Text == dbType ||
-                    SqlDbType.Time == dbType ||
-                    SqlDbType.Timestamp == dbType ||
-                    SqlDbType.TinyInt == dbType ||
-                    SqlDbType.UniqueIdentifier == dbType ||
-                    SqlDbType.Variant == dbType ||
-                    SqlDbType.Xml == dbType))
-                throw SQL.InvalidSqlDbTypeForConstructor(dbType);
-
-            SetDefaultsForType(dbType);
-
-            if (SqlDbType.NText == dbType || SqlDbType.Text == dbType)
-            {
-                _lLocale = CultureInfo.CurrentCulture.LCID;
-            }
-
-
-            _strName = name;
-            _useServerDefault = useServerDefault;
-            _isUniqueKey = isUniqueKey;
-            _columnSortOrder = columnSortOrder;
-            _sortOrdinal = sortOrdinal;
-        }
-
-        // Construction for all types that vary by user-specified length (not Udts)
-        private void Construct(string name, SqlDbType dbType, long maxLength, bool useServerDefault,
-                    bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            AssertNameIsValid(name);
-
-            ValidateSortOrder(columnSortOrder, sortOrdinal);
-
-            long lLocale = 0;
-            if (SqlDbType.Char == dbType)
-            {
-                if (maxLength > x_lServerMaxANSI || maxLength < 0)
-                    throw ADP.Argument(SR.GetString(SR.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(SR.GetString(SR.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(SR.GetString(SR.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(SR.GetString(SR.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(SR.GetString(SR.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(SR.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength));
-            }
-            else if (SqlDbType.VarBinary == dbType)
-            {
-                if ((maxLength > x_lServerMaxBinary || maxLength < 0) && maxLength != Max)
-                    throw ADP.Argument(SR.GetString(SR.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(SR.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength));
-            }
-            else
-                throw SQL.InvalidSqlDbTypeForConstructor(dbType);
-
-            SetDefaultsForType(dbType);
-
-            _strName = name;
-            _lMaxLength = maxLength;
-            _lLocale = lLocale;
-            _useServerDefault = useServerDefault;
-            _isUniqueKey = isUniqueKey;
-            _columnSortOrder = columnSortOrder;
-            _sortOrdinal = sortOrdinal;
-        }
-
-        // Construction for string types with specified locale/compare options
-        private void Construct(string name,
-                               SqlDbType dbType,
-                               long maxLength,
-                               long locale,
-                               SqlCompareOptions compareOptions,
-                               bool useServerDefault,
-                               bool isUniqueKey,
-                               SortOrder columnSortOrder,
-                               int sortOrdinal)
-        {
-            AssertNameIsValid(name);
-
-            ValidateSortOrder(columnSortOrder, sortOrdinal);
-
-            // Validate type and max length.
-            if (SqlDbType.Char == dbType)
-            {
-                if (maxLength > x_lServerMaxANSI || maxLength < 0)
-                    throw ADP.Argument(SR.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength));
-            }
-            else if (SqlDbType.VarChar == dbType)
-            {
-                if ((maxLength > x_lServerMaxANSI || maxLength < 0) && maxLength != Max)
-                    throw ADP.Argument(SR.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength));
-            }
-            else if (SqlDbType.NChar == dbType)
-            {
-                if (maxLength > x_lServerMaxUnicode || maxLength < 0)
-                    throw ADP.Argument(SR.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength));
-            }
-            else if (SqlDbType.NVarChar == dbType)
-            {
-                if ((maxLength > x_lServerMaxUnicode || maxLength < 0) && maxLength != Max)
-                    throw ADP.Argument(SR.GetString(SR.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(SR.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength));
-            }
-            else
-                throw SQL.InvalidSqlDbTypeForConstructor(dbType);
-
-            // Validate locale?
-
-            // Validate compare options
-            //    Binary sort must be by itself.
-            //    Nothing else but the Ignore bits is allowed.
-            if (SqlCompareOptions.BinarySort != compareOptions &&
-                    0 != (~((int)SqlCompareOptions.IgnoreCase | (int)SqlCompareOptions.IgnoreNonSpace |
-                            (int)SqlCompareOptions.IgnoreKanaType | (int)SqlCompareOptions.IgnoreWidth) &
-                        (int)compareOptions))
-                throw ADP.InvalidEnumerationValue(typeof(SqlCompareOptions), (int)compareOptions);
-
-            SetDefaultsForType(dbType);
-
-            _strName = name;
-            _lMaxLength = maxLength;
-            _lLocale = locale;
-            _eCompareOptions = compareOptions;
-            _useServerDefault = useServerDefault;
-            _isUniqueKey = isUniqueKey;
-            _columnSortOrder = columnSortOrder;
-            _sortOrdinal = sortOrdinal;
-        }
-
-
-        private static readonly byte[] s_maxLenFromPrecision = new byte[]
-        {
-            5, 5, 5, 5, 5, 5, 5, 5, 5, 9, 9, 9, 9, 9, 9, 9,
-            9, 9, 9, 13, 13, 13, 13, 13, 13, 13, 13, 13, 17,
-            17, 17, 17, 17, 17, 17, 17, 17, 17
-        };
-
-        private const byte MaxTimeScale = 7;
-
-        private static readonly byte[] s_maxVarTimeLenOffsetFromScale = new byte[] { 2, 2, 2, 1, 1, 0, 0, 0 };
-
-        // Construction for Decimal type and new Katmai Date/Time types
-        private void Construct(string name, SqlDbType dbType, byte precision, byte scale, bool useServerDefault,
-                    bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            AssertNameIsValid(name);
-
-            ValidateSortOrder(columnSortOrder, sortOrdinal);
-
-            if (SqlDbType.Decimal == dbType)
-            {
-                if (precision > SqlDecimal.MaxPrecision || scale > precision)
-                    throw SQL.PrecisionValueOutOfRange(precision);
-
-                if (scale > SqlDecimal.MaxScale)
-                    throw SQL.ScaleValueOutOfRange(scale);
-            }
-            else if (SqlDbType.Time == dbType || SqlDbType.DateTime2 == dbType || SqlDbType.DateTimeOffset == dbType)
-            {
-                if (scale > MaxTimeScale)
-                {
-                    throw SQL.TimeScaleValueOutOfRange(scale);
-                }
-            }
-            else
-            {
-                throw SQL.InvalidSqlDbTypeForConstructor(dbType);
-            }
-            SetDefaultsForType(dbType);
-
-            _strName = name;
-            _bPrecision = precision;
-            _bScale = scale;
-            if (SqlDbType.Decimal == dbType)
-            {
-                _lMaxLength = s_maxLenFromPrecision[precision - 1];
-            }
-            else
-            {
-                _lMaxLength -= s_maxVarTimeLenOffsetFromScale[scale];
-            }
-            _useServerDefault = useServerDefault;
-            _isUniqueKey = isUniqueKey;
-            _columnSortOrder = columnSortOrder;
-            _sortOrdinal = sortOrdinal;
-        }
-
-        // Construction for Udt type
-        private void Construct(string name, SqlDbType dbType, Type userDefinedType, string serverTypeName, bool useServerDefault,
-                    bool isUniqueKey, SortOrder columnSortOrder, int sortOrdinal)
-        {
-            AssertNameIsValid(name);
-
-            ValidateSortOrder(columnSortOrder, sortOrdinal);
-
-            if (SqlDbType.Udt != dbType)
-                throw SQL.InvalidSqlDbTypeForConstructor(dbType);
-
-            if (null == userDefinedType)
-                throw ADP.ArgumentNull(nameof(userDefinedType));
-
-            SetDefaultsForType(SqlDbType.Udt);
-
-            _strName = name;
-            _lMaxLength = SerializationHelperSql9.GetUdtMaxLength(userDefinedType);
-            _udtType = userDefinedType;
-            _serverTypeName = serverTypeName;
-            _useServerDefault = useServerDefault;
-            _isUniqueKey = isUniqueKey;
-            _columnSortOrder = columnSortOrder;
-            _sortOrdinal = sortOrdinal;
-        }
-
-        // Construction for Xml type
-        private void Construct(string name, SqlDbType dbType, string database, string owningSchema,
-                    string objectName, bool useServerDefault, bool isUniqueKey, SortOrder columnSortOrder,
-                    int sortOrdinal)
-        {
-            AssertNameIsValid(name);
-
-            ValidateSortOrder(columnSortOrder, sortOrdinal);
-
-            if (SqlDbType.Xml != dbType)
-                throw SQL.InvalidSqlDbTypeForConstructor(dbType);
-
-            if (null != database || null != owningSchema)
-            {
-                if (null == objectName)
-                {
-                    throw ADP.ArgumentNull(nameof(objectName));
-                }
-            }
-
-            SetDefaultsForType(SqlDbType.Xml);
-            _strName = name;
-
-            _xmlSchemaCollectionDatabase = database;
-            _xmlSchemaCollectionOwningSchema = owningSchema;
-            _xmlSchemaCollectionName = objectName;
-            _useServerDefault = useServerDefault;
-            _isUniqueKey = isUniqueKey;
-            _columnSortOrder = columnSortOrder;
-            _sortOrdinal = sortOrdinal;
-        }
-
-        private void AssertNameIsValid(string name)
-        {
-            if (null == name)
-                throw ADP.ArgumentNull(nameof(name));
-
-            if (Microsoft.SqlServer.Server.SmiMetaData.MaxNameLength < name.Length)
-                throw SQL.NameTooLong(nameof(name));
-        }
-
-        private void ValidateSortOrder(SortOrder columnSortOrder, int sortOrdinal)
-        {
-            // Check that sort order is valid enum value.
-            if (SortOrder.Unspecified != columnSortOrder &&
-                    SortOrder.Ascending != columnSortOrder &&
-                    SortOrder.Descending != columnSortOrder)
-            {
-                throw SQL.InvalidSortOrder(columnSortOrder);
-            }
-
-            // Must specify both sort order and ordinal, or neither
-            if ((SortOrder.Unspecified == columnSortOrder) != (x_defaultSortOrdinal == sortOrdinal))
-            {
-                throw SQL.MustSpecifyBothSortOrderAndOrdinal(columnSortOrder, sortOrdinal);
-            }
-        }
-
-
-        public short Adjust(short value)
-        {
-            if (SqlDbType.SmallInt != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public int Adjust(int value)
-        {
-            if (SqlDbType.Int != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public long Adjust(long value)
-        {
-            if (SqlDbType.BigInt != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public float Adjust(float value)
-        {
-            if (SqlDbType.Real != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public double Adjust(double value)
-        {
-            if (SqlDbType.Float != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public string Adjust(string value)
-        {
-            if (SqlDbType.Char == SqlDbType || SqlDbType.NChar == SqlDbType)
-            {
-                // Don't pad null values
-                if (null != value)
-                {
-                    // Pad if necessary
-                    if (value.Length < MaxLength)
-                        value = value.PadRight((int)MaxLength);
-                }
-            }
-            else if (SqlDbType.VarChar != SqlDbType &&
-                     SqlDbType.NVarChar != SqlDbType &&
-                     SqlDbType.Text != SqlDbType &&
-                     SqlDbType.NText != SqlDbType)
-            {
-                ThrowInvalidType();
-            }
-
-            // Handle null values after type check
-            if (null == value)
-            {
-                return null;
-            }
-
-            if (value.Length > MaxLength && Max != MaxLength)
-                value = value.Remove((int)MaxLength, (int)(value.Length - MaxLength));
-
-            return value;
-        }
-
-        public decimal Adjust(decimal value)
-        {
-            if (SqlDbType.Decimal != SqlDbType &&
-                SqlDbType.Money != SqlDbType &&
-                SqlDbType.SmallMoney != SqlDbType)
-            {
-                ThrowInvalidType();
-            }
-
-            if (SqlDbType.Decimal != SqlDbType)
-            {
-                VerifyMoneyRange(new SqlMoney(value));
-                return value;
-            }
-            else
-            {
-                SqlDecimal sdValue = InternalAdjustSqlDecimal(new SqlDecimal(value));
-                return sdValue.Value;
-            }
-        }
-
-        public DateTime Adjust(DateTime value)
-        {
-            if (SqlDbType.DateTime == SqlDbType || SqlDbType.SmallDateTime == SqlDbType)
-            {
-                VerifyDateTimeRange(value);
-            }
-            else if (SqlDbType.DateTime2 == SqlDbType)
-            {
-                return new DateTime(InternalAdjustTimeTicks(value.Ticks));
-            }
-            else if (SqlDbType.Date == SqlDbType)
-            {
-                return value.Date;
-            }
-            else
-            {
-                ThrowInvalidType();
-            }
-            return value;
-        }
-
-        public Guid Adjust(Guid value)
-        {
-            if (SqlDbType.UniqueIdentifier != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlBoolean Adjust(SqlBoolean value)
-        {
-            if (SqlDbType.Bit != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlByte Adjust(SqlByte value)
-        {
-            if (SqlDbType.TinyInt != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlInt16 Adjust(SqlInt16 value)
-        {
-            if (SqlDbType.SmallInt != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlInt32 Adjust(SqlInt32 value)
-        {
-            if (SqlDbType.Int != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlInt64 Adjust(SqlInt64 value)
-        {
-            if (SqlDbType.BigInt != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlSingle Adjust(SqlSingle value)
-        {
-            if (SqlDbType.Real != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlDouble Adjust(SqlDouble value)
-        {
-            if (SqlDbType.Float != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlMoney Adjust(SqlMoney value)
-        {
-            if (SqlDbType.Money != SqlDbType &&
-                SqlDbType.SmallMoney != SqlDbType)
-                ThrowInvalidType();
-
-            if (!value.IsNull)
-                VerifyMoneyRange(value);
-
-            return value;
-        }
-
-        public SqlDateTime Adjust(SqlDateTime value)
-        {
-            if (SqlDbType.DateTime != SqlDbType &&
-                SqlDbType.SmallDateTime != SqlDbType)
-                ThrowInvalidType();
-
-            if (!value.IsNull)
-                VerifyDateTimeRange(value.Value);
-
-            return value;
-        }
-
-        public SqlDecimal Adjust(SqlDecimal value)
-        {
-            if (SqlDbType.Decimal != SqlDbType)
-                ThrowInvalidType();
-            return InternalAdjustSqlDecimal(value);
-        }
-
-        public SqlString Adjust(SqlString value)
-        {
-            if (SqlDbType.Char == SqlDbType || SqlDbType.NChar == SqlDbType)
-            {
-                //DBG.Assert(Max!=MaxLength, "SqlMetaData.Adjust(SqlString): Fixed-length type with Max length!");
-                // Don't pad null values
-                if (!value.IsNull)
-                {
-                    // Pad fixed-length types
-                    if (value.Value.Length < MaxLength)
-                        return new SqlString(value.Value.PadRight((int)MaxLength));
-                }
-            }
-            else if (SqlDbType.VarChar != SqlDbType && SqlDbType.NVarChar != SqlDbType &&
-                    SqlDbType.Text != SqlDbType && SqlDbType.NText != SqlDbType)
-                ThrowInvalidType();
-
-            // Handle null values after type check
-            if (value.IsNull)
-            {
-                return value;
-            }
-
-            // trim all types
-            if (value.Value.Length > MaxLength && Max != MaxLength)
-                value = new SqlString(value.Value.Remove((int)MaxLength, (int)(value.Value.Length - MaxLength)));
-
-            return value;
-        }
-
-        public SqlBinary Adjust(SqlBinary value)
-        {
-            if (SqlDbType.Binary == SqlDbType ||
-                SqlDbType.Timestamp == SqlDbType)
-            {
-                if (!value.IsNull)
-                {
-                    // Pad fixed-length types
-                    if (value.Length < MaxLength)
-                    {
-                        byte[] rgbValue = value.Value;
-                        byte[] rgbNewValue = new byte[MaxLength];
-                        Buffer.BlockCopy(rgbValue, 0, rgbNewValue, 0, rgbValue.Length);
-                        Array.Clear(rgbNewValue, rgbValue.Length, rgbNewValue.Length - rgbValue.Length);
-                        return new SqlBinary(rgbNewValue);
-                    }
-                }
-            }
-            else if (SqlDbType.VarBinary != SqlDbType &&
-                    SqlDbType.Image != SqlDbType)
-                ThrowInvalidType();
-
-            // Handle null values
-            if (value.IsNull)
-            {
-                return value;
-            }
-
-            // trim all types
-            if (value.Length > MaxLength && Max != MaxLength)
-            {
-                byte[] rgbValue = value.Value;
-                byte[] rgbNewValue = new byte[MaxLength];
-                Buffer.BlockCopy(rgbValue, 0, rgbNewValue, 0, (int)MaxLength);
-                value = new SqlBinary(rgbNewValue);
-            }
-
-            return value;
-        }
-
-        public SqlGuid Adjust(SqlGuid value)
-        {
-            if (SqlDbType.UniqueIdentifier != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public SqlChars Adjust(SqlChars value)
-        {
-            if (SqlDbType.Char == SqlDbType || SqlDbType.NChar == SqlDbType)
-            {
-                //DBG.Assert(Max!=MaxLength, "SqlMetaData.Adjust(SqlChars): Fixed-length type with Max length!");
-                // Don't pad null values
-                if (null != value && !value.IsNull)
-                {
-                    // Pad fixed-length types
-                    long oldLength = value.Length;
-                    if (oldLength < MaxLength)
-                    {
-                        // Make sure buffer is long enough
-                        if (value.MaxLength < MaxLength)
-                        {
-                            char[] rgchNew = new char[(int)MaxLength];
-                            Buffer.BlockCopy(value.Buffer, 0, rgchNew, 0, (int)oldLength);
-                            value = new SqlChars(rgchNew);
-                        }
-
-                        // pad extra space
-                        char[] rgchTemp = value.Buffer;
-                        for (long i = oldLength; i < MaxLength; i++)
-                            rgchTemp[i] = ' ';
-
-                        value.SetLength(MaxLength);
-                        return value;
-                    }
-                }
-            }
-            else if (SqlDbType.VarChar != SqlDbType && SqlDbType.NVarChar != SqlDbType &&
-                    SqlDbType.Text != SqlDbType && SqlDbType.NText != SqlDbType)
-                ThrowInvalidType();
-
-            // Handle null values after type check.
-            if (null == value || value.IsNull)
-            {
-                return value;
-            }
-
-            // trim all types
-            if (value.Length > MaxLength && Max != MaxLength)
-                value.SetLength(MaxLength);
-
-            return value;
-        }
-
-        public SqlBytes Adjust(SqlBytes value)
-        {
-            if (SqlDbType.Binary == SqlDbType || SqlDbType.Timestamp == SqlDbType)
-            {
-                //DBG.Assert(Max!=MaxLength, "SqlMetaData.Adjust(SqlBytes): Fixed-length type with Max length!");
-                // Don't pad null values
-                if (null != value && !value.IsNull)
-                {
-                    // Pad fixed-length types
-                    int oldLength = (int)value.Length;
-                    if (oldLength < MaxLength)
-                    {
-                        // Make sure buffer is long enough
-                        if (value.MaxLength < MaxLength)
-                        {
-                            byte[] rgbNew = new byte[MaxLength];
-                            Buffer.BlockCopy(value.Buffer, 0, rgbNew, 0, (int)oldLength);
-                            value = new SqlBytes(rgbNew);
-                        }
-
-                        // pad extra space
-                        byte[] rgbTemp = value.Buffer;
-                        Array.Clear(rgbTemp, oldLength, rgbTemp.Length - oldLength);
-                        value.SetLength(MaxLength);
-                        return value;
-                    }
-                }
-            }
-            else if (SqlDbType.VarBinary != SqlDbType &&
-                     SqlDbType.Image != SqlDbType)
-                ThrowInvalidType();
-
-            // Handle null values after type check.
-            if (null == value || value.IsNull)
-            {
-                return value;
-            }
-
-            // trim all types
-            if (value.Length > MaxLength && Max != MaxLength)
-                value.SetLength(MaxLength);
-
-            return value;
-        }
-
-        public SqlXml Adjust(SqlXml value)
-        {
-            if (SqlDbType.Xml != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public TimeSpan Adjust(TimeSpan value)
-        {
-            if (SqlDbType.Time != SqlDbType)
-                ThrowInvalidType();
-            VerifyTimeRange(value);
-            return new TimeSpan(InternalAdjustTimeTicks(value.Ticks));
-        }
-
-        public DateTimeOffset Adjust(DateTimeOffset value)
-        {
-            if (SqlDbType.DateTimeOffset != SqlDbType)
-                ThrowInvalidType();
-            return new DateTimeOffset(InternalAdjustTimeTicks(value.Ticks), value.Offset);
-        }
-
-        public object Adjust(object value)
-        {
-            // Pass null references through
-            if (null == value)
-                return null;
-
-            Type dataType = value.GetType();
-            switch (Type.GetTypeCode(dataType))
-            {
-                case TypeCode.Boolean: value = this.Adjust((bool)value); break;
-                case TypeCode.Byte: value = this.Adjust((byte)value); break;
-                case TypeCode.Char: value = this.Adjust((char)value); break;
-                case TypeCode.DateTime: value = this.Adjust((DateTime)value); break;
-                case TypeCode.DBNull:    /* DBNull passes through as is for all types */   break;
-                case TypeCode.Decimal: value = this.Adjust((decimal)value); break;
-                case TypeCode.Double: value = this.Adjust((double)value); break;
-                case TypeCode.Empty: throw ADP.InvalidDataType(TypeCode.Empty);
-                case TypeCode.Int16: value = this.Adjust((short)value); break;
-                case TypeCode.Int32: value = this.Adjust((int)value); break;
-                case TypeCode.Int64: value = this.Adjust((long)value); break;
-                case TypeCode.SByte: throw ADP.InvalidDataType(TypeCode.SByte);
-                case TypeCode.Single: value = this.Adjust((float)value); break;
-                case TypeCode.String: value = this.Adjust((string)value); break;
-                case TypeCode.UInt16: throw ADP.InvalidDataType(TypeCode.UInt16);
-                case TypeCode.UInt32: throw ADP.InvalidDataType(TypeCode.UInt32);
-                case TypeCode.UInt64: throw ADP.InvalidDataType(TypeCode.UInt64);
-                case TypeCode.Object:
-                    if (dataType == typeof(byte[]))
-                        value = this.Adjust((byte[])value);
-                    else if (dataType == typeof(char[]))
-                        value = this.Adjust((char[])value);
-                    else if (dataType == typeof(System.Guid))
-                        value = this.Adjust((System.Guid)value);
-                    else if (dataType == typeof(object))
-                    {
-                        throw ADP.InvalidDataType(TypeCode.UInt64);
-                    }
-                    else if (dataType == typeof(SqlBinary))
-                        value = this.Adjust((SqlBinary)value);
-                    else if (dataType == typeof(SqlBoolean))
-                        value = this.Adjust((SqlBoolean)value);
-                    else if (dataType == typeof(SqlByte))
-                        value = this.Adjust((SqlByte)value);
-                    else if (dataType == typeof(SqlDateTime))
-                        value = this.Adjust((SqlDateTime)value);
-                    else if (dataType == typeof(SqlDouble))
-                        value = this.Adjust((SqlDouble)value);
-                    else if (dataType == typeof(SqlGuid))
-                        value = this.Adjust((SqlGuid)value);
-                    else if (dataType == typeof(SqlInt16))
-                        value = this.Adjust((SqlInt16)value);
-                    else if (dataType == typeof(SqlInt32))
-                        value = this.Adjust((SqlInt32)value);
-                    else if (dataType == typeof(SqlInt64))
-                        value = this.Adjust((SqlInt64)value);
-                    else if (dataType == typeof(SqlMoney))
-                        value = this.Adjust((SqlMoney)value);
-                    else if (dataType == typeof(SqlDecimal))
-                        value = this.Adjust((SqlDecimal)value);
-                    else if (dataType == typeof(SqlSingle))
-                        value = this.Adjust((SqlSingle)value);
-                    else if (dataType == typeof(SqlString))
-                        value = this.Adjust((SqlString)value);
-                    else if (dataType == typeof(SqlChars))
-                        value = this.Adjust((SqlChars)value);
-                    else if (dataType == typeof(SqlBytes))
-                        value = this.Adjust((SqlBytes)value);
-                    else if (dataType == typeof(SqlXml))
-                        value = this.Adjust((SqlXml)value);
-                    else if (dataType == typeof(TimeSpan))
-                        value = this.Adjust((TimeSpan)value);
-                    else if (dataType == typeof(DateTimeOffset))
-                        value = this.Adjust((DateTimeOffset)value);
-                    else
-                    {
-                        // Handle UDTs?
-                        throw ADP.UnknownDataType(dataType);
-                    }
-                    break;
-
-
-                default: throw ADP.UnknownDataTypeCode(dataType, Type.GetTypeCode(dataType));
-            }
-
-            return value;
-        }
-
-        public static SqlMetaData InferFromValue(object value, string name)
-        {
-            if (value == null)
-                throw ADP.ArgumentNull(nameof(value));
-            SqlMetaData smd = null;
-            Type dataType = value.GetType();
-            switch (Type.GetTypeCode(dataType))
-            {
-                case TypeCode.Boolean: smd = new SqlMetaData(name, SqlDbType.Bit); break;
-                case TypeCode.Byte: smd = new SqlMetaData(name, SqlDbType.TinyInt); break;
-                case TypeCode.Char: smd = new SqlMetaData(name, SqlDbType.NVarChar, 1); break;
-                case TypeCode.DateTime: smd = new SqlMetaData(name, SqlDbType.DateTime); break;
-                case TypeCode.DBNull: throw ADP.InvalidDataType(TypeCode.DBNull);
-                case TypeCode.Decimal:
-                    {  // Add brackets in order to contain scope declare local variable "sd"
-                       // use logic inside SqlDecimal to infer precision and scale.
-                        SqlDecimal sd = new SqlDecimal((decimal)value);
-                        smd = new SqlMetaData(name, SqlDbType.Decimal, sd.Precision, sd.Scale);
-                    }
-                    break;
-                case TypeCode.Double: smd = new SqlMetaData(name, SqlDbType.Float); break;
-                case TypeCode.Empty: throw ADP.InvalidDataType(TypeCode.Empty);
-                case TypeCode.Int16: smd = new SqlMetaData(name, SqlDbType.SmallInt); break;
-                case TypeCode.Int32: smd = new SqlMetaData(name, SqlDbType.Int); break;
-                case TypeCode.Int64: smd = new SqlMetaData(name, SqlDbType.BigInt); break;
-                case TypeCode.SByte: throw ADP.InvalidDataType(TypeCode.SByte);
-                case TypeCode.Single: smd = new SqlMetaData(name, SqlDbType.Real); break;
-                case TypeCode.String:
-                    {
-                        long maxLen = ((string)value).Length;
-                        if (maxLen < 1) maxLen = 1;
-
-                        if (x_lServerMaxUnicode < maxLen)
-                            maxLen = Max;
-
-                        smd = new SqlMetaData(name, SqlDbType.NVarChar, maxLen);
-                    }
-                    break;
-                case TypeCode.UInt16: throw ADP.InvalidDataType(TypeCode.UInt16);
-                case TypeCode.UInt32: throw ADP.InvalidDataType(TypeCode.UInt32);
-                case TypeCode.UInt64: throw ADP.InvalidDataType(TypeCode.UInt64);
-                case TypeCode.Object:
-                    if (dataType == typeof(byte[]))
-                    {
-                        long maxLen = ((byte[])value).Length;
-                        if (maxLen < 1) maxLen = 1;
-
-                        if (x_lServerMaxBinary < maxLen)
-                            maxLen = Max;
-
-                        smd = new SqlMetaData(name, SqlDbType.VarBinary, maxLen);
-                    }
-                    else if (dataType == typeof(char[]))
-                    {
-                        long maxLen = ((char[])value).Length;
-                        if (maxLen < 1) maxLen = 1;
-
-                        if (x_lServerMaxUnicode < maxLen)
-                            maxLen = Max;
-
-                        smd = new SqlMetaData(name, SqlDbType.NVarChar, maxLen);
-                    }
-                    else if (dataType == typeof(System.Guid))
-                        smd = new SqlMetaData(name, SqlDbType.UniqueIdentifier);
-                    else if (dataType == typeof(object))
-                        smd = new SqlMetaData(name, SqlDbType.Variant);
-                    else if (dataType == typeof(SqlBinary))
-                    {
-                        long maxLen;
-                        SqlBinary sb = ((SqlBinary)value);
-                        if (!sb.IsNull)
-                        {
-                            maxLen = sb.Length;
-                            if (maxLen < 1) maxLen = 1;
-
-                            if (x_lServerMaxBinary < maxLen)
-                                maxLen = Max;
-                        }
-                        else
-                            maxLen = sxm_rgDefaults[(int)SqlDbType.VarBinary].MaxLength;
-
-                        smd = new SqlMetaData(name, SqlDbType.VarBinary, maxLen);
-                    }
-                    else if (dataType == typeof(SqlBoolean))
-                        smd = new SqlMetaData(name, SqlDbType.Bit);
-                    else if (dataType == typeof(SqlByte))
-                        smd = new SqlMetaData(name, SqlDbType.TinyInt);
-                    else if (dataType == typeof(SqlDateTime))
-                        smd = new SqlMetaData(name, SqlDbType.DateTime);
-                    else if (dataType == typeof(SqlDouble))
-                        smd = new SqlMetaData(name, SqlDbType.Float);
-                    else if (dataType == typeof(SqlGuid))
-                        smd = new SqlMetaData(name, SqlDbType.UniqueIdentifier);
-                    else if (dataType == typeof(SqlInt16))
-                        smd = new SqlMetaData(name, SqlDbType.SmallInt);
-                    else if (dataType == typeof(SqlInt32))
-                        smd = new SqlMetaData(name, SqlDbType.Int);
-                    else if (dataType == typeof(SqlInt64))
-                        smd = new SqlMetaData(name, SqlDbType.BigInt);
-                    else if (dataType == typeof(SqlMoney))
-                        smd = new SqlMetaData(name, SqlDbType.Money);
-                    else if (dataType == typeof(SqlDecimal))
-                    {
-                        byte bPrec;
-                        byte scale;
-                        SqlDecimal sd = (SqlDecimal)value;
-                        if (!sd.IsNull)
-                        {
-                            bPrec = sd.Precision;
-                            scale = sd.Scale;
-                        }
-                        else
-                        {
-                            bPrec = sxm_rgDefaults[(int)SqlDbType.Decimal].Precision;
-                            scale = sxm_rgDefaults[(int)SqlDbType.Decimal].Scale;
-                        }
-                        smd = new SqlMetaData(name, SqlDbType.Decimal, bPrec, scale);
-                    }
-                    else if (dataType == typeof(SqlSingle))
-                        smd = new SqlMetaData(name, SqlDbType.Real);
-                    else if (dataType == typeof(SqlString))
-                    {
-                        SqlString ss = (SqlString)value;
-                        if (!ss.IsNull)
-                        {
-                            long maxLen = ss.Value.Length;
-                            if (maxLen < 1) maxLen = 1;
-
-                            if (maxLen > x_lServerMaxUnicode)
-                                maxLen = Max;
-
-                            smd = new SqlMetaData(name, SqlDbType.NVarChar, maxLen, ss.LCID, ss.SqlCompareOptions);
-                        }
-                        else
-                        {
-                            smd = new SqlMetaData(name, SqlDbType.NVarChar, sxm_rgDefaults[(int)SqlDbType.NVarChar].MaxLength);
-                        }
-                    }
-                    else if (dataType == typeof(SqlChars))
-                    {
-                        long maxLen;
-                        SqlChars sch = (SqlChars)value;
-                        if (!sch.IsNull)
-                        {
-                            maxLen = sch.Length;
-                            if (maxLen < 1) maxLen = 1;
-
-                            if (maxLen > x_lServerMaxUnicode)
-                                maxLen = Max;
-                        }
-                        else
-                            maxLen = sxm_rgDefaults[(int)SqlDbType.NVarChar].MaxLength;
-
-                        smd = new SqlMetaData(name, SqlDbType.NVarChar, maxLen);
-                    }
-                    else if (dataType == typeof(SqlBytes))
-                    {
-                        long maxLen;
-                        SqlBytes sb = (SqlBytes)value;
-                        if (!sb.IsNull)
-                        {
-                            maxLen = sb.Length;
-                            if (maxLen < 1) maxLen = 1;
-                            else if (x_lServerMaxBinary < maxLen) maxLen = Max;
-                        }
-                        else
-                            maxLen = sxm_rgDefaults[(int)SqlDbType.VarBinary].MaxLength;
-
-                        smd = new SqlMetaData(name, SqlDbType.VarBinary, maxLen);
-                    }
-                    else if (dataType == typeof(SqlXml))
-                        smd = new SqlMetaData(name, SqlDbType.Xml);
-                    else if (dataType == typeof(TimeSpan))
-                        smd = new SqlMetaData(name, SqlDbType.Time, 0, InferScaleFromTimeTicks(((TimeSpan)value).Ticks));
-                    else if (dataType == typeof(DateTimeOffset))
-                        smd = new SqlMetaData(name, SqlDbType.DateTimeOffset, 0, InferScaleFromTimeTicks(((DateTimeOffset)value).Ticks));
-                    else
-                        throw ADP.UnknownDataType(dataType);
-                    break;
-
-
-                default: throw ADP.UnknownDataTypeCode(dataType, Type.GetTypeCode(dataType));
-            }
-
-            return smd;
-        }
-
-        public bool Adjust(bool value)
-        {
-            if (SqlDbType.Bit != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public byte Adjust(byte value)
-        {
-            if (SqlDbType.TinyInt != SqlDbType)
-                ThrowInvalidType();
-            return value;
-        }
-
-        public byte[] Adjust(byte[] value)
-        {
-            if (SqlDbType.Binary == SqlDbType || SqlDbType.Timestamp == SqlDbType)
-            {
-                // Don't pad null values
-                if (null != value)
-                {
-                    // Pad fixed-length types
-                    if (value.Length < MaxLength)
-                    {
-                        byte[] rgbNewValue = new byte[MaxLength];
-                        Buffer.BlockCopy(value, 0, rgbNewValue, 0, value.Length);
-                        Array.Clear(rgbNewValue, value.Length, (int)rgbNewValue.Length - value.Length);
-                        return rgbNewValue;
-                    }
-                }
-            }
-            else if (SqlDbType.VarBinary != SqlDbType &&
-                    SqlDbType.Image != SqlDbType)
-                ThrowInvalidType();
-
-            // Handle null values after type check
-            if (null == value)
-            {
-                return null;
-            }
-
-            // trim all types
-            if (value.Length > MaxLength && Max != MaxLength)
-            {
-                byte[] rgbNewValue = new byte[MaxLength];
-                Buffer.BlockCopy(value, 0, rgbNewValue, 0, (int)MaxLength);
-                value = rgbNewValue;
-            }
-
-            return value;
-        }
-
-        public char Adjust(char value)
-        {
-            if (SqlDbType.Char == SqlDbType || SqlDbType.NChar == SqlDbType)
-            {
-                if (1 != MaxLength)
-                    ThrowInvalidType();
-            }
-            else if ((1 > MaxLength) ||  // char must have max length of at least 1
-                    (SqlDbType.VarChar != SqlDbType && SqlDbType.NVarChar != SqlDbType &&
-                    SqlDbType.Text != SqlDbType && SqlDbType.NText != SqlDbType)
-                    )
-                ThrowInvalidType();
-
-            return value;
-        }
-
-        public char[] Adjust(char[] value)
-        {
-            if (SqlDbType.Char == SqlDbType || SqlDbType.NChar == SqlDbType)
-            {
-                // Don't pad null values
-                if (null != value)
-                {
-                    // Pad fixed-length types
-                    long oldLength = value.Length;
-                    if (oldLength < MaxLength)
-                    {
-                        char[] rgchNew = new char[(int)MaxLength];
-                        Buffer.BlockCopy(value, 0, rgchNew, 0, (int)oldLength);
-
-                        // pad extra space
-                        for (long i = oldLength; i < rgchNew.Length; i++)
-                            rgchNew[i] = ' ';
-
-                        return rgchNew;
-                    }
-                }
-            }
-            else if (SqlDbType.VarChar != SqlDbType && SqlDbType.NVarChar != SqlDbType &&
-                    SqlDbType.Text != SqlDbType && SqlDbType.NText != SqlDbType)
-                ThrowInvalidType();
-
-            // Handle null values after type check
-            if (null == value)
-            {
-                return null;
-            }
-
-            // trim all types
-            if (value.Length > MaxLength && Max != MaxLength)
-            {
-                char[] rgchNewValue = new char[MaxLength];
-                Buffer.BlockCopy(value, 0, rgchNewValue, 0, (int)MaxLength);
-                value = rgchNewValue;
-            }
-
-
-            return value;
-        }
-
-
-        internal static SqlMetaData GetPartialLengthMetaData(SqlMetaData md)
-        {
-            if (md.IsPartialLength == true)
-            {
-                return md;
-            }
-            if (md.SqlDbType == SqlDbType.Xml)
-                ThrowInvalidType();     //Xml should always have IsPartialLength = true
-
-            if (md.SqlDbType == SqlDbType.NVarChar || md.SqlDbType == SqlDbType.VarChar ||
-                    md.SqlDbType == SqlDbType.VarBinary)
-            {
-                SqlMetaData mdnew = new SqlMetaData(md.Name, md.SqlDbType, SqlMetaData.Max, 0, 0, md.LocaleId,
-                    md.CompareOptions, null, null, null, true, md.Type);
-                return mdnew;
-            }
-            else
-                return md;
-        }
-
-
-        private static void ThrowInvalidType()
-        {
-            throw ADP.InvalidMetaDataValue();
-        }
-
-        // Hard coding smalldatetime limits...
-        private static readonly DateTime s_dtSmallMax = new DateTime(2079, 06, 06, 23, 59, 29, 998);
-        private static readonly DateTime s_dtSmallMin = new DateTime(1899, 12, 31, 23, 59, 29, 999);
-        private void VerifyDateTimeRange(DateTime value)
-        {
-            if (SqlDbType.SmallDateTime == SqlDbType && (s_dtSmallMax < value || s_dtSmallMin > value))
-                ThrowInvalidType();
-        }
-
-        private static readonly SqlMoney s_smSmallMax = new SqlMoney(((decimal)int.MaxValue) / 10000);
-        private static readonly SqlMoney s_smSmallMin = new SqlMoney(((decimal)int.MinValue) / 10000);
-        private void VerifyMoneyRange(SqlMoney value)
-        {
-            if (SqlDbType.SmallMoney == SqlDbType && ((s_smSmallMax < value).Value || (s_smSmallMin > value).Value))
-                ThrowInvalidType();
-        }
-
-        private SqlDecimal InternalAdjustSqlDecimal(SqlDecimal value)
-        {
-            if (!value.IsNull && (value.Precision != Precision || value.Scale != Scale))
-            {
-                // Force truncation if target scale is smaller than actual scale.
-                if (value.Scale != Scale)
-                {
-                    value = SqlDecimal.AdjustScale(value, Scale - value.Scale, false /* Don't round, truncate. */);
-                }
-                return SqlDecimal.ConvertToPrecScale(value, Precision, Scale);
-            }
-
-            return value;
-        }
-
-        private static readonly TimeSpan s_timeMin = TimeSpan.Zero;
-        private static readonly TimeSpan s_timeMax = new TimeSpan(TimeSpan.TicksPerDay - 1);
-        private void VerifyTimeRange(TimeSpan value)
-        {
-            if (SqlDbType.Time == SqlDbType && (s_timeMin > value || value > s_timeMax))
-            {
-                ThrowInvalidType();
-            }
-        }
-
-        private static readonly long[] s_unitTicksFromScale = {
-            10000000,
-            1000000,
-            100000,
-            10000,
-            1000,
-            100,
-            10,
-            1,
-        };
-
-        private long InternalAdjustTimeTicks(long ticks)
-        {
-            return (ticks / s_unitTicksFromScale[Scale] * s_unitTicksFromScale[Scale]);
-        }
-
-        private static byte InferScaleFromTimeTicks(long ticks)
-        {
-            for (byte scale = 0; scale < MaxTimeScale; ++scale)
-            {
-                if ((ticks / s_unitTicksFromScale[scale] * s_unitTicksFromScale[scale]) == ticks)
-                {
-                    return scale;
-                }
-            }
-            return MaxTimeScale;
-        }
-
-        private static readonly DbType[] sxm_rgSqlDbTypeToDbType = {
-            DbType.Int64,           // SqlDbType.BigInt
-            DbType.Binary,          // SqlDbType.Binary
-            DbType.Boolean,         // SqlDbType.Bit
-            DbType.AnsiString,      // SqlDbType.Char
-            DbType.DateTime,        // SqlDbType.DateTime
-            DbType.Decimal,         // SqlDbType.Decimal
-            DbType.Double,          // SqlDbType.Float
-            DbType.Binary,          // SqlDbType.Image
-            DbType.Int32,           // SqlDbType.Int
-            DbType.Currency,        // SqlDbType.Money
-            DbType.String,          // SqlDbType.NChar
-            DbType.String,          // SqlDbType.NText
-            DbType.String,          // SqlDbType.NVarChar
-            DbType.Single,          // SqlDbType.Real
-            DbType.Guid,            // SqlDbType.UniqueIdentifier
-            DbType.DateTime,        // SqlDbType.SmallDateTime
-            DbType.Int16,           // SqlDbType.SmallInt
-            DbType.Currency,        // SqlDbType.SmallMoney
-            DbType.AnsiString,      // SqlDbType.Text
-            DbType.Binary,          // SqlDbType.Timestamp
-            DbType.Byte,            // SqlDbType.TinyInt
-            DbType.Binary,          // SqlDbType.VarBinary
-            DbType.AnsiString,      // SqlDbType.VarChar
-            DbType.Object,          // SqlDbType.Variant
-            DbType.Object,          // SqlDbType.Row
-            DbType.Xml,             // SqlDbType.Xml
-            DbType.String,          // SqlDbType.NVarChar, place holder
-            DbType.String,          // SqlDbType.NVarChar, place holder
-            DbType.String,          // SqlDbType.NVarChar, place holder
-            DbType.Object,          // SqlDbType.Udt
-            DbType.Object,          // SqlDbType.Structured
-            DbType.Date,            // SqlDbType.Date
-            DbType.Time,            // SqlDbType.Time
-            DbType.DateTime2,       // SqlDbType.DateTime2
-            DbType.DateTimeOffset   // SqlDbType.DateTimeOffset
-        };
-
-        private void SetDefaultsForType(SqlDbType dbType)
-        {
-            if (SqlDbType.BigInt <= dbType && SqlDbType.DateTimeOffset >= dbType)
-            {
-                SqlMetaData smdDflt = sxm_rgDefaults[(int)dbType];
-                _sqlDbType = dbType;
-                _lMaxLength = smdDflt.MaxLength;
-                _bPrecision = smdDflt.Precision;
-                _bScale = smdDflt.Scale;
-                _lLocale = smdDflt.LocaleId;
-                _eCompareOptions = smdDflt.CompareOptions;
-            }
-        }
-
-        // Array of default-valued metadata ordered by corresponding SqlDbType.
-        internal static SqlMetaData[] sxm_rgDefaults =
-            {
-            //    new SqlMetaData(name, DbType, SqlDbType, MaxLen, Prec, Scale, Locale, DatabaseName, SchemaName, isPartialLength)
-            new SqlMetaData("bigint", SqlDbType.BigInt,
-                    8, 19, 0, 0, SqlCompareOptions.None,  false),            // SqlDbType.BigInt
-            new SqlMetaData("binary", SqlDbType.Binary,
-                    1, 0, 0, 0, SqlCompareOptions.None,  false),                // SqlDbType.Binary
-            new SqlMetaData("bit", SqlDbType.Bit,
-                    1, 1, 0, 0, SqlCompareOptions.None, false),                // SqlDbType.Bit
-            new SqlMetaData("char", SqlDbType.Char,
-                    1, 0, 0, 0, x_eDefaultStringCompareOptions,  false),                // SqlDbType.Char
-            new SqlMetaData("datetime", SqlDbType.DateTime,
-                    8, 23, 3, 0, SqlCompareOptions.None, false),            // SqlDbType.DateTime
-            new SqlMetaData("decimal", SqlDbType.Decimal,
-                    9, 18, 0, 0, SqlCompareOptions.None,  false),            // SqlDbType.Decimal
-            new SqlMetaData("float", SqlDbType.Float,
-                    8, 53, 0, 0, SqlCompareOptions.None, false),            // SqlDbType.Float
-            new SqlMetaData("image", SqlDbType.Image,
-                    x_lMax, 0, 0, 0, SqlCompareOptions.None, false),                // SqlDbType.Image
-            new SqlMetaData("int", SqlDbType.Int,
-                    4, 10, 0, 0, SqlCompareOptions.None, false),            // SqlDbType.Int
-            new SqlMetaData("money", SqlDbType.Money,
-                    8, 19, 4, 0, SqlCompareOptions.None, false),            // SqlDbType.Money
-            new SqlMetaData("nchar", SqlDbType.NChar,
-                    1, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // SqlDbType.NChar
-            new SqlMetaData("ntext", SqlDbType.NText,
-                    x_lMax, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // SqlDbType.NText
-            new SqlMetaData("nvarchar", SqlDbType.NVarChar,
-                    x_lServerMaxUnicode, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // SqlDbType.NVarChar
-            new SqlMetaData("real", SqlDbType.Real,
-                    4, 24, 0, 0, SqlCompareOptions.None, false),            // SqlDbType.Real
-            new SqlMetaData("uniqueidentifier", SqlDbType.UniqueIdentifier,
-                    16, 0, 0, 0, SqlCompareOptions.None, false),            // SqlDbType.UniqueIdentifier
-            new SqlMetaData("smalldatetime", SqlDbType.SmallDateTime,
-                    4, 16, 0, 0, SqlCompareOptions.None, false),            // SqlDbType.SmallDateTime
-            new SqlMetaData("smallint", SqlDbType.SmallInt,
-                    2, 5, 0, 0, SqlCompareOptions.None, false),                                    // SqlDbType.SmallInt
-            new SqlMetaData("smallmoney", SqlDbType.SmallMoney,
-                    4, 10, 4, 0, SqlCompareOptions.None, false),                // SqlDbType.SmallMoney
-            new SqlMetaData("text", SqlDbType.Text,
-                    x_lMax, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // SqlDbType.Text
-            new SqlMetaData("timestamp", SqlDbType.Timestamp,
-                    8, 0, 0, 0, SqlCompareOptions.None, false),                // SqlDbType.Timestamp
-            new SqlMetaData("tinyint", SqlDbType.TinyInt,
-                    1, 3, 0, 0, SqlCompareOptions.None, false),                // SqlDbType.TinyInt
-            new SqlMetaData("varbinary", SqlDbType.VarBinary,
-                    x_lServerMaxBinary, 0, 0, 0, SqlCompareOptions.None, false),                // SqlDbType.VarBinary
-            new SqlMetaData("varchar", SqlDbType.VarChar,
-                    x_lServerMaxANSI, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // SqlDbType.VarChar
-            new SqlMetaData("sql_variant", SqlDbType.Variant,
-                    8016, 0, 0, 0, SqlCompareOptions.None, false),            // SqlDbType.Variant
-            new SqlMetaData("nvarchar", SqlDbType.NVarChar,
-                    1, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // Placeholder for value 24
-            new SqlMetaData("xml", SqlDbType.Xml,
-                    x_lMax, 0, 0, 0, x_eDefaultStringCompareOptions, true),                // SqlDbType.Xml
-            new SqlMetaData("nvarchar", SqlDbType.NVarChar,
-                    1, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // Placeholder for value 26
-            new SqlMetaData("nvarchar", SqlDbType.NVarChar,
-                    x_lServerMaxUnicode, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // Placeholder for value 27
-            new SqlMetaData("nvarchar", SqlDbType.NVarChar,
-                    x_lServerMaxUnicode, 0, 0, 0, x_eDefaultStringCompareOptions, false),                // Placeholder for value 28
-            new SqlMetaData("udt", SqlDbType.Udt,
-                    0, 0, 0, 0, SqlCompareOptions.None, false),            // SqlDbType.Udt = 29
-            new SqlMetaData("table", SqlDbType.Structured,
-                    0, 0, 0, 0, SqlCompareOptions.None, false),                // SqlDbType.Structured
-            new SqlMetaData("date", SqlDbType.Date,
-                    3, 10, 0, 0, SqlCompareOptions.None, false),                // SqlDbType.Date
-            new SqlMetaData("time", SqlDbType.Time,
-                    5, 0, 7, 0, SqlCompareOptions.None, false),                // SqlDbType.Time
-            new SqlMetaData("datetime2", SqlDbType.DateTime2,
-                    8, 0, 7, 0, SqlCompareOptions.None, false),                // SqlDbType.DateTime2
-            new SqlMetaData("datetimeoffset", SqlDbType.DateTimeOffset,
-                   10, 0, 7, 0, SqlCompareOptions.None, false),                // SqlDbType.DateTimeOffset
-            };
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlMethodAttribute.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlMethodAttribute.cs
deleted file mode 100644 (file)
index 7deebbc..0000000
+++ /dev/null
@@ -1,42 +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;
-
-namespace Microsoft.SqlServer.Server
-{
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false), Serializable]
-    public sealed class SqlMethodAttribute : SqlFunctionAttribute
-    {
-        private bool _isCalledOnNullInputs;
-        private bool _isMutator;
-        private bool _shouldInvokeIfReceiverIsNull;
-
-        public SqlMethodAttribute()
-        {
-            // default values
-            _isCalledOnNullInputs = true;
-            _isMutator = false;
-            _shouldInvokeIfReceiverIsNull = false;
-        }
-
-        public bool OnNullCall
-        {
-            get => _isCalledOnNullInputs;
-            set => _isCalledOnNullInputs = value;
-        }
-
-        public bool IsMutator
-        {
-            get => _isMutator;
-            set => _isMutator = value;
-        }
-
-        public bool InvokeIfReceiverIsNull
-        {
-            get => _shouldInvokeIfReceiverIsNull;
-            set => _shouldInvokeIfReceiverIsNull = value;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlNorm.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlNorm.cs
deleted file mode 100644 (file)
index 24d6cf0..0000000
+++ /dev/null
@@ -1,605 +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;
-using System.Diagnostics;
-using System.Data;
-using System.IO;
-using System.Globalization;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Runtime.CompilerServices;
-using System.Data.SqlTypes;
-
-namespace Microsoft.SqlServer.Server
-{
-    // The class that holds the offset, field, and normalizer for
-    // a particular field.
-    internal sealed class FieldInfoEx : IComparable
-    {
-        internal readonly int Offset;
-        internal readonly FieldInfo FieldInfo;
-        internal readonly Normalizer Normalizer;
-
-        internal FieldInfoEx(FieldInfo fi, int offset, Normalizer normalizer)
-        {
-            FieldInfo = fi;
-            Offset = offset;
-            Debug.Assert(normalizer != null, "normalizer argument should not be null!");
-            Normalizer = normalizer;
-        }
-
-        // Sort fields by field offsets.
-        public int CompareTo(object other)
-        {
-            FieldInfoEx otherF = other as FieldInfoEx;
-            if (otherF == null)
-                return -1;
-            return Offset.CompareTo(otherF.Offset);
-        }
-    }
-
-    // The most complex normalizer, a udt normalizer
-    internal sealed class BinaryOrderedUdtNormalizer : Normalizer
-    {
-        internal readonly FieldInfoEx[] FieldsToNormalize;
-        private int _size;
-        private readonly byte[] _padBuffer;
-        internal readonly object NullInstance;
-        //a boolean that tells us if a udt is a "top-level" udt,
-        //i.e. one that does not require a null byte header.
-        private readonly bool _isTopLevelUdt;
-
-        private FieldInfo[] GetFields(Type t)
-        {
-            return t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
-        }
-
-        internal BinaryOrderedUdtNormalizer(Type t, bool isTopLevelUdt)
-        {
-            _skipNormalize = false;
-            if (_skipNormalize)
-            {
-                // if skipping normalization, dont write the null
-                // byte header for IsNull
-                _isTopLevelUdt = true;
-            }
-
-            _isTopLevelUdt = true;
-
-            // get all the fields
-            FieldInfo[] fields = GetFields(t);
-
-            FieldsToNormalize = new FieldInfoEx[fields.Length];
-
-            int i = 0;
-
-            foreach (FieldInfo fi in fields)
-            {
-                int offset = Marshal.OffsetOf(fi.DeclaringType, fi.Name).ToInt32();
-                FieldsToNormalize[i++] = new FieldInfoEx(fi, offset, GetNormalizer(fi.FieldType));
-            }
-
-            //sort by offset
-            Array.Sort(FieldsToNormalize);
-            //if this is not a top-level udt, do setup for null values.
-            //null values need to compare less than all other values,
-            //so prefix a null byte indicator.
-            if (!_isTopLevelUdt)
-            {
-                //get the null value for this type, special case for sql types, which
-                //have a null field
-                if (typeof(INullable).IsAssignableFrom(t))
-                {
-                    PropertyInfo pi = t.GetProperty("Null",
-                    BindingFlags.Public | BindingFlags.Static);
-                    if (pi == null || pi.PropertyType != t)
-                    {
-                        FieldInfo fi = t.GetField("Null", BindingFlags.Public | BindingFlags.Static);
-                        if (fi == null || fi.FieldType != t)
-                            throw new Exception("could not find Null field/property in nullable type " + t);
-                        else
-                            NullInstance = fi.GetValue(null);
-                    }
-                    else
-                    {
-                        NullInstance = pi.GetValue(null, null);
-                    }
-                    //create the padding buffer
-                    _padBuffer = new byte[Size - 1];
-                }
-            }
-        }
-
-        internal bool IsNullable => (NullInstance != null);
-
-        // Normalize the top-level udt
-        internal void NormalizeTopObject(object udt, Stream s)
-        {
-            Normalize(null, udt, s);
-        }
-
-        // Denormalize a top-level udt and return it
-        internal object DeNormalizeTopObject(Type t, Stream s) => DeNormalizeInternal(t, s);
-
-        // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private object DeNormalizeInternal(Type t, Stream s)
-        {
-            object result = null;
-            //if nullable and not the top object, read the null marker
-            if (!_isTopLevelUdt && typeof(INullable).IsAssignableFrom(t))
-            {
-                byte nullByte = (byte)s.ReadByte();
-                if (nullByte == 0)
-                {
-                    result = NullInstance;
-                    s.Read(_padBuffer, 0, _padBuffer.Length);
-                    return result;
-                }
-            }
-            if (result == null)
-                result = Activator.CreateInstance(t);
-            foreach (FieldInfoEx myField in FieldsToNormalize)
-            {
-                myField.Normalizer.DeNormalize(myField.FieldInfo, result, s);
-            }
-            return result;
-        }
-
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            object inner;
-            if (fi == null)
-            {
-                inner = obj;
-            }
-            else
-            {
-                inner = GetValue(fi, obj);
-            }
-
-            // If nullable and not the top object, write a null indicator
-            if (inner is INullable oNullable && !_isTopLevelUdt)
-            {
-                if (oNullable.IsNull)
-                {
-                    s.WriteByte(0);
-                    s.Write(_padBuffer, 0, _padBuffer.Length);
-                    return;
-                }
-                else
-                {
-                    s.WriteByte(1);
-                }
-            }
-
-            foreach (FieldInfoEx myField in FieldsToNormalize)
-            {
-                myField.Normalizer.Normalize(myField.FieldInfo, inner, s);
-            }
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            SetValue(fi, recvr, DeNormalizeInternal(fi.FieldType, s));
-        }
-
-        internal override int Size
-        {
-            get
-            {
-                if (_size != 0)
-                    return _size;
-                if (IsNullable && !_isTopLevelUdt)
-                    _size = 1;
-                foreach (FieldInfoEx myField in FieldsToNormalize)
-                {
-                    _size += myField.Normalizer.Size;
-                }
-                return _size;
-            }
-        }
-    }
-
-    internal abstract class Normalizer
-    {
-        protected bool _skipNormalize;
-
-        internal static Normalizer GetNormalizer(Type t)
-        {
-            Normalizer n = null;
-            if (t.IsPrimitive)
-            {
-                if (t == typeof(byte))
-                    n = new ByteNormalizer();
-                else if (t == typeof(sbyte))
-                    n = new SByteNormalizer();
-                else if (t == typeof(bool))
-                    n = new BooleanNormalizer();
-                else if (t == typeof(short))
-                    n = new ShortNormalizer();
-                else if (t == typeof(ushort))
-                    n = new UShortNormalizer();
-                else if (t == typeof(int))
-                    n = new IntNormalizer();
-                else if (t == typeof(uint))
-                    n = new UIntNormalizer();
-                else if (t == typeof(float))
-                    n = new FloatNormalizer();
-                else if (t == typeof(double))
-                    n = new DoubleNormalizer();
-                else if (t == typeof(long))
-                    n = new LongNormalizer();
-                else if (t == typeof(ulong))
-                    n = new ULongNormalizer();
-            }
-            else if (t.IsValueType)
-            {
-                n = new BinaryOrderedUdtNormalizer(t, false);
-            }
-            if (n == null)
-                throw new Exception(SR.GetString(SR.SQL_CannotCreateNormalizer, t.FullName));
-            n._skipNormalize = false;
-            return n;
-        }
-
-        internal abstract void Normalize(FieldInfo fi, object recvr, Stream s);
-
-        internal abstract void DeNormalize(FieldInfo fi, object recvr, Stream s);
-
-        protected void FlipAllBits(byte[] b)
-        {
-            for (int i = 0; i < b.Length; i++)
-                b[i] = (byte)~b[i];
-        }
-
-        protected object GetValue(FieldInfo fi, object obj) => fi.GetValue(obj);
-
-        protected void SetValue(FieldInfo fi, object recvr, object value)
-        {
-            fi.SetValue(recvr, value);
-        }
-
-        internal abstract int Size { get; }
-    }
-
-    internal sealed class BooleanNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            bool b = (bool)GetValue(fi, obj);
-            s.WriteByte((byte)(b ? 1 : 0));
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte b = (byte)s.ReadByte();
-            SetValue(fi, recvr, b == 1);
-        }
-
-        internal override int Size => 1;
-    }
-
-    internal sealed class SByteNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            sbyte sb = (sbyte)GetValue(fi, obj);
-            byte b;
-            unchecked
-            {
-                b = (byte)sb;
-            }
-            if (!_skipNormalize)
-                b ^= 0x80; // flip the sign bit
-            s.WriteByte(b);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte b = (byte)s.ReadByte();
-            if (!_skipNormalize)
-                b ^= 0x80; // flip the sign bit
-            sbyte sb;
-            unchecked
-            {
-                sb = (sbyte)b;
-            }
-            SetValue(fi, recvr, sb);
-        }
-
-        internal override int Size => 1;
-    }
-
-    internal sealed class ByteNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            byte b = (byte)GetValue(fi, obj);
-            s.WriteByte(b);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte b = (byte)s.ReadByte();
-            SetValue(fi, recvr, b);
-        }
-
-        internal override int Size => 1;
-    }
-
-    internal sealed class ShortNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            byte[] b = BitConverter.GetBytes((short)GetValue(fi, obj));
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-                b[0] ^= 0x80;
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[2];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                b[0] ^= 0x80;
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToInt16(b, 0));
-        }
-
-        internal override int Size { get { return 2; } }
-    }
-
-    internal sealed class UShortNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            byte[] b = BitConverter.GetBytes((ushort)GetValue(fi, obj));
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[2];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToUInt16(b, 0));
-        }
-
-        internal override int Size => 2;
-    }
-
-    internal sealed class IntNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            byte[] b = BitConverter.GetBytes((int)GetValue(fi, obj));
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-                b[0] ^= 0x80;
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[4];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                b[0] ^= 0x80;
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToInt32(b, 0));
-        }
-
-        internal override int Size => 4;
-    }
-
-    internal sealed class UIntNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            byte[] b = BitConverter.GetBytes((uint)GetValue(fi, obj));
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[4];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToUInt32(b, 0));
-        }
-
-        internal override int Size => 4;
-    }
-
-    internal sealed class LongNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            byte[] b = BitConverter.GetBytes((long)GetValue(fi, obj));
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-                b[0] ^= 0x80;
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[8];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                b[0] ^= 0x80;
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToInt64(b, 0));
-        }
-
-        internal override int Size => 8;
-    }
-
-    internal sealed class ULongNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            byte[] b = BitConverter.GetBytes((ulong)GetValue(fi, obj));
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[8];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToUInt64(b, 0));
-        }
-
-        internal override int Size => 8;
-    }
-
-    internal sealed class FloatNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            float f = (float)GetValue(fi, obj);
-            byte[] b = BitConverter.GetBytes(f);
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-                if ((b[0] & 0x80) == 0)
-                {
-                    // This is a positive number.
-                    // Flip the highest bit
-                    b[0] ^= 0x80;
-                }
-                else
-                {
-                    // This is a negative number.
-
-                    // If all zeroes, means it was a negative zero.
-                    // Treat it same as positive zero, so that
-                    // the normalized key will compare equal.
-                    if (f < 0)
-                        FlipAllBits(b);
-                }
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[4];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                if ((b[0] & 0x80) > 0)
-                {
-                    // This is a positive number.
-                    // Flip the highest bit
-                    b[0] ^= 0x80;
-                }
-                else
-                {
-                    // This is a negative number.
-                    FlipAllBits(b);
-                }
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToSingle(b, 0));
-        }
-
-        internal override int Size => 4;
-    }
-
-    internal sealed class DoubleNormalizer : Normalizer
-    {
-        internal override void Normalize(FieldInfo fi, object obj, Stream s)
-        {
-            double d = (double)GetValue(fi, obj);
-            byte[] b = BitConverter.GetBytes(d);
-            if (!_skipNormalize)
-            {
-                Array.Reverse(b);
-                if ((b[0] & 0x80) == 0)
-                {
-                    // This is a positive number.
-                    // Flip the highest bit
-                    b[0] ^= 0x80;
-                }
-                else
-                {
-                    // This is a negative number.
-                    if (d < 0)
-                    {
-                        // If all zeroes, means it was a negative zero.
-                        // Treat it same as positive zero, so that
-                        // the normalized key will compare equal.
-                        FlipAllBits(b);
-                    }
-                }
-            }
-            s.Write(b, 0, b.Length);
-        }
-
-        internal override void DeNormalize(FieldInfo fi, object recvr, Stream s)
-        {
-            byte[] b = new byte[8];
-            s.Read(b, 0, b.Length);
-            if (!_skipNormalize)
-            {
-                if ((b[0] & 0x80) > 0)
-                {
-                    // This is a positive number.
-                    // Flip the highest bit
-                    b[0] ^= 0x80;
-                }
-                else
-                {
-                    // This is a negative number.
-                    FlipAllBits(b);
-                }
-                Array.Reverse(b);
-            }
-            SetValue(fi, recvr, BitConverter.ToDouble(b, 0));
-        }
-
-        internal override int Size => 8;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlNotificationRequest.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlNotificationRequest.cs
deleted file mode 100644 (file)
index 88c2dc8..0000000
+++ /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.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.Sql
-{
-    public sealed class SqlNotificationRequest
-    {
-        private string _userData;
-        private string _options;
-        private int _timeout;
-
-        public SqlNotificationRequest()
-                : this(null, null, SQL.SqlDependencyTimeoutDefault) { }
-
-        public SqlNotificationRequest(string userData, string options, int timeout)
-        {
-            UserData = userData;
-            Timeout = timeout;
-            Options = options;
-        }
-
-        public string Options
-        {
-            get
-            {
-                return _options;
-            }
-            set
-            {
-                if ((null != value) && (ushort.MaxValue < value.Length))
-                {
-                    throw ADP.ArgumentOutOfRange(string.Empty, nameof(Options));
-                }
-                _options = value;
-            }
-        }
-
-        public int Timeout
-        {
-            get
-            {
-                return _timeout;
-            }
-            set
-            {
-                if (0 > value)
-                {
-                    throw ADP.ArgumentOutOfRange(string.Empty, nameof(Timeout));
-                }
-                _timeout = value;
-            }
-        }
-
-        public string UserData
-        {
-            get
-            {
-                return _userData;
-            }
-            set
-            {
-                if ((null != value) && (ushort.MaxValue < value.Length))
-                {
-                    throw ADP.ArgumentOutOfRange(string.Empty, nameof(UserData));
-                }
-                _userData = value;
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlSer.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlSer.cs
deleted file mode 100644 (file)
index 21f8248..0000000
+++ /dev/null
@@ -1,248 +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;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.IO;
-using System.Runtime.CompilerServices;
-
-namespace Microsoft.SqlServer.Server
-{
-    internal class SerializationHelperSql9
-    {
-        // Don't let anyone create an instance of this class.
-        private SerializationHelperSql9() { }
-
-        // Get the m_size of the serialized stream for this type, in bytes.
-        // This method creates an instance of the type using the public
-        // no-argument constructor, serializes it, and returns the m_size
-        // in bytes.
-        // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        internal static int SizeInBytes(Type t) => SizeInBytes(Activator.CreateInstance(t));
-
-        // Get the m_size of the serialized stream for this type, in bytes.
-        internal static int SizeInBytes(object instance)
-        {
-            Type t = instance.GetType();
-            Format k = GetFormat(t);
-            DummyStream stream = new DummyStream();
-            Serializer ser = GetSerializer(instance.GetType());
-            ser.Serialize(stream, instance);
-            return (int)stream.Length;
-        }
-
-        internal static void Serialize(Stream s, object instance)
-        {
-            GetSerializer(instance.GetType()).Serialize(s, instance);
-        }
-
-        internal static object Deserialize(Stream s, Type resultType) => GetSerializer(resultType).Deserialize(s);
-
-        private static Format GetFormat(Type t) => GetUdtAttribute(t).Format;
-
-        // Cache the relationship between a type and its serializer.
-        // This is expensive to compute since it involves traversing the
-        // custom attributes of the type using reflection.
-        //
-        // Use a per-thread cache, so that there are no synchronization
-        // issues when accessing cache entries from multiple threads.
-        [ThreadStatic]
-        private static Hashtable s_types2Serializers;
-
-        private static Serializer GetSerializer(Type t)
-        {
-            if (s_types2Serializers == null)
-                s_types2Serializers = new Hashtable();
-
-            Serializer s = (Serializer)s_types2Serializers[t];
-            if (s == null)
-            {
-                s = GetNewSerializer(t);
-                s_types2Serializers[t] = s;
-            }
-            return s;
-        }
-
-        internal static int GetUdtMaxLength(Type t)
-        {
-            SqlUdtInfo udtInfo = SqlUdtInfo.GetFromType(t);
-
-            if (Format.Native == udtInfo.SerializationFormat)
-            {
-                // In the native format, the user does not specify the
-                // max byte size, it is computed from the type definition
-                return SizeInBytes(t);
-            }
-            else
-            {
-                // In all other formats, the user specifies the maximum size in bytes.
-                return udtInfo.MaxByteSize;
-            }
-        }
-
-        private static object[] GetCustomAttributes(Type t)
-        {
-            return t.GetCustomAttributes(typeof(SqlUserDefinedTypeAttribute), false);
-        }
-
-        internal static SqlUserDefinedTypeAttribute GetUdtAttribute(Type t)
-        {
-            SqlUserDefinedTypeAttribute udtAttr = null;
-            object[] attr = GetCustomAttributes(t);
-
-            if (attr != null && attr.Length == 1)
-            {
-                udtAttr = (SqlUserDefinedTypeAttribute)attr[0];
-            }
-            else
-            {
-                throw InvalidUdtException.Create(t, SR.SqlUdtReason_NoUdtAttribute);
-            }
-            return udtAttr;
-        }
-
-        // Create a new serializer for the given type.
-        private static Serializer GetNewSerializer(Type t)
-        {
-            SqlUserDefinedTypeAttribute udtAttr = GetUdtAttribute(t);
-            Format k = GetFormat(t);
-
-            switch (k)
-            {
-                case Format.Native:
-                    return new NormalizedSerializer(t);
-                case Format.UserDefined:
-                    return new BinarySerializeSerializer(t);
-                case Format.Unknown: // should never happen, but fall through
-                default:
-                    throw ADP.InvalidUserDefinedTypeSerializationFormat(k);
-            }
-        }
-    }
-
-    // The base serializer class.
-    internal abstract class Serializer
-    {
-        public abstract object Deserialize(Stream s);
-        public abstract void Serialize(Stream s, object o);
-        protected Type _type;
-
-        protected Serializer(Type t)
-        {
-            _type = t;
-        }
-    }
-
-    internal sealed class NormalizedSerializer : Serializer
-    {
-        private readonly BinaryOrderedUdtNormalizer _normalizer;
-        private readonly bool _isFixedSize;
-        private readonly int _maxSize;
-
-        internal NormalizedSerializer(Type t) : base(t)
-        {
-            SqlUserDefinedTypeAttribute udtAttr = SerializationHelperSql9.GetUdtAttribute(t);
-            _normalizer = new BinaryOrderedUdtNormalizer(t, true);
-            _isFixedSize = udtAttr.IsFixedLength;
-            _maxSize = _normalizer.Size;
-        }
-
-        public override void Serialize(Stream s, object o)
-        {
-            _normalizer.NormalizeTopObject(o, s);
-        }
-
-        public override object Deserialize(Stream s) => _normalizer.DeNormalizeTopObject(_type, s);
-    }
-
-    internal sealed class BinarySerializeSerializer : Serializer
-    {
-        internal BinarySerializeSerializer(Type t) : base(t)
-        {
-        }
-
-        public override void Serialize(Stream s, object o)
-        {
-            BinaryWriter w = new BinaryWriter(s);
-            ((IBinarySerialize)o).Write(w);
-        }
-
-        // Prevent inlining so that reflection calls are not moved
-        // to a caller that may be in a different assembly that may
-        // have a different grant set.
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        public override object Deserialize(Stream s)
-        {
-            object instance = Activator.CreateInstance(_type);
-            BinaryReader r = new BinaryReader(s);
-            ((IBinarySerialize)instance).Read(r);
-            return instance;
-        }
-    }
-
-    // A dummy stream class, used to get the number of bytes written
-    // to the stream.
-    internal sealed class DummyStream : Stream
-    {
-        private long _size;
-
-        public DummyStream()
-        {
-        }
-
-        private void DontDoIt()
-        {
-            throw new Exception(SR.GetString(SR.Sql_InternalError));
-        }
-
-        public override bool CanRead => false;
-
-        public override bool CanWrite => true;
-
-        public override bool CanSeek => false;
-
-        public override long Position
-        {
-            get
-            {
-                return _size;
-            }
-            set
-            {
-                _size = value;
-            }
-        }
-
-        public override long Length => _size;
-
-        public override void SetLength(long value)
-        {
-            _size = value;
-        }
-
-        public override long Seek(long value, SeekOrigin loc)
-        {
-            DontDoIt();
-            return -1;
-        }
-
-        public override void Flush()
-        {
-        }
-
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            DontDoIt();
-            return -1;
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            _size += count;
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlUserDefinedAggregateAttribute.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlUserDefinedAggregateAttribute.cs
deleted file mode 100644 (file)
index 0bb216c..0000000
+++ /dev/null
@@ -1,124 +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.Data.Common;
-
-namespace Microsoft.SqlServer.Server
-{
-    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
-    public sealed class SqlUserDefinedAggregateAttribute : Attribute
-    {
-        private int _maxByteSize;
-        private bool _isInvariantToDup;
-        private bool _isInvariantToNulls;
-        private bool _isInvariantToOrder = true;
-        private bool _isNullIfEmpty;
-        private readonly Format _format;
-        private string _name;
-
-        // The maximum value for the maxbytesize field, in bytes.
-        public const int MaxByteSizeValue = 8000;
-
-        // A required attribute on all UD Aggs, used to indicate that the
-        // given type is a UD Agg, and its storage format.
-        public SqlUserDefinedAggregateAttribute(Format format)
-        {
-            switch (format)
-            {
-                case Format.Unknown:
-                    throw ADP.NotSupportedUserDefinedTypeSerializationFormat(format, nameof(format));
-                case Format.Native:
-                case Format.UserDefined:
-                    _format = format;
-                    break;
-                default:
-                    throw ADP.InvalidUserDefinedTypeSerializationFormat(format);
-            }
-        }
-
-        // The maximum size of this instance, in bytes. Does not have to be
-        // specified for Native format serialization. The maximum value
-        // for this property is specified by MaxByteSizeValue.
-        public int MaxByteSize
-        {
-            get
-            {
-                return _maxByteSize;
-            }
-            set
-            {
-                // MaxByteSize of -1 means 2GB and is valid, as well as 0 to MaxByteSizeValue
-                if (value < -1 || value > MaxByteSizeValue)
-                {
-                    throw ADP.ArgumentOutOfRange(SR.GetString(SR.SQLUDT_MaxByteSizeValue), nameof(MaxByteSize), value);
-                }
-                _maxByteSize = value;
-            }
-        }
-
-        public bool IsInvariantToDuplicates
-        {
-            get
-            {
-                return _isInvariantToDup;
-            }
-            set
-            {
-                _isInvariantToDup = value;
-            }
-        }
-
-        public bool IsInvariantToNulls
-        {
-            get
-            {
-                return _isInvariantToNulls;
-            }
-            set
-            {
-                _isInvariantToNulls = value;
-            }
-        }
-
-        public bool IsInvariantToOrder
-        {
-            get
-            {
-                return _isInvariantToOrder;
-            }
-            set
-            {
-                _isInvariantToOrder = value;
-            }
-        }
-
-        public bool IsNullIfEmpty
-        {
-            get
-            {
-                return _isNullIfEmpty;
-            }
-            set
-            {
-                _isNullIfEmpty = value;
-            }
-        }
-
-        // The on-disk format for this type.
-        public Format Format => _format;
-
-        public string Name
-        {
-            get
-            {
-                return _name;
-            }
-            set
-            {
-                _name = value;
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlUserDefinedTypeAttribute.cs b/src/libraries/System.Data.SqlClient/src/System/Data/Sql/SqlUserDefinedTypeAttribute.cs
deleted file mode 100644 (file)
index 5a94c43..0000000
+++ /dev/null
@@ -1,128 +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.Data.Common;
-
-namespace Microsoft.SqlServer.Server
-{
-    public enum Format
-    {
-        Unknown = 0,
-        Native = 1,
-        UserDefined = 2,
-    }
-
-    // This custom attribute indicates that the given type is
-    // a SqlServer udt. The properties on the attribute reflect the
-    // physical attributes that will be used when the type is registered
-    // with SqlServer.
-    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
-    public sealed class SqlUserDefinedTypeAttribute : Attribute
-    {
-        private int _maxByteSize;
-        private bool _isFixedLength;
-        private bool _isByteOrdered;
-        private readonly Format _format;
-        private string _name;
-
-        // The maximum value for the maxbytesize field, in bytes.
-        internal const int YukonMaxByteSizeValue = 8000;
-        private string _validationMethodName = null;
-
-        // A required attribute on all udts, used to indicate that the
-        // given type is a udt, and its storage format.
-        public SqlUserDefinedTypeAttribute(Format format)
-        {
-            switch (format)
-            {
-                case Format.Unknown:
-                    throw ADP.NotSupportedUserDefinedTypeSerializationFormat(format, nameof(format));
-                case Format.Native:
-                case Format.UserDefined:
-                    _format = format;
-                    break;
-                default:
-                    throw ADP.InvalidUserDefinedTypeSerializationFormat(format);
-            }
-        }
-
-        // The maximum size of this instance, in bytes. Does not have to be
-        // specified for Native serialization. The maximum value
-        // for this property is specified by MaxByteSizeValue.
-        public int MaxByteSize
-        {
-            get
-            {
-                return _maxByteSize;
-            }
-            set
-            {
-                if (value < -1)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(MaxByteSize));
-                }
-                _maxByteSize = value;
-            }
-        }
-
-        // Are all instances of this udt the same size on disk?
-        public bool IsFixedLength
-        {
-            get
-            {
-                return _isFixedLength;
-            }
-            set
-            {
-                _isFixedLength = value;
-            }
-        }
-
-        // Is this type byte ordered, i.e. is the on disk representation
-        // consistent with the ordering semantics for this type?
-        // If true, the binary representation of the type will be used
-        // in comparison by SqlServer. This property enables indexing on the
-        // udt and faster comparisons.
-        public bool IsByteOrdered
-        {
-            get
-            {
-                return _isByteOrdered;
-            }
-            set
-            {
-                _isByteOrdered = value;
-            }
-        }
-
-        // The on-disk format for this type.
-        public Format Format => _format;
-
-        // An Optional method used to validate this UDT
-        public string ValidationMethodName
-        {
-            get
-            {
-                return _validationMethodName;
-            }
-            set
-            {
-                _validationMethodName = value;
-            }
-        }
-
-        public string Name
-        {
-            get
-            {
-                return _name;
-            }
-            set
-            {
-                _name = value;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/ApplicationIntent.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/ApplicationIntent.cs
deleted file mode 100644 (file)
index b127b7c..0000000
+++ /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.
-
-
-//------------------------------------------------------------------------------
-
-namespace System.Data.SqlClient
-{
-    /// <summary>
-    /// represents the application workload type when connecting to a server
-    /// </summary>
-    public enum ApplicationIntent
-    {
-        ReadWrite = 0,
-        ReadOnly = 1,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Common.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Common.cs
deleted file mode 100644 (file)
index b58bdd3..0000000
+++ /dev/null
@@ -1,120 +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.Data.SqlClient;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Text;
-
-namespace System.Data
-{
-    internal static partial class LocalDBAPI
-    {
-        private static LocalDBFormatMessageDelegate s_localDBFormatMessage = null;
-
-        internal static void ReleaseDLLHandles()
-        {
-            s_userInstanceDLLHandle = IntPtr.Zero;
-            s_localDBFormatMessage = null;
-        }
-
-
-        private static LocalDBFormatMessageDelegate LocalDBFormatMessage
-        {
-            get
-            {
-                if (s_localDBFormatMessage == null)
-                {
-                    lock (s_dllLock)
-                    {
-                        if (s_localDBFormatMessage == null)
-                        {
-                            IntPtr functionAddr = LoadProcAddress();
-
-                            if (functionAddr == IntPtr.Zero)
-                            {
-                                throw CreateLocalDBException(errorMessage: SR.LocalDB_MethodNotFound);
-                            }
-                            s_localDBFormatMessage = Marshal.GetDelegateForFunctionPointer<LocalDBFormatMessageDelegate>(functionAddr);
-                        }
-                    }
-                }
-                return s_localDBFormatMessage;
-            }
-        }
-
-        //This is copy of handle that SNI maintains, so we are responsible for freeing it - therefore there we are not using SafeHandle
-        private static IntPtr s_userInstanceDLLHandle = IntPtr.Zero;
-
-        private static readonly object s_dllLock = new object();
-
-
-        private const uint const_LOCALDB_TRUNCATE_ERR_MESSAGE = 1; // flag for LocalDBFormatMessage that indicates that message can be truncated if it does not fit in the buffer
-        private const int const_ErrorMessageBufferSize = 1024;     // Buffer size for Local DB error message 1K will be enough for all messages
-
-
-        internal static string GetLocalDBMessage(int hrCode)
-        {
-            Debug.Assert(hrCode < 0, "HRCode does not indicate error");
-            try
-            {
-                StringBuilder buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
-                uint len = (uint)buffer.Capacity;
-
-
-                // First try for current culture
-                int hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: (uint)CultureInfo.CurrentCulture.LCID,
-                                                 buffer: buffer, buflen: ref len);
-                if (hResult >= 0)
-                    return buffer.ToString();
-                else
-                {
-                    // Message is not available for current culture, try default
-                    buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
-                    len = (uint)buffer.Capacity;
-                    hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: 0 /* thread locale with fallback to English */,
-                                                 buffer: buffer, buflen: ref len);
-                    if (hResult >= 0)
-                        return buffer.ToString();
-                    else
-                        return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", SR.LocalDB_UnobtainableMessage, hResult);
-                }
-            }
-            catch (SqlException exc)
-            {
-                return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", SR.LocalDB_UnobtainableMessage, exc.Message);
-            }
-        }
-
-
-        private static SqlException CreateLocalDBException(string errorMessage, string instance = null, int localDbError = 0, int sniError = 0)
-        {
-            Debug.Assert((localDbError == 0) || (sniError == 0), "LocalDB error and SNI error cannot be specified simultaneously");
-            Debug.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty");
-            SqlErrorCollection collection = new SqlErrorCollection();
-
-            int errorCode = (localDbError == 0) ? sniError : localDbError;
-
-            if (sniError != 0)
-            {
-                string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
-                errorMessage = string.Format("{0} (error: {1} - {2})",
-                         errorMessage, sniError, sniErrorMessage);
-            }
-
-            collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, errorMessage, null, 0));
-
-            if (localDbError != 0)
-                collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
-
-            SqlException exc = SqlException.CreateException(collection, null);
-
-            exc._doNotReconnect = true;
-
-            return exc;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs
deleted file mode 100644 (file)
index f0a1356..0000000
+++ /dev/null
@@ -1,13 +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.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.
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs
deleted file mode 100644 (file)
index 33a6cfc..0000000
+++ /dev/null
@@ -1,42 +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.Data.SqlClient;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Text;
-
-namespace System.Data
-{
-    internal static partial class LocalDBAPI
-    {
-        private static IntPtr LoadProcAddress() => SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBFormatMessage");
-
-        private static IntPtr UserInstanceDLLHandle
-        {
-            get
-            {
-                if (s_userInstanceDLLHandle == IntPtr.Zero)
-                {
-                    lock (s_dllLock)
-                    {
-                        if (s_userInstanceDLLHandle == IntPtr.Zero)
-                        {
-                            SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle);
-                            if (s_userInstanceDLLHandle == IntPtr.Zero)
-                            {
-                                SNINativeMethodWrapper.SNI_Error sniError;
-                                SNINativeMethodWrapper.SNIGetLastError(out sniError);
-                                throw CreateLocalDBException(errorMessage: SR.GetString("LocalDB_FailedGetDLLHandle"), sniError: (int)sniError.sniError);
-                            }
-                        }
-                    }
-                }
-                return s_userInstanceDLLHandle;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs
deleted file mode 100644 (file)
index e617f03..0000000
+++ /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.Runtime.InteropServices;
-using System.Text;
-
-namespace System.Data
-{
-    internal static partial class LocalDBAPI
-    {
-        private const string const_localDbPrefix = @"(localdb)\";
-
-
-        [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
-        private delegate int LocalDBFormatMessageDelegate(int hrLocalDB, uint dwFlags, uint dwLanguageId, StringBuilder buffer, ref uint buflen);
-
-        // check if name is in format (localdb)\<InstanceName - not empty> and return instance name if it is
-        internal static string GetLocalDbInstanceNameFromServerName(string serverName)
-        {
-            if (serverName == null)
-                return null;
-            serverName = serverName.TrimStart(); // it can start with spaces if specified in quotes
-            if (!serverName.StartsWith(const_localDbPrefix, StringComparison.OrdinalIgnoreCase))
-                return null;
-            string instanceName = serverName.Substring(const_localDbPrefix.Length).Trim();
-            if (instanceName.Length == 0)
-                return null;
-            else
-                return instanceName;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/OnChangedEventHandler.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/OnChangedEventHandler.cs
deleted file mode 100644 (file)
index ce8b2cb..0000000
+++ /dev/null
@@ -1,8 +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.Data.SqlClient
-{
-    public delegate void OnChangeEventHandler(object sender, SqlNotificationEventArgs e);
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PacketHandle.Unix.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PacketHandle.Unix.cs
deleted file mode 100644 (file)
index 4bf00ed..0000000
+++ /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.
-
-
-namespace System.Data.SqlClient
-{
-    // this structure is used for transporting packet handle references between the TdsParserStateObject
-    //  base class and Managed or Native implementations.
-    // It prevents the native IntPtr type from being boxed and prevents the need to cast from object which loses compile time type safety
-    // It carries type information so that assertions about the type of handle can be made in the implemented abstract methods
-    // it is a ref struct so that it can only be used to transport the handles and not store them
-
-    // N.B. If you change this type you must also change the version for the other platform
-
-    internal readonly ref struct PacketHandle
-    {
-        public const int NativePointerType = 1;
-        public const int NativePacketType = 2;
-        public const int ManagedPacketType = 3;
-
-        public readonly SNI.SNIPacket ManagedPacket;
-        public readonly int Type;
-
-        private PacketHandle(SNI.SNIPacket managedPacket, int type)
-        {
-            Type = type;
-            ManagedPacket = managedPacket;
-        }
-
-        public static PacketHandle FromManagedPacket(SNI.SNIPacket managedPacket) => new PacketHandle(managedPacket, ManagedPacketType);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PacketHandle.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PacketHandle.Windows.cs
deleted file mode 100644 (file)
index a2c4276..0000000
+++ /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.
-
-
-namespace System.Data.SqlClient
-{
-    // this structure is used for transporting packet handle references between the TdsParserStateObject
-    //  base class and Managed or Native implementations.
-    // It prevents the native IntPtr type from being boxed and prevents the need to cast from object which loses compile time type safety
-    // It carries type information so that assertions about the type of handle can be made in the implemented abstract methods
-    // it is a ref struct so that it can only be used to transport the handles and not store them
-
-    // N.B. If you change this type you must also change the version for the other platform
-
-    internal readonly ref struct PacketHandle
-    {
-        public const int NativePointerType = 1;
-        public const int NativePacketType = 2;
-        public const int ManagedPacketType = 3;
-
-        public readonly IntPtr NativePointer;
-        public readonly SNIPacket NativePacket;
-
-        public readonly SNI.SNIPacket ManagedPacket;
-        public readonly int Type;
-
-        private PacketHandle(IntPtr nativePointer, SNIPacket nativePacket, SNI.SNIPacket managedPacket, int type)
-        {
-            Type = type;
-            ManagedPacket = managedPacket;
-            NativePointer = nativePointer;
-            NativePacket = nativePacket;
-        }
-
-        public static PacketHandle FromManagedPacket(SNI.SNIPacket managedPacket) => new PacketHandle(default, default, managedPacket, ManagedPacketType);
-
-        public static PacketHandle FromNativePointer(IntPtr nativePointer) => new PacketHandle(nativePointer, default, default, NativePointerType);
-
-        public static PacketHandle FromNativePacket(SNIPacket nativePacket) => new PacketHandle(default, nativePacket, default, NativePacketType);
-
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/ParameterPeekAheadValue.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/ParameterPeekAheadValue.cs
deleted file mode 100644 (file)
index d203466..0000000
+++ /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.Collections.Generic;
-using Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    // simple storage to contain objects that must be generated prior to sending data, but
-    //  that we cannot re-generate at the time of sending the data.  The entire purpose is
-    //  to avoid long, complicated parameter lists that take every possible set of values.
-    //  Instead, a single peekahead object is passed in, encapsulating whatever sets are needed.
-    //
-    //  Example:
-    //      When processing IEnumerable<SqlDataRecord>, we need to obtain the enumerator and
-    //      the first record during metadata generation (metadata is stored in the first record),
-    //      but to properly stream the value, we can't ask the IEnumerable for these objects again
-    //      when it's time to send the actual values.
-
-    internal class ParameterPeekAheadValue
-    {
-        // Peekahead for IEnumerable<SqlDataRecord>
-        internal IEnumerator<SqlDataRecord> Enumerator;
-        internal SqlDataRecord FirstRecord;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PoolBlockingPeriod.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/PoolBlockingPeriod.cs
deleted file mode 100644 (file)
index 4c1d2d7..0000000
+++ /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.Data.SqlClient
-{
-    public enum PoolBlockingPeriod
-    {
-        Auto = 0,         // Blocking period OFF for Azure SQL servers, but ON for all other SQL servers.
-        AlwaysBlock = 1,  // Blocking period ON for all SQL servers including Azure SQL servers.
-        NeverBlock = 2,   // Blocking period OFF for all SQL servers including Azure SQL servers.
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/RowsCopiedEventArgs.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/RowsCopiedEventArgs.cs
deleted file mode 100644 (file)
index d2bf133..0000000
+++ /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.
-
-
-
-//------------------------------------------------------------------------------
-
-namespace System.Data.SqlClient
-{
-    public class SqlRowsCopiedEventArgs : System.EventArgs
-    {
-        private bool _abort;
-        private readonly long _rowsCopied;
-
-        public SqlRowsCopiedEventArgs(long rowsCopied)
-        {
-            _rowsCopied = rowsCopied;
-        }
-
-        public bool Abort
-        {
-            get
-            {
-                return _abort;
-            }
-            set
-            {
-                _abort = value;
-            }
-        }
-
-        public long RowsCopied
-        {
-            get
-            {
-                return _rowsCopied;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/RowsCopiedEventHandler.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/RowsCopiedEventHandler.cs
deleted file mode 100644 (file)
index 6cf7aff..0000000
+++ /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.
-
-
-
-//------------------------------------------------------------------------------
-
-namespace System.Data.SqlClient
-{
-    public delegate void SqlRowsCopiedEventHandler(object sender, SqlRowsCopiedEventArgs e);
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Unix.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Unix.cs
deleted file mode 100644 (file)
index a7da062..0000000
+++ /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.
-
-
-namespace System.Data.SqlClient.SNI
-{
-    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.
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs
deleted file mode 100644 (file)
index 367e1a3..0000000
+++ /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 Microsoft.Win32;
-using Microsoft.Win32.SafeHandles;
-using System.Runtime.InteropServices;
-using System.Text;
-
-namespace System.Data.SqlClient.SNI
-{
-    internal sealed class LocalDB
-    {
-        private static readonly LocalDB Instance = new LocalDB();
-
-        //HKEY_LOCAL_MACHINE
-        private const string LocalDBInstalledVersionRegistryKey = "SOFTWARE\\Microsoft\\Microsoft SQL Server Local DB\\Installed Versions\\";
-
-        private const string InstanceAPIPathValueName = "InstanceAPIPath";
-
-        private const string ProcLocalDBStartInstance = "LocalDBStartInstance";
-
-        private const int MAX_LOCAL_DB_CONNECTION_STRING_SIZE = 260;
-
-        private IntPtr _startInstanceHandle = IntPtr.Zero;
-
-        // Local Db api doc https://msdn.microsoft.com/en-us/library/hh217143.aspx
-        // HRESULT LocalDBStartInstance( [Input ] PCWSTR pInstanceName, [Input ] DWORD dwFlags,[Output] LPWSTR wszSqlConnection,[Input/Output] LPDWORD lpcchSqlConnection);
-        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
-        internal delegate int LocalDBStartInstance(
-                [In] [MarshalAs(UnmanagedType.LPWStr)] string localDBInstanceName,
-                [In]  int flags,
-                [Out] [MarshalAs(UnmanagedType.LPWStr)] StringBuilder sqlConnectionDataSource,
-                [In, Out]ref int bufferLength);
-
-        private LocalDBStartInstance localDBStartInstanceFunc = null;
-
-        private volatile SafeLibraryHandle _sqlUserInstanceLibraryHandle;
-
-        private LocalDB() { }
-
-        internal static string GetLocalDBConnectionString(string localDbInstance) =>
-            Instance.LoadUserInstanceDll() ? Instance.GetConnectionString(localDbInstance) : null;
-
-        internal static IntPtr GetProcAddress(string functionName) =>
-            Instance.LoadUserInstanceDll() ? Interop.Kernel32.GetProcAddress(LocalDB.Instance._sqlUserInstanceLibraryHandle, functionName) : IntPtr.Zero;
-
-        private string GetConnectionString(string localDbInstance)
-        {
-            StringBuilder localDBConnectionString = new StringBuilder(MAX_LOCAL_DB_CONNECTION_STRING_SIZE + 1);
-            int sizeOfbuffer = localDBConnectionString.Capacity;
-            localDBStartInstanceFunc(localDbInstance, 0, localDBConnectionString, ref sizeOfbuffer);
-            return localDBConnectionString.ToString();
-        }
-
-        internal enum LocalDBErrorState
-        {
-            NO_INSTALLATION, INVALID_CONFIG, NO_SQLUSERINSTANCEDLL_PATH, INVALID_SQLUSERINSTANCEDLL_PATH, NONE
-        }
-
-        internal static uint MapLocalDBErrorStateToCode(LocalDBErrorState errorState) =>
-            errorState switch
-            {
-                LocalDBErrorState.NO_INSTALLATION => SNICommon.LocalDBNoInstallation,
-                LocalDBErrorState.INVALID_CONFIG => SNICommon.LocalDBInvalidConfig,
-                LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH => SNICommon.LocalDBNoSqlUserInstanceDllPath,
-                LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH => SNICommon.LocalDBInvalidSqlUserInstanceDllPath,
-                LocalDBErrorState.NONE => 0,
-                _ => SNICommon.LocalDBInvalidConfig,
-            };
-
-        /// <summary>
-        /// Loads the User Instance dll.
-        /// </summary>
-        private bool LoadUserInstanceDll()
-        {
-            // Check in a non thread-safe way if the handle is already set for performance.
-            if (_sqlUserInstanceLibraryHandle != null)
-            {
-                return true;
-            }
-
-            lock (this)
-            {
-                if (_sqlUserInstanceLibraryHandle != null)
-                {
-                    return true;
-                }
-                //Get UserInstance Dll path
-                LocalDBErrorState registryQueryErrorState;
-
-                // Get the LocalDB instance dll path from the registry
-                string dllPath = GetUserInstanceDllPath(out registryQueryErrorState);
-
-                // If there was no DLL path found, then there is an error.
-                if (dllPath == null)
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, MapLocalDBErrorStateToCode(registryQueryErrorState), string.Empty);
-                    return false;
-                }
-
-                // In case the registry had an empty path for dll
-                if (string.IsNullOrWhiteSpace(dllPath))
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBInvalidSqlUserInstanceDllPath, string.Empty);
-                    return false;
-                }
-
-                // Load the dll
-                SafeLibraryHandle libraryHandle = Interop.Kernel32.LoadLibraryExW(dllPath.Trim(), IntPtr.Zero, 0);
-
-                if (libraryHandle.IsInvalid)
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBFailedToLoadDll, string.Empty);
-                    libraryHandle.Dispose();
-                    return false;
-                }
-
-                // Load the procs from the DLLs
-                _startInstanceHandle = Interop.Kernel32.GetProcAddress(libraryHandle, ProcLocalDBStartInstance);
-
-                if (_startInstanceHandle == IntPtr.Zero)
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, string.Empty);
-                    libraryHandle.Dispose();
-                    return false;
-                }
-
-                // Set the delegate the invoke.
-                localDBStartInstanceFunc = (LocalDBStartInstance)Marshal.GetDelegateForFunctionPointer(_startInstanceHandle, typeof(LocalDBStartInstance));
-
-                if (localDBStartInstanceFunc == null)
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, string.Empty);
-                    libraryHandle.Dispose();
-                    _startInstanceHandle = IntPtr.Zero;
-                    return false;
-                }
-
-                _sqlUserInstanceLibraryHandle = libraryHandle;
-
-                return true;
-            }
-        }
-
-        /// <summary>
-        /// Retrieves the part of the sqlUserInstance.dll from the registry
-        /// </summary>
-        /// <param name="errorState">In case the dll path is not found, the error is set here.</param>
-        /// <returns></returns>
-        private string GetUserInstanceDllPath(out LocalDBErrorState errorState)
-        {
-            string dllPath = null;
-            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(LocalDBInstalledVersionRegistryKey))
-            {
-                if (key == null)
-                {
-                    errorState = LocalDBErrorState.NO_INSTALLATION;
-                    return null;
-                }
-
-                Version zeroVersion = new Version();
-
-                Version latestVersion = zeroVersion;
-
-                foreach (string subKey in key.GetSubKeyNames())
-                {
-                    Version currentKeyVersion;
-
-                    if (!Version.TryParse(subKey, out currentKeyVersion))
-                    {
-                        errorState = LocalDBErrorState.INVALID_CONFIG;
-                        return null;
-                    }
-
-                    if (latestVersion.CompareTo(currentKeyVersion) < 0)
-                    {
-                        latestVersion = currentKeyVersion;
-                    }
-                }
-
-                // If no valid versions are found, then error out
-                if (latestVersion.Equals(zeroVersion))
-                {
-                    errorState = LocalDBErrorState.INVALID_CONFIG;
-                    return null;
-                }
-
-                // Use the latest version to get the DLL path
-                using (RegistryKey latestVersionKey = key.OpenSubKey(latestVersion.ToString()))
-                {
-
-                    object instanceAPIPathRegistryObject = latestVersionKey.GetValue(InstanceAPIPathValueName);
-
-                    if (instanceAPIPathRegistryObject == null)
-                    {
-                        errorState = LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH;
-                        return null;
-                    }
-
-                    RegistryValueKind valueKind = latestVersionKey.GetValueKind(InstanceAPIPathValueName);
-
-                    if (valueKind != RegistryValueKind.String)
-                    {
-                        errorState = LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH;
-                        return null;
-                    }
-
-                    dllPath = (string)instanceAPIPathRegistryObject;
-
-                    errorState = LocalDBErrorState.NONE;
-                    return dllPath;
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNICommon.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNICommon.cs
deleted file mode 100644 (file)
index c54e1e5..0000000
+++ /dev/null
@@ -1,221 +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.Security;
-using System.Security.Cryptography.X509Certificates;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// SNI Asynchronous callback
-    /// </summary>
-    /// <param name="packet">SNI packet</param>
-    /// <param name="sniErrorCode">SNI error code</param>
-    internal delegate void SNIAsyncCallback(SNIPacket packet, uint sniErrorCode);
-
-    /// <summary>
-    /// SNI provider identifiers
-    /// </summary>
-    internal enum SNIProviders
-    {
-        HTTP_PROV, // HTTP Provider
-        NP_PROV, // Named Pipes Provider
-        SESSION_PROV, // Session Provider
-        SIGN_PROV, // Sign Provider
-        SM_PROV, // Shared Memory Provider
-        SMUX_PROV, // SMUX Provider
-        SSL_PROV, // SSL Provider
-        TCP_PROV, // TCP Provider
-        MAX_PROVS, // Number of providers
-        INVALID_PROV // SQL Network Interfaces
-    }
-
-    /// <summary>
-    /// SMUX packet header
-    /// </summary>
-    internal sealed class SNISMUXHeader
-    {
-        public const int HEADER_LENGTH = 16;
-
-        public byte SMID;
-        public byte flags;
-        public ushort sessionId;
-        public uint length;
-        public uint sequenceNumber;
-        public uint highwater;
-
-        public void Read(byte[] bytes)
-        {
-            SMID = bytes[0];
-            flags = bytes[1];
-            sessionId = BitConverter.ToUInt16(bytes, 2);
-            length = BitConverter.ToUInt32(bytes, 4) - SNISMUXHeader.HEADER_LENGTH;
-            sequenceNumber = BitConverter.ToUInt32(bytes, 8);
-            highwater = BitConverter.ToUInt32(bytes, 12);
-        }
-
-        public void Write(Span<byte> bytes)
-        {
-            uint value = highwater;
-            // access the highest element first to cause the largest range check in the jit, then fill in the rest of the value and carry on as normal
-            bytes[15] = (byte)((value >> 24) & 0xff);
-            bytes[12] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.highwater).CopyTo(headerBytes, 12);
-            bytes[13] = (byte)((value >> 8) & 0xff);
-            bytes[14] = (byte)((value >> 16) & 0xff);
-
-            bytes[0] = SMID; // BitConverter.GetBytes(_currentHeader.SMID).CopyTo(headerBytes, 0);
-            bytes[1] = flags; // BitConverter.GetBytes(_currentHeader.flags).CopyTo(headerBytes, 1);
-
-            value = sessionId;
-            bytes[2] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sessionId).CopyTo(headerBytes, 2);
-            bytes[3] = (byte)((value >> 8) & 0xff);
-
-            value = length;
-            bytes[4] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.length).CopyTo(headerBytes, 4);
-            bytes[5] = (byte)((value >> 8) & 0xff);
-            bytes[6] = (byte)((value >> 16) & 0xff);
-            bytes[7] = (byte)((value >> 24) & 0xff);
-
-            value = sequenceNumber;
-            bytes[8] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sequenceNumber).CopyTo(headerBytes, 8);
-            bytes[9] = (byte)((value >> 8) & 0xff);
-            bytes[10] = (byte)((value >> 16) & 0xff);
-            bytes[11] = (byte)((value >> 24) & 0xff);
-
-        }
-    }
-
-    /// <summary>
-    /// SMUX packet flags
-    /// </summary>
-    [Flags]
-    internal enum SNISMUXFlags
-    {
-        SMUX_SYN = 1,       // Begin SMUX connection
-        SMUX_ACK = 2,       // Acknowledge SMUX packets
-        SMUX_FIN = 4,       // End SMUX connection
-        SMUX_DATA = 8       // SMUX data packet
-    }
-
-    internal class SNICommon
-    {
-        // Each error number maps to SNI_ERROR_* in String.resx
-        internal const int ConnTerminatedError = 2;
-        internal const int InvalidParameterError = 5;
-        internal const int ProtocolNotSupportedError = 8;
-        internal const int ConnTimeoutError = 11;
-        internal const int ConnNotUsableError = 19;
-        internal const int InvalidConnStringError = 25;
-        internal const int HandshakeFailureError = 31;
-        internal const int InternalExceptionError = 35;
-        internal const int ConnOpenFailedError = 40;
-        internal const int ErrorSpnLookup = 44;
-        internal const int LocalDBErrorCode = 50;
-        internal const int MultiSubnetFailoverWithMoreThan64IPs = 47;
-        internal const int MultiSubnetFailoverWithInstanceSpecified = 48;
-        internal const int MultiSubnetFailoverWithNonTcpProtocol = 49;
-        internal const int MaxErrorValue = 50157;
-        internal const int LocalDBNoInstanceName = 51;
-        internal const int LocalDBNoInstallation = 52;
-        internal const int LocalDBInvalidConfig = 53;
-        internal const int LocalDBNoSqlUserInstanceDllPath = 54;
-        internal const int LocalDBInvalidSqlUserInstanceDllPath = 55;
-        internal const int LocalDBFailedToLoadDll = 56;
-        internal const int LocalDBBadRuntime = 57;
-
-        /// <summary>
-        /// Validate server certificate callback for SSL
-        /// </summary>
-        /// <param name="targetServerName">Server that client is expecting to connect to</param>
-        /// <param name="sender">Sender object</param>
-        /// <param name="cert">X.509 certificate</param>
-        /// <param name="chain">X.509 chain</param>
-        /// <param name="policyErrors">Policy errors</param>
-        /// <returns>True if certificate is valid</returns>
-        internal static bool ValidateSslServerCertificate(string targetServerName, object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
-        {
-            if (policyErrors == SslPolicyErrors.None)
-            {
-                return true;
-            }
-
-            if ((policyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
-            {
-                string certServerName = cert.Subject.Substring(cert.Subject.IndexOf('=') + 1);
-
-                // Verify that target server name matches subject in the certificate
-                if (targetServerName.Length > certServerName.Length)
-                {
-                    return false;
-                }
-                else if (targetServerName.Length == certServerName.Length)
-                {
-                    // Both strings have the same length, so targetServerName must be a FQDN
-                    if (!targetServerName.Equals(certServerName, StringComparison.OrdinalIgnoreCase))
-                    {
-                        return false;
-                    }
-                }
-                else
-                {
-                    if (string.Compare(targetServerName, 0, certServerName, 0, targetServerName.Length, StringComparison.OrdinalIgnoreCase) != 0)
-                    {
-                        return false;
-                    }
-
-                    // Server name matches cert name for its whole length, so ensure that the
-                    // character following the server name is a '.'. This will avoid
-                    // having server name "ab" match "abc.corp.company.com"
-                    // (Names have different lengths, so the target server can't be a FQDN.)
-                    if (certServerName[targetServerName.Length] != '.')
-                    {
-                        return false;
-                    }
-                }
-            }
-            else
-            {
-                // Fail all other SslPolicy cases besides RemoteCertificateNameMismatch
-                return false;
-            }
-            return true;
-        }
-
-        /// <summary>
-        /// Sets last error encountered for SNI
-        /// </summary>
-        /// <param name="provider">SNI provider</param>
-        /// <param name="nativeError">Native error code</param>
-        /// <param name="sniError">SNI error code</param>
-        /// <param name="errorMessage">Error message</param>
-        /// <returns></returns>
-        internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uint sniError, string errorMessage)
-        {
-            return ReportSNIError(new SNIError(provider, nativeError, sniError, errorMessage));
-        }
-
-        /// <summary>
-        /// Sets last error encountered for SNI
-        /// </summary>
-        /// <param name="provider">SNI provider</param>
-        /// <param name="sniError">SNI error code</param>
-        /// <param name="sniException">SNI Exception</param>
-        /// <returns></returns>
-        internal static uint ReportSNIError(SNIProviders provider, uint sniError, Exception sniException)
-        {
-            return ReportSNIError(new SNIError(provider, sniError, sniException));
-        }
-
-        /// <summary>
-        /// Sets last error encountered for SNI
-        /// </summary>
-        /// <param name="error">SNI error</param>
-        /// <returns></returns>
-        internal static uint ReportSNIError(SNIError error)
-        {
-            SNILoadHandle.SingletonInstance.LastError = error;
-            return TdsEnums.SNI_ERROR;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIError.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIError.cs
deleted file mode 100644 (file)
index b2fe7fa..0000000
+++ /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.
-
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// SNI error
-    /// </summary>
-    internal class SNIError
-    {
-        public readonly SNIProviders provider;
-        public readonly string errorMessage;
-        public readonly uint nativeError;
-        public readonly uint sniError;
-        public readonly string function;
-        public readonly uint lineNumber;
-        public readonly Exception exception;
-
-        public SNIError(SNIProviders provider, uint nativeError, uint sniErrorCode, string errorMessage)
-        {
-            this.lineNumber = 0;
-            this.function = string.Empty;
-            this.provider = provider;
-            this.nativeError = nativeError;
-            this.sniError = sniErrorCode;
-            this.errorMessage = errorMessage;
-            this.exception = null;
-        }
-
-        public SNIError(SNIProviders provider, uint sniErrorCode, Exception sniException)
-        {
-            this.lineNumber = 0;
-            this.function = string.Empty;
-            this.provider = provider;
-            this.nativeError = 0;
-            this.sniError = sniErrorCode;
-            this.errorMessage = string.Empty;
-            this.exception = sniException;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIHandle.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIHandle.cs
deleted file mode 100644 (file)
index 00af92b..0000000
+++ /dev/null
@@ -1,96 +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.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// SNI connection handle
-    /// </summary>
-    internal abstract class SNIHandle
-    {
-        /// <summary>
-        /// Dispose class
-        /// </summary>
-        public abstract void Dispose();
-
-        /// <summary>
-        /// Set async callbacks
-        /// </summary>
-        /// <param name="receiveCallback">Receive callback</param>
-        /// <param name="sendCallback">Send callback</param>
-        public abstract void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback);
-
-        /// <summary>
-        /// Set buffer size
-        /// </summary>
-        /// <param name="bufferSize">Buffer size</param>
-        public abstract void SetBufferSize(int bufferSize);
-
-        /// <summary>
-        /// Send a packet synchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        public abstract uint Send(SNIPacket packet);
-
-        /// <summary>
-        /// Send a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="callback">Completion callback</param>
-        /// <returns>SNI error code</returns>
-        public abstract uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null);
-
-        /// <summary>
-        /// Receive a packet synchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param>
-        /// <returns>SNI error code</returns>
-        public abstract uint Receive(out SNIPacket packet, int timeoutInMilliseconds);
-
-        /// <summary>
-        /// Receive a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        public abstract uint ReceiveAsync(ref SNIPacket packet);
-
-        /// <summary>
-        /// Enable SSL
-        /// </summary>
-        public abstract uint EnableSsl(uint options);
-
-        /// <summary>
-        /// Disable SSL
-        /// </summary>
-        public abstract void DisableSsl();
-
-        /// <summary>
-        /// Check connection status
-        /// </summary>
-        /// <returns>SNI error code</returns>
-        public abstract uint CheckConnection();
-
-        /// <summary>
-        /// Last handle status
-        /// </summary>
-        public abstract uint Status { get; }
-
-        /// <summary>
-        /// Connection ID
-        /// </summary>
-        public abstract Guid ConnectionId { get; }
-
-        public virtual int ReserveHeaderSize => 0;
-
-#if DEBUG
-        /// <summary>
-        /// Test handle for killing underlying connection
-        /// </summary>
-        public abstract void KillConnection();
-#endif
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNILoadHandle.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNILoadHandle.cs
deleted file mode 100644 (file)
index 43ce28b..0000000
+++ /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.Threading;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// Global SNI settings and status
-    /// </summary>
-    internal class SNILoadHandle
-    {
-        public static readonly SNILoadHandle SingletonInstance = new SNILoadHandle();
-
-        public readonly EncryptionOptions _encryptionOption = EncryptionOptions.OFF;
-        public ThreadLocal<SNIError> _lastError = new ThreadLocal<SNIError>(() => { return new SNIError(SNIProviders.INVALID_PROV, 0, TdsEnums.SNI_SUCCESS, string.Empty); });
-
-        private readonly uint _status = TdsEnums.SNI_SUCCESS;
-
-        /// <summary>
-        /// Last SNI error
-        /// </summary>
-        public SNIError LastError
-        {
-            get
-            {
-                return _lastError.Value;
-            }
-
-            set
-            {
-                _lastError.Value = value;
-            }
-        }
-
-        /// <summary>
-        /// SNI library status
-        /// </summary>
-        public uint Status
-        {
-            get
-            {
-                return _status;
-            }
-        }
-
-        /// <summary>
-        /// Encryption options setting
-        /// </summary>
-        public EncryptionOptions Options
-        {
-            get
-            {
-                return _encryptionOption;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsConnection.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsConnection.cs
deleted file mode 100644 (file)
index 81bc8a6..0000000
+++ /dev/null
@@ -1,318 +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.Generic;
-using System.Diagnostics;
-using System.Threading;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// SNI MARS connection. Multiple MARS streams will be overlaid on this connection.
-    /// </summary>
-    internal class SNIMarsConnection
-    {
-        private readonly Guid _connectionId = Guid.NewGuid();
-        private readonly Dictionary<int, SNIMarsHandle> _sessions = new Dictionary<int, SNIMarsHandle>();
-        private readonly byte[] _headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH];
-        private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader();
-        private SNIHandle _lowerHandle;
-        private ushort _nextSessionId = 0;
-        private int _currentHeaderByteCount = 0;
-        private int _dataBytesLeft = 0;
-        private SNIPacket _currentPacket;
-
-        /// <summary>
-        /// Connection ID
-        /// </summary>
-        public Guid ConnectionId
-        {
-            get
-            {
-                return _connectionId;
-            }
-        }
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="lowerHandle">Lower handle</param>
-        public SNIMarsConnection(SNIHandle lowerHandle)
-        {
-            _lowerHandle = lowerHandle;
-            _lowerHandle.SetAsyncCallbacks(HandleReceiveComplete, HandleSendComplete);
-        }
-
-        public SNIMarsHandle CreateMarsSession(object callbackObject, bool async)
-        {
-            lock (this)
-            {
-                ushort sessionId = _nextSessionId++;
-                SNIMarsHandle handle = new SNIMarsHandle(this, sessionId, callbackObject, async);
-                _sessions.Add(sessionId, handle);
-                return handle;
-            }
-        }
-
-        /// <summary>
-        /// Start receiving
-        /// </summary>
-        /// <returns></returns>
-        public uint StartReceive()
-        {
-            SNIPacket packet = null;
-
-            if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING)
-            {
-                return TdsEnums.SNI_SUCCESS_IO_PENDING;
-            }
-
-            return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, string.Empty);
-        }
-
-        /// <summary>
-        /// Send a packet synchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        public uint Send(SNIPacket packet)
-        {
-            lock (this)
-            {
-                return _lowerHandle.Send(packet);
-            }
-        }
-
-        /// <summary>
-        /// Send a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="callback">Completion callback</param>
-        /// <returns>SNI error code</returns>
-        public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback)
-        {
-            lock (this)
-            {
-                return _lowerHandle.SendAsync(packet, false, callback);
-            }
-        }
-
-        /// <summary>
-        /// Receive a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        public uint ReceiveAsync(ref SNIPacket packet)
-        {
-            if (packet != null)
-            {
-                packet.Release();
-                packet = null;
-            }
-            lock (this)
-            {
-                return _lowerHandle.ReceiveAsync(ref packet);
-            }
-        }
-
-        /// <summary>
-        /// Check SNI handle connection
-        /// </summary>
-        /// <returns>SNI error status</returns>
-        public uint CheckConnection()
-        {
-            lock (this)
-            {
-                return _lowerHandle.CheckConnection();
-            }
-        }
-
-        /// <summary>
-        /// Process a receive error
-        /// </summary>
-        public void HandleReceiveError(SNIPacket packet)
-        {
-            Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked.");
-            foreach (SNIMarsHandle handle in _sessions.Values)
-            {
-                if (packet.HasCompletionCallback)
-                {
-                    handle.HandleReceiveError(packet);
-                }
-            }
-            packet?.Release();
-        }
-
-        /// <summary>
-        /// Process a send completion
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="sniErrorCode">SNI error code</param>
-        public void HandleSendComplete(SNIPacket packet, uint sniErrorCode)
-        {
-            packet.InvokeCompletionCallback(sniErrorCode);
-        }
-
-        /// <summary>
-        /// Process a receive completion
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="sniErrorCode">SNI error code</param>
-        public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode)
-        {
-            SNISMUXHeader currentHeader = null;
-            SNIPacket currentPacket = null;
-            SNIMarsHandle currentSession = null;
-
-            if (sniErrorCode != TdsEnums.SNI_SUCCESS)
-            {
-                lock (this)
-                {
-                    HandleReceiveError(packet);
-                    return;
-                }
-            }
-
-            while (true)
-            {
-                lock (this)
-                {
-                    if (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
-                    {
-                        currentHeader = null;
-                        currentPacket = null;
-                        currentSession = null;
-
-                        while (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
-                        {
-                            int bytesTaken = packet.TakeData(_headerBytes, _currentHeaderByteCount, SNISMUXHeader.HEADER_LENGTH - _currentHeaderByteCount);
-                            _currentHeaderByteCount += bytesTaken;
-
-                            if (bytesTaken == 0)
-                            {
-                                sniErrorCode = ReceiveAsync(ref packet);
-
-                                if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
-                                {
-                                    return;
-                                }
-
-                                HandleReceiveError(packet);
-                                return;
-                            }
-                        }
-
-                        _currentHeader.Read(_headerBytes);
-                        _dataBytesLeft = (int)_currentHeader.length;
-                        _currentPacket = new SNIPacket(headerSize: 0, dataSize: (int)_currentHeader.length);
-                    }
-
-                    currentHeader = _currentHeader;
-                    currentPacket = _currentPacket;
-
-                    if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
-                    {
-                        if (_dataBytesLeft > 0)
-                        {
-                            int length = packet.TakeData(_currentPacket, _dataBytesLeft);
-                            _dataBytesLeft -= length;
-
-                            if (_dataBytesLeft > 0)
-                            {
-                                sniErrorCode = ReceiveAsync(ref packet);
-
-                                if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
-                                {
-                                    return;
-                                }
-
-                                HandleReceiveError(packet);
-                                return;
-                            }
-                        }
-                    }
-
-                    _currentHeaderByteCount = 0;
-
-                    if (!_sessions.ContainsKey(_currentHeader.sessionId))
-                    {
-                        SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.InvalidParameterError, string.Empty);
-                        HandleReceiveError(packet);
-                        _lowerHandle.Dispose();
-                        _lowerHandle = null;
-                        return;
-                    }
-
-                    if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_FIN)
-                    {
-                        _sessions.Remove(_currentHeader.sessionId);
-                    }
-                    else
-                    {
-                        currentSession = _sessions[_currentHeader.sessionId];
-                    }
-                }
-
-                if (currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
-                {
-                    currentSession.HandleReceiveComplete(currentPacket, currentHeader);
-                }
-
-                if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_ACK)
-                {
-                    try
-                    {
-                        currentSession.HandleAck(currentHeader.highwater);
-                    }
-                    catch (Exception e)
-                    {
-                        SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e);
-                    }
-                }
-
-                lock (this)
-                {
-                    if (packet.DataLeft == 0)
-                    {
-                        sniErrorCode = ReceiveAsync(ref packet);
-
-                        if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
-                        {
-                            return;
-                        }
-
-                        HandleReceiveError(packet);
-                        return;
-                    }
-                }
-            }
-        }
-
-        /// <summary>
-        /// Enable SSL
-        /// </summary>
-        public uint EnableSsl(uint options)
-        {
-            return _lowerHandle.EnableSsl(options);
-        }
-
-        /// <summary>
-        /// Disable SSL
-        /// </summary>
-        public void DisableSsl()
-        {
-            _lowerHandle.DisableSsl();
-        }
-
-#if DEBUG
-        /// <summary>
-        /// Test handle for killing underlying connection
-        /// </summary>
-        public void KillConnection()
-        {
-            _lowerHandle.KillConnection();
-        }
-#endif
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsHandle.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsHandle.cs
deleted file mode 100644 (file)
index 17ac984..0000000
+++ /dev/null
@@ -1,479 +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.Generic;
-using System.Diagnostics;
-using System.Threading;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// MARS handle
-    /// </summary>
-    internal sealed class SNIMarsHandle : SNIHandle
-    {
-        private const uint ACK_THRESHOLD = 2;
-
-        private readonly SNIMarsConnection _connection;
-        private readonly uint _status = TdsEnums.SNI_UNINITIALIZED;
-        private readonly Queue<SNIPacket> _receivedPacketQueue = new Queue<SNIPacket>();
-        private readonly Queue<SNIMarsQueuedPacket> _sendPacketQueue = new Queue<SNIMarsQueuedPacket>();
-        private readonly object _callbackObject;
-        private readonly Guid _connectionId = Guid.NewGuid();
-        private readonly ushort _sessionId;
-        private readonly ManualResetEventSlim _packetEvent = new ManualResetEventSlim(false);
-        private readonly ManualResetEventSlim _ackEvent = new ManualResetEventSlim(false);
-        private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader();
-
-        private uint _sendHighwater = 4;
-        private int _asyncReceives = 0;
-        private uint _receiveHighwater = 4;
-        private uint _receiveHighwaterLastAck = 4;
-        private uint _sequenceNumber;
-        private SNIError _connectionError;
-
-        public override Guid ConnectionId => _connectionId;
-
-        public override uint Status => _status;
-
-        public override int ReserveHeaderSize => SNISMUXHeader.HEADER_LENGTH;
-
-        /// <summary>
-        /// Dispose object
-        /// </summary>
-        public override void Dispose()
-        {
-            try
-            {
-                SendControlPacket(SNISMUXFlags.SMUX_FIN);
-            }
-            catch (Exception e)
-            {
-                SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e);
-            }
-        }
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="connection">MARS connection</param>
-        /// <param name="sessionId">MARS session ID</param>
-        /// <param name="callbackObject">Callback object</param>
-        /// <param name="async">true if connection is asynchronous</param>
-        public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object callbackObject, bool async)
-        {
-            _sessionId = sessionId;
-            _connection = connection;
-            _callbackObject = callbackObject;
-            SendControlPacket(SNISMUXFlags.SMUX_SYN);
-            _status = TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Send control packet
-        /// </summary>
-        /// <param name="flags">SMUX header flags</param>
-        private void SendControlPacket(SNISMUXFlags flags)
-        {
-            SNIPacket packet = new SNIPacket(headerSize: SNISMUXHeader.HEADER_LENGTH, dataSize: 0);
-            lock (this)
-            {
-                SetupSMUXHeader(0, flags);
-                _currentHeader.Write(packet.GetHeaderBuffer(SNISMUXHeader.HEADER_LENGTH));
-                packet.SetHeaderActive();
-            }
-            _connection.Send(packet);
-        }
-
-        private void SetupSMUXHeader(int length, SNISMUXFlags flags)
-        {
-            Debug.Assert(Monitor.IsEntered(this), "must take lock on self before updating mux header");
-            _currentHeader.SMID = 83;
-            _currentHeader.flags = (byte)flags;
-            _currentHeader.sessionId = _sessionId;
-            _currentHeader.length = (uint)SNISMUXHeader.HEADER_LENGTH + (uint)length;
-            _currentHeader.sequenceNumber = ((flags == SNISMUXFlags.SMUX_FIN) || (flags == SNISMUXFlags.SMUX_ACK)) ? _sequenceNumber - 1 : _sequenceNumber++;
-            _currentHeader.highwater = _receiveHighwater;
-            _receiveHighwaterLastAck = _currentHeader.highwater;
-        }
-
-        /// <summary>
-        /// Generate a packet with SMUX header
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>The packet with the SMUx header set.</returns>
-        private SNIPacket SetPacketSMUXHeader(SNIPacket packet)
-        {
-            Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to mux packet without mux reservation");
-
-            SetupSMUXHeader(packet.Length, SNISMUXFlags.SMUX_DATA);
-            _currentHeader.Write(packet.GetHeaderBuffer(SNISMUXHeader.HEADER_LENGTH));
-            packet.SetHeaderActive();
-            return packet;
-        }
-
-        /// <summary>
-        /// Send a packet synchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        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");
-
-            while (true)
-            {
-                lock (this)
-                {
-                    if (_sequenceNumber < _sendHighwater)
-                    {
-                        break;
-                    }
-                }
-
-                _ackEvent.Wait();
-
-                lock (this)
-                {
-                    _ackEvent.Reset();
-                }
-            }
-
-            SNIPacket muxedPacket = null;
-            lock (this)
-            {
-                muxedPacket = SetPacketSMUXHeader(packet);
-            }
-            return _connection.Send(muxedPacket);
-        }
-
-        /// <summary>
-        /// Send packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="callback">Completion callback</param>
-        /// <returns>SNI error code</returns>
-        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");
-            lock (this)
-            {
-                if (_sequenceNumber >= _sendHighwater)
-                {
-                    return TdsEnums.SNI_QUEUE_FULL;
-                }
-
-                SNIPacket muxedPacket = SetPacketSMUXHeader(packet);
-                muxedPacket.SetCompletionCallback(callback ?? HandleSendComplete);
-                return _connection.SendAsync(muxedPacket, callback);
-            }
-        }
-
-        /// <summary>
-        /// Send pending packets
-        /// </summary>
-        /// <returns>SNI error code</returns>
-        private uint SendPendingPackets()
-        {
-            SNIMarsQueuedPacket packet = null;
-
-            while (true)
-            {
-                lock (this)
-                {
-                    if (_sequenceNumber < _sendHighwater)
-                    {
-                        if (_sendPacketQueue.Count != 0)
-                        {
-                            packet = _sendPacketQueue.Peek();
-                            uint result = InternalSendAsync(packet.Packet, packet.Callback);
-
-                            if (result != TdsEnums.SNI_SUCCESS && result != TdsEnums.SNI_SUCCESS_IO_PENDING)
-                            {
-                                return result;
-                            }
-
-                            _sendPacketQueue.Dequeue();
-                            continue;
-                        }
-                        else
-                        {
-                            _ackEvent.Set();
-                        }
-                    }
-
-                    break;
-                }
-            }
-
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Send a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="callback">Completion callback</param>
-        /// <returns>SNI error code</returns>
-        public override uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null)
-        {
-            lock (this)
-            {
-                _sendPacketQueue.Enqueue(new SNIMarsQueuedPacket(packet, callback != null ? callback : HandleSendComplete));
-            }
-
-            SendPendingPackets();
-            return TdsEnums.SNI_SUCCESS_IO_PENDING;
-        }
-
-        /// <summary>
-        /// Receive a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        public override uint ReceiveAsync(ref SNIPacket packet)
-        {
-            lock (_receivedPacketQueue)
-            {
-                int queueCount = _receivedPacketQueue.Count;
-
-                if (_connectionError != null)
-                {
-                    return SNICommon.ReportSNIError(_connectionError);
-                }
-
-                if (queueCount == 0)
-                {
-                    _asyncReceives++;
-                    return TdsEnums.SNI_SUCCESS_IO_PENDING;
-                }
-
-                packet = _receivedPacketQueue.Dequeue();
-
-                if (queueCount == 1)
-                {
-                    _packetEvent.Reset();
-                }
-            }
-
-            lock (this)
-            {
-                _receiveHighwater++;
-            }
-
-            SendAckIfNecessary();
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Handle receive error
-        /// </summary>
-        public void HandleReceiveError(SNIPacket packet)
-        {
-            lock (_receivedPacketQueue)
-            {
-                _connectionError = SNILoadHandle.SingletonInstance.LastError;
-                _packetEvent.Set();
-            }
-
-            ((TdsParserStateObject)_callbackObject).ReadAsyncCallback(PacketHandle.FromManagedPacket(packet), 1);
-        }
-
-        /// <summary>
-        /// Handle send completion
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="sniErrorCode">SNI error code</param>
-        public void HandleSendComplete(SNIPacket packet, uint sniErrorCode)
-        {
-            lock (this)
-            {
-                Debug.Assert(_callbackObject != null);
-
-                ((TdsParserStateObject)_callbackObject).WriteAsyncCallback(PacketHandle.FromManagedPacket(packet), sniErrorCode);
-            }
-        }
-
-        /// <summary>
-        /// Handle SMUX acknowledgement
-        /// </summary>
-        /// <param name="highwater">Send highwater mark</param>
-        public void HandleAck(uint highwater)
-        {
-            lock (this)
-            {
-                if (_sendHighwater != highwater)
-                {
-                    _sendHighwater = highwater;
-                    SendPendingPackets();
-                }
-            }
-        }
-
-        /// <summary>
-        /// Handle receive completion
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="header">SMUX header</param>
-        public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header)
-        {
-            lock (this)
-            {
-                if (_sendHighwater != header.highwater)
-                {
-                    HandleAck(header.highwater);
-                }
-
-                lock (_receivedPacketQueue)
-                {
-                    if (_asyncReceives == 0)
-                    {
-                        _receivedPacketQueue.Enqueue(packet);
-                        _packetEvent.Set();
-                        return;
-                    }
-
-                    _asyncReceives--;
-                    Debug.Assert(_callbackObject != null);
-
-                    ((TdsParserStateObject)_callbackObject).ReadAsyncCallback(PacketHandle.FromManagedPacket(packet), 0);
-                }
-            }
-
-            lock (this)
-            {
-                _receiveHighwater++;
-            }
-
-            SendAckIfNecessary();
-        }
-
-        /// <summary>
-        /// Send ACK if we've hit highwater threshold
-        /// </summary>
-        private void SendAckIfNecessary()
-        {
-            uint receiveHighwater;
-            uint receiveHighwaterLastAck;
-
-            lock (this)
-            {
-                receiveHighwater = _receiveHighwater;
-                receiveHighwaterLastAck = _receiveHighwaterLastAck;
-            }
-
-            if (receiveHighwater - receiveHighwaterLastAck > ACK_THRESHOLD)
-            {
-                SendControlPacket(SNISMUXFlags.SMUX_ACK);
-            }
-        }
-
-        /// <summary>
-        /// Receive a packet synchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param>
-        /// <returns>SNI error code</returns>
-        public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
-        {
-            packet = null;
-            int queueCount;
-            uint result = TdsEnums.SNI_SUCCESS_IO_PENDING;
-
-            while (true)
-            {
-                lock (_receivedPacketQueue)
-                {
-                    if (_connectionError != null)
-                    {
-                        return SNICommon.ReportSNIError(_connectionError);
-                    }
-
-                    queueCount = _receivedPacketQueue.Count;
-
-                    if (queueCount > 0)
-                    {
-                        packet = _receivedPacketQueue.Dequeue();
-
-                        if (queueCount == 1)
-                        {
-                            _packetEvent.Reset();
-                        }
-
-                        result = TdsEnums.SNI_SUCCESS;
-                    }
-                }
-
-                if (result == TdsEnums.SNI_SUCCESS)
-                {
-                    lock (this)
-                    {
-                        _receiveHighwater++;
-                    }
-
-                    SendAckIfNecessary();
-                    return result;
-                }
-
-                if (!_packetEvent.Wait(timeoutInMilliseconds))
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnTimeoutError, string.Empty);
-                    return TdsEnums.SNI_WAIT_TIMEOUT;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Check SNI handle connection
-        /// </summary>
-        /// <returns>SNI error status</returns>
-        public override uint CheckConnection()
-        {
-            return _connection.CheckConnection();
-        }
-
-        /// <summary>
-        /// Set async callbacks
-        /// </summary>
-        /// <param name="receiveCallback">Receive callback</param>
-        /// <param name="sendCallback">Send callback</param>
-        public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
-        {
-        }
-
-        /// <summary>
-        /// Set buffer size
-        /// </summary>
-        /// <param name="bufferSize">Buffer size</param>
-        public override void SetBufferSize(int bufferSize)
-        {
-        }
-
-        /// <summary>
-        /// Enable SSL
-        /// </summary>
-        public override uint EnableSsl(uint options)
-        {
-            return _connection.EnableSsl(options);
-        }
-
-        /// <summary>
-        /// Disable SSL
-        /// </summary>
-        public override void DisableSsl()
-        {
-            _connection.DisableSsl();
-        }
-
-#if DEBUG
-        /// <summary>
-        /// Test handle for killing underlying connection
-        /// </summary>
-        public override void KillConnection()
-        {
-            _connection.KillConnection();
-        }
-#endif
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsQueuedPacket.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIMarsQueuedPacket.cs
deleted file mode 100644 (file)
index 355d373..0000000
+++ /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.
-
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// Mars queued packet
-    /// </summary>
-    internal class SNIMarsQueuedPacket
-    {
-        private SNIPacket _packet;
-        private SNIAsyncCallback _callback;
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="callback">Completion callback</param>
-        public SNIMarsQueuedPacket(SNIPacket packet, SNIAsyncCallback callback)
-        {
-            _packet = packet;
-            _callback = callback;
-        }
-
-        /// <summary>
-        /// SNI packet
-        /// </summary>
-        public SNIPacket Packet
-        {
-            get
-            {
-                return _packet;
-            }
-
-            set
-            {
-                _packet = value;
-            }
-        }
-
-        /// <summary>
-        /// Completion callback
-        /// </summary>
-        public SNIAsyncCallback Callback
-        {
-            get
-            {
-                return _callback;
-            }
-
-            set
-            {
-                _callback = value;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs
deleted file mode 100644 (file)
index 746ff6c..0000000
+++ /dev/null
@@ -1,314 +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.IO;
-using System.IO.Pipes;
-using System.Net.Security;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// Named Pipe connection handle
-    /// </summary>
-    internal sealed class SNINpHandle : SNIHandle
-    {
-        internal const string DefaultPipePath = @"sql\query"; // e.g. \\HOSTNAME\pipe\sql\query
-
-        private readonly string _targetServer;
-        private readonly object _callbackObject;
-
-        private Stream _stream;
-        private NamedPipeClientStream _pipeStream;
-        private SslOverTdsStream _sslOverTdsStream;
-        private SslStream _sslStream;
-        private SNIAsyncCallback _receiveCallback;
-        private SNIAsyncCallback _sendCallback;
-
-        private bool _validateCert = true;
-        private readonly uint _status = TdsEnums.SNI_UNINITIALIZED;
-        private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE;
-        private readonly Guid _connectionId = Guid.NewGuid();
-
-        public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject)
-        {
-            _targetServer = serverName;
-            _callbackObject = callbackObject;
-
-            try
-            {
-                _pipeStream = new NamedPipeClientStream(
-                    serverName,
-                    pipeName,
-                    PipeDirection.InOut,
-                    PipeOptions.Asynchronous | PipeOptions.WriteThrough);
-
-                bool isInfiniteTimeOut = long.MaxValue == timerExpire;
-                if (isInfiniteTimeOut)
-                {
-                    _pipeStream.Connect(Threading.Timeout.Infinite);
-                }
-                else
-                {
-                    TimeSpan ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
-                    ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
-
-                    _pipeStream.Connect((int)ts.TotalMilliseconds);
-                }
-            }
-            catch (TimeoutException te)
-            {
-                SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te);
-                _status = TdsEnums.SNI_ERROR;
-                return;
-            }
-            catch (IOException ioe)
-            {
-                SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe);
-                _status = TdsEnums.SNI_ERROR;
-                return;
-            }
-
-            if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead)
-            {
-                SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty);
-                _status = TdsEnums.SNI_ERROR;
-                return;
-            }
-
-            _sslOverTdsStream = new SslOverTdsStream(_pipeStream);
-            _sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
-
-            _stream = _pipeStream;
-            _status = TdsEnums.SNI_SUCCESS;
-        }
-
-        public override Guid ConnectionId
-        {
-            get
-            {
-                return _connectionId;
-            }
-        }
-
-        public override uint Status
-        {
-            get
-            {
-                return _status;
-            }
-        }
-
-        public override uint CheckConnection()
-        {
-            if (!_stream.CanWrite || !_stream.CanRead)
-            {
-                return TdsEnums.SNI_ERROR;
-            }
-            else
-            {
-                return TdsEnums.SNI_SUCCESS;
-            }
-        }
-
-        public override void Dispose()
-        {
-            lock (this)
-            {
-                if (_sslOverTdsStream != null)
-                {
-                    _sslOverTdsStream.Dispose();
-                    _sslOverTdsStream = null;
-                }
-
-                if (_sslStream != null)
-                {
-                    _sslStream.Dispose();
-                    _sslStream = null;
-                }
-
-                if (_pipeStream != null)
-                {
-                    _pipeStream.Dispose();
-                    _pipeStream = null;
-                }
-
-                //Release any references held by _stream.
-                _stream = null;
-            }
-        }
-
-        public override uint Receive(out SNIPacket packet, int timeout)
-        {
-            lock (this)
-            {
-                packet = null;
-                try
-                {
-                    packet = new SNIPacket(headerSize: 0, dataSize: _bufferSize);
-                    packet.ReadFromStream(_stream);
-
-                    if (packet.Length == 0)
-                    {
-                        var e = new Win32Exception();
-                        return ReportErrorAndReleasePacket(packet, (uint)e.NativeErrorCode, 0, e.Message);
-                    }
-                }
-                catch (ObjectDisposedException ode)
-                {
-                    return ReportErrorAndReleasePacket(packet, ode);
-                }
-                catch (IOException ioe)
-                {
-                    return ReportErrorAndReleasePacket(packet, ioe);
-                }
-
-                return TdsEnums.SNI_SUCCESS;
-            }
-        }
-
-        public override uint ReceiveAsync(ref SNIPacket packet)
-        {
-            packet = new SNIPacket(headerSize: 0, dataSize: _bufferSize);
-
-            try
-            {
-                packet.ReadFromStreamAsync(_stream, _receiveCallback);
-                return TdsEnums.SNI_SUCCESS_IO_PENDING;
-            }
-            catch (ObjectDisposedException ode)
-            {
-                return ReportErrorAndReleasePacket(packet, ode);
-            }
-            catch (IOException ioe)
-            {
-                return ReportErrorAndReleasePacket(packet, ioe);
-            }
-        }
-
-        public override uint Send(SNIPacket packet)
-        {
-            lock (this)
-            {
-                try
-                {
-                    packet.WriteToStream(_stream);
-                    return TdsEnums.SNI_SUCCESS;
-                }
-                catch (ObjectDisposedException ode)
-                {
-                    return ReportErrorAndReleasePacket(packet, ode);
-                }
-                catch (IOException ioe)
-                {
-                    return ReportErrorAndReleasePacket(packet, ioe);
-                }
-            }
-        }
-
-        public override uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null)
-        {
-            SNIAsyncCallback cb = callback ?? _sendCallback;
-            packet.WriteToStreamAsync(_stream, cb, SNIProviders.NP_PROV, disposePacketAfterSendAsync);
-            return TdsEnums.SNI_SUCCESS_IO_PENDING;
-        }
-
-        public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
-        {
-            _receiveCallback = receiveCallback;
-            _sendCallback = sendCallback;
-        }
-
-        public override uint EnableSsl(uint options)
-        {
-            _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
-
-            try
-            {
-                _sslStream.AuthenticateAsClientAsync(_targetServer).GetAwaiter().GetResult();
-                _sslOverTdsStream.FinishHandshake();
-            }
-            catch (AuthenticationException aue)
-            {
-                return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, aue);
-            }
-            catch (InvalidOperationException ioe)
-            {
-                return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, ioe);
-            }
-
-            _stream = _sslStream;
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        public override void DisableSsl()
-        {
-            _sslStream.Dispose();
-            _sslStream = null;
-            _sslOverTdsStream.Dispose();
-            _sslOverTdsStream = null;
-
-            _stream = _pipeStream;
-        }
-
-        /// <summary>
-        /// Validate server certificate
-        /// </summary>
-        /// <param name="sender">Sender object</param>
-        /// <param name="cert">X.509 certificate</param>
-        /// <param name="chain">X.509 chain</param>
-        /// <param name="policyErrors">Policy errors</param>
-        /// <returns>true if valid</returns>
-        private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
-        {
-            if (!_validateCert)
-            {
-                return true;
-            }
-
-            return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors);
-        }
-
-        /// <summary>
-        /// Set buffer size
-        /// </summary>
-        /// <param name="bufferSize">Buffer size</param>
-        public override void SetBufferSize(int bufferSize)
-        {
-            _bufferSize = bufferSize;
-        }
-
-        private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException)
-        {
-            if (packet != null)
-            {
-                packet.Release();
-            }
-            return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, sniException);
-        }
-
-        private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage)
-        {
-            if (packet != null)
-            {
-                packet.Release();
-            }
-            return SNICommon.ReportSNIError(SNIProviders.NP_PROV, nativeError, sniError, errorMessage);
-        }
-
-#if DEBUG
-        /// <summary>
-        /// Test handle for killing underlying connection
-        /// </summary>
-        public override void KillConnection()
-        {
-            _pipeStream.Dispose();
-            _pipeStream = null;
-        }
-#endif
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIPacket.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIPacket.cs
deleted file mode 100644 (file)
index 5f6edda..0000000
+++ /dev/null
@@ -1,264 +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.Buffers;
-using System.Diagnostics;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.SNI
-{
-    internal sealed class SNIPacket
-    {
-        private int _dataLength; // the length of the data in the data segment, advanced by Append-ing data, does not include smux header length
-        private int _dataCapacity; // the total capacity requested, if the array is rented this may be less than the _data.Length, does not include smux header length
-        private int _dataOffset; // the start point of the data in the data segment, advanced by Take-ing data
-        private int _headerLength; // the amount of space at the start of the array reserved for the smux header, this is zeroed in SetHeader
-                                   // _headerOffset is not needed because it is always 0
-        private byte[] _data;
-        private SNIAsyncCallback _completionCallback;
-
-        public SNIPacket(int headerSize, int dataSize)
-        {
-            Allocate(headerSize, dataSize);
-        }
-
-        /// <summary>
-        /// Length of data left to process
-        /// </summary>
-        public int DataLeft => (_dataLength - _dataOffset);
-
-        /// <summary>
-        /// Length of data
-        /// </summary>
-        public int Length => _dataLength;
-
-        /// <summary>
-        /// Packet validity
-        /// </summary>
-        public bool IsInvalid => _data is null;
-
-        public bool HasCompletionCallback => !(_completionCallback is null);
-
-        /// <summary>
-        /// Packet data
-        /// </summary>
-        public void Dispose() => Release();
-
-        public int ReservedHeaderSize => _headerLength;
-
-        /// <summary>
-        /// Set async completion callback
-        /// </summary>
-        /// <param name="completionCallback">Completion callback</param>
-        public void SetCompletionCallback(SNIAsyncCallback completionCallback)
-        {
-            _completionCallback = completionCallback;
-        }
-
-        /// <summary>
-        /// Invoke the completion callback
-        /// </summary>
-        /// <param name="sniErrorCode">SNI error</param>
-        public void InvokeCompletionCallback(uint sniErrorCode)
-        {
-            _completionCallback(this, sniErrorCode);
-        }
-
-        /// <summary>
-        /// Allocate space for data
-        /// </summary>
-        /// <param name="dataLength">Length of byte array to be allocated</param>
-        private void Allocate(int headerLength, int dataLength)
-        {
-            _data = ArrayPool<byte>.Shared.Rent(headerLength + dataLength);
-            _dataCapacity = dataLength;
-            _dataLength = 0;
-            _dataOffset = 0;
-            _headerLength = headerLength;
-        }
-
-        /// <summary>
-        /// Read packet data into a buffer without removing it from the packet
-        /// </summary>
-        /// <param name="buffer">Buffer</param>
-        /// <param name="dataSize">Number of bytes read from the packet into the buffer</param>
-        public void GetData(byte[] buffer, ref int dataSize)
-        {
-            Buffer.BlockCopy(_data, _headerLength, buffer, 0, _dataLength); // read from
-            dataSize = _dataLength;
-        }
-
-        /// <summary>
-        /// Take data from another packet
-        /// </summary>
-        /// <param name="packet">Packet</param>
-        /// <param name="size">Data to take</param>
-        /// <returns>Amount of data taken</returns>
-        public int TakeData(SNIPacket packet, int size)
-        {
-            int dataSize = TakeData(packet._data, packet._headerLength + packet._dataLength, size);
-            packet._dataLength += dataSize;
-            return dataSize;
-        }
-
-        /// <summary>
-        /// Append data
-        /// </summary>
-        /// <param name="data">Data</param>
-        /// <param name="size">Size</param>
-        public void AppendData(byte[] data, int size)
-        {
-            Buffer.BlockCopy(data, 0, _data, _headerLength + _dataLength, size);
-            _dataLength += size;
-        }
-
-        /// <summary>
-        /// Read data from the packet into the buffer at dataOffset for zize and then remove that data from the packet
-        /// </summary>
-        /// <param name="buffer">Buffer</param>
-        /// <param name="dataOffset">Data offset to write data at</param>
-        /// <param name="size">Number of bytes to read from the packet into the buffer</param>
-        /// <returns></returns>
-        public int TakeData(byte[] buffer, int dataOffset, int size)
-        {
-            if (_dataOffset >= _dataLength)
-            {
-                return 0;
-            }
-
-            if (_dataOffset + size > _dataLength)
-            {
-                size = _dataLength - _dataOffset;
-            }
-
-            Buffer.BlockCopy(_data, _headerLength + _dataOffset, buffer, dataOffset, size);
-            _dataOffset += size;
-            return size;
-        }
-
-        public Span<byte> GetHeaderBuffer(int headerSize)
-        {
-            Debug.Assert(_dataOffset == 0, "requested packet header buffer from partially consumed packet");
-            Debug.Assert(headerSize > 0, "requested packet header buffer of 0 length");
-            Debug.Assert(_headerLength == headerSize, "requested packet header of headerSize which is not equal to the _headerSize reservation");
-            return _data.AsSpan(0, headerSize);
-        }
-
-        public void SetHeaderActive()
-        {
-            Debug.Assert(_headerLength > 0, "requested to set header active when it is not reserved or is already active");
-            _dataCapacity += _headerLength;
-            _dataLength += _headerLength;
-            _headerLength = 0;
-        }
-
-        /// <summary>
-        /// Release packet
-        /// </summary>
-        public void Release()
-        {
-            if (_data != null)
-            {
-                Array.Clear(_data, 0, _headerLength + _dataLength);
-                ArrayPool<byte>.Shared.Return(_data, clearArray: false);
-                _data = null;
-                _dataCapacity = 0;
-            }
-            _dataLength = 0;
-            _dataOffset = 0;
-            _headerLength = 0;
-            _completionCallback = null;
-        }
-
-        /// <summary>
-        /// Read data from a stream asynchronously
-        /// </summary>
-        /// <param name="stream">Stream to read from</param>
-        /// <param name="callback">Completion callback</param>
-        public void ReadFromStreamAsync(Stream stream, SNIAsyncCallback callback)
-        {
-            bool error = false;
-
-            stream.ReadAsync(_data, 0, _dataCapacity, CancellationToken.None).ContinueWith(t =>
-            {
-                Exception e = t.Exception?.InnerException;
-                if (e != null)
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, e);
-                    error = true;
-                }
-                else
-                {
-                    _dataLength = t.Result;
-
-                    if (_dataLength == 0)
-                    {
-                        SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.ConnTerminatedError, string.Empty);
-                        error = true;
-                    }
-                }
-
-                if (error)
-                {
-                    Release();
-                }
-
-                callback(this, error ? TdsEnums.SNI_ERROR : TdsEnums.SNI_SUCCESS);
-            },
-            CancellationToken.None,
-            TaskContinuationOptions.DenyChildAttach,
-            TaskScheduler.Default);
-        }
-
-        /// <summary>
-        /// Read data from a stream synchronously
-        /// </summary>
-        /// <param name="stream">Stream to read from</param>
-        public void ReadFromStream(Stream stream)
-        {
-            _dataLength = stream.Read(_data, _headerLength, _dataCapacity);
-        }
-
-        /// <summary>
-        /// Write data to a stream asynchronously
-        /// </summary>
-        /// <param name="stream">Stream to write to</param>
-        /// <param name="callback">SNI Asynchronous Callback</param>
-        /// <param name="provider">SNI provider identifier</param>
-        /// <param name="disposeAfterWriteAsync">Bool flag to decide whether or not to dispose after Write Async operation</param>
-        public async void WriteToStreamAsync(Stream stream, SNIAsyncCallback callback, SNIProviders provider, bool disposeAfterWriteAsync = false)
-        {
-            uint status = TdsEnums.SNI_SUCCESS;
-            try
-            {
-                await stream.WriteAsync(_data, 0, _dataLength, CancellationToken.None).ConfigureAwait(false);
-            }
-            catch (Exception e)
-            {
-                SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, SNICommon.InternalExceptionError, e);
-                status = TdsEnums.SNI_ERROR;
-            }
-            callback(this, status);
-
-            if (disposeAfterWriteAsync)
-            {
-                Dispose();
-            }
-        }
-
-        /// <summary>
-        /// Write data to a stream synchronously
-        /// </summary>
-        /// <param name="stream">Stream to write to</param>
-        public void WriteToStream(Stream stream)
-        {
-            stream.Write(_data, _headerLength, _dataLength);
-        }
-
-    }
-
-
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIProxy.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIProxy.cs
deleted file mode 100644 (file)
index af8ba0c..0000000
+++ /dev/null
@@ -1,843 +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;
-#if NETCOREAPP2_1 || !NETCOREAPP
-using System.Linq;
-#endif
-using System.Net;
-using System.Net.Security;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading.Tasks;
-using System.IO;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient.
-    /// </summary>
-    internal partial class SNIProxy
-    {
-        private const int DefaultSqlServerPort = 1433;
-        private const int DefaultSqlServerDacPort = 1434;
-        private const string SqlServerSpnHeader = "MSSQLSvc/";
-
-        public static readonly SNIProxy Singleton = new SNIProxy();
-
-        /// <summary>
-        /// Terminate SNI
-        /// </summary>
-        public void Terminate()
-        {
-        }
-
-        /// <summary>
-        /// Enable SSL on a connection
-        /// </summary>
-        /// <param name="handle">Connection handle</param>
-        /// <returns>SNI error code</returns>
-        public uint EnableSsl(SNIHandle handle, uint options)
-        {
-            try
-            {
-                return handle.EnableSsl(options);
-            }
-            catch (Exception e)
-            {
-                return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e);
-            }
-        }
-
-        /// <summary>
-        /// Disable SSL on a connection
-        /// </summary>
-        /// <param name="handle">Connection handle</param>
-        /// <returns>SNI error code</returns>
-        public uint DisableSsl(SNIHandle handle)
-        {
-            handle.DisableSsl();
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Generate SSPI context
-        /// </summary>
-        /// <param name="sspiClientContextStatus">SSPI client context status</param>
-        /// <param name="receivedBuff">Receive buffer</param>
-        /// <param name="sendBuff">Send buffer</param>
-        /// <param name="serverName">Service Principal Name buffer</param>
-        public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName)
-        {
-            SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext;
-            ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags;
-            SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;
-
-            string securityPackage = NegotiationInfoClass.Negotiate;
-
-            if (securityContext == null)
-            {
-                credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false);
-            }
-
-            int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage);
-            byte[] resultToken = new byte[tokenSize];
-
-            ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
-                | ContextFlagsPal.Confidentiality
-                | ContextFlagsPal.Delegate
-                | ContextFlagsPal.MutualAuth;
-
-            string serverSPN = System.Text.Encoding.UTF8.GetString(serverName);
-
-            SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
-                       ref credentialsHandle,
-                       ref securityContext,
-                       serverSPN,
-                       requestedContextFlags,
-                       receivedBuff,
-                       null,
-                       ref resultToken,
-                       ref contextFlags);
-
-            if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
-                statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
-            {
-                statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, resultToken);
-                resultToken = null;
-            }
-
-            sendBuff = resultToken;
-            if (sendBuff == null)
-            {
-                sendBuff = Array.Empty<byte>();
-            }
-
-            sspiClientContextStatus.SecurityContext = securityContext;
-            sspiClientContextStatus.ContextFlags = contextFlags;
-            sspiClientContextStatus.CredentialsHandle = credentialsHandle;
-
-            if (IsErrorStatus(statusCode.ErrorCode))
-            {
-                // Could not access Kerberos Ticket.
-                //
-                // SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException,
-                // so we don't need to check for a GssApiException here.
-                if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError)
-                {
-                    throw new InvalidOperationException(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
-                }
-                else
-                {
-                    throw new InvalidOperationException(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
-                }
-            }
-        }
-
-        private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode)
-        {
-            return errorCode != SecurityStatusPalErrorCode.NotSet &&
-                errorCode != SecurityStatusPalErrorCode.OK &&
-                errorCode != SecurityStatusPalErrorCode.ContinueNeeded &&
-                errorCode != SecurityStatusPalErrorCode.CompleteNeeded &&
-                errorCode != SecurityStatusPalErrorCode.CompAndContinue &&
-                errorCode != SecurityStatusPalErrorCode.ContextExpired &&
-                errorCode != SecurityStatusPalErrorCode.CredentialsNeeded &&
-                errorCode != SecurityStatusPalErrorCode.Renegotiate;
-        }
-
-        /// <summary>
-        /// Initialize SSPI
-        /// </summary>
-        /// <param name="maxLength">Max length of SSPI packet</param>
-        /// <returns>SNI error code</returns>
-        public uint InitializeSspiPackage(ref uint maxLength)
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Set connection buffer size
-        /// </summary>
-        /// <param name="handle">SNI handle</param>
-        /// <param name="bufferSize">Buffer size</param>
-        /// <returns>SNI error code</returns>
-        public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize)
-        {
-            handle.SetBufferSize((int)bufferSize);
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Copies data in SNIPacket to given byte array parameter
-        /// </summary>
-        /// <param name="packet">SNIPacket object containing data packets</param>
-        /// <param name="inBuff">Destination byte array where data packets are copied to</param>
-        /// <param name="dataSize">Length of data packets</param>
-        /// <returns>SNI error status</returns>
-        public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize)
-        {
-            int dataSizeInt = 0;
-            packet.GetData(inBuff, ref dataSizeInt);
-            dataSize = (uint)dataSizeInt;
-
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Read synchronously
-        /// </summary>
-        /// <param name="handle">SNI handle</param>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="timeout">Timeout</param>
-        /// <returns>SNI error status</returns>
-        public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout)
-        {
-            return handle.Receive(out packet, timeout);
-        }
-
-        /// <summary>
-        /// Get SNI connection ID
-        /// </summary>
-        /// <param name="handle">SNI handle</param>
-        /// <param name="clientConnectionId">Client connection ID</param>
-        /// <returns>SNI error status</returns>
-        public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId)
-        {
-            clientConnectionId = handle.ConnectionId;
-
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Send a packet
-        /// </summary>
-        /// <param name="handle">SNI handle</param>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="sync">true if synchronous, false if asynchronous</param>
-        /// <returns>SNI error status</returns>
-        public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync)
-        {
-            uint result;
-            if (sync)
-            {
-                result = handle.Send(packet);
-                packet.Release();
-            }
-            else
-            {
-                result = handle.SendAsync(packet, true);
-            }
-
-            return result;
-        }
-
-        /// <summary>
-        /// Create a SNI connection handle
-        /// </summary>
-        /// <param name="callbackObject">Asynchronous I/O callback object</param>
-        /// <param name="fullServerName">Full server name from connection string</param>
-        /// <param name="ignoreSniOpenTimeout">Ignore open timeout</param>
-        /// <param name="timerExpire">Timer expiration</param>
-        /// <param name="instanceName">Instance name</param>
-        /// <param name="spnBuffer">SPN</param>
-        /// <param name="flushCache">Flush packet cache</param>
-        /// <param name="async">Asynchronous connection</param>
-        /// <param name="parallel">Attempt parallel connects</param>
-        /// <returns>SNI handle</returns>
-        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)
-        {
-            instanceName = new byte[1];
-
-            bool errorWithLocalDBProcessing;
-            string localDBDataSource = GetLocalDBDataSource(fullServerName, out errorWithLocalDBProcessing);
-
-            if (errorWithLocalDBProcessing)
-            {
-                return null;
-            }
-
-            // If a localDB Data source is available, we need to use it.
-            fullServerName = localDBDataSource ?? fullServerName;
-
-            DataSource details = DataSource.ParseServerName(fullServerName);
-            if (details == null)
-            {
-                return null;
-            }
-
-            SNIHandle sniHandle = null;
-            switch (details.ConnectionProtocol)
-            {
-                case DataSource.Protocol.Admin:
-                case DataSource.Protocol.None: // default to using tcp if no protocol is provided
-                case DataSource.Protocol.TCP:
-                    sniHandle = CreateTcpHandle(details, timerExpire, callbackObject, parallel);
-                    break;
-                case DataSource.Protocol.NP:
-                    sniHandle = CreateNpHandle(details, timerExpire, callbackObject, parallel);
-                    break;
-                default:
-                    Debug.Fail($"Unexpected connection protocol: {details.ConnectionProtocol}");
-                    break;
-            }
-
-            if (isIntegratedSecurity)
-            {
-                try
-                {
-                    spnBuffer = GetSqlServerSPN(details);
-                }
-                catch (Exception e)
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, SNICommon.ErrorSpnLookup, e);
-                }
-            }
-
-            return sniHandle;
-        }
-
-        private static byte[] GetSqlServerSPN(DataSource dataSource)
-        {
-            Debug.Assert(!string.IsNullOrWhiteSpace(dataSource.ServerName));
-
-            string hostName = dataSource.ServerName;
-            string postfix = null;
-            if (dataSource.Port != -1)
-            {
-                postfix = dataSource.Port.ToString();
-            }
-            else if (!string.IsNullOrWhiteSpace(dataSource.InstanceName))
-            {
-                postfix = dataSource.InstanceName;
-            }
-            // For handling tcp:<hostname> format
-            else if (dataSource.ConnectionProtocol == DataSource.Protocol.TCP)
-            {
-                postfix = DefaultSqlServerPort.ToString();
-            }
-
-            return GetSqlServerSPN(hostName, postfix);
-        }
-
-        private static byte[] GetSqlServerSPN(string hostNameOrAddress, string portOrInstanceName)
-        {
-            Debug.Assert(!string.IsNullOrWhiteSpace(hostNameOrAddress));
-            IPHostEntry hostEntry = null;
-            string fullyQualifiedDomainName;
-            try
-            {
-                hostEntry = Dns.GetHostEntry(hostNameOrAddress);
-            }
-            catch (SocketException)
-            {
-                // A SocketException can occur while resolving the hostname.
-                // We will fallback on using hostname from the connection string in the finally block
-            }
-            finally
-            {
-                // If the DNS lookup failed, then resort to using the user provided hostname to construct the SPN.
-                fullyQualifiedDomainName = hostEntry?.HostName ?? hostNameOrAddress;
-            }
-            string serverSpn = SqlServerSpnHeader + fullyQualifiedDomainName;
-            if (!string.IsNullOrWhiteSpace(portOrInstanceName))
-            {
-                serverSpn += ":" + portOrInstanceName;
-            }
-            return Encoding.UTF8.GetBytes(serverSpn);
-        }
-
-        /// <summary>
-        /// Creates an SNITCPHandle object
-        /// </summary>
-        /// <param name="details">Data source</param>
-        /// <param name="timerExpire">Timer expiration</param>
-        /// <param name="callbackObject">Asynchronous I/O callback object</param>
-        /// <param name="parallel">Should MultiSubnetFailover be used</param>
-        /// <returns>SNITCPHandle</returns>
-        private SNITCPHandle CreateTcpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel)
-        {
-            // TCP Format:
-            // tcp:<host name>\<instance name>
-            // tcp:<host name>,<TCP/IP port number>
-
-            string hostName = details.ServerName;
-            if (string.IsNullOrWhiteSpace(hostName))
-            {
-                SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
-                return null;
-            }
-
-            int port = -1;
-            bool isAdminConnection = details.ConnectionProtocol == DataSource.Protocol.Admin;
-            if (details.IsSsrpRequired)
-            {
-                try
-                {
-                    port = isAdminConnection ?
-                            SSRP.GetDacPortByInstanceName(hostName, details.InstanceName) :
-                            SSRP.GetPortByInstanceName(hostName, details.InstanceName);
-                }
-                catch (SocketException se)
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, se);
-                    return null;
-                }
-            }
-            else if (details.Port != -1)
-            {
-                port = details.Port;
-            }
-            else
-            {
-                port = isAdminConnection ? DefaultSqlServerDacPort : DefaultSqlServerPort;
-            }
-
-            return new SNITCPHandle(hostName, port, timerExpire, callbackObject, parallel);
-        }
-
-        /// <summary>
-        /// Creates an SNINpHandle object
-        /// </summary>
-        /// <param name="details">Data source</param>
-        /// <param name="timerExpire">Timer expiration</param>
-        /// <param name="callbackObject">Asynchronous I/O callback object</param>
-        /// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param>
-        /// <returns>SNINpHandle</returns>
-        private SNINpHandle CreateNpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel)
-        {
-            if (parallel)
-            {
-                SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty);
-                return null;
-            }
-            return new SNINpHandle(details.PipeHostName, details.PipeName, timerExpire, callbackObject);
-        }
-
-        /// <summary>
-        /// Read packet asynchronously
-        /// </summary>
-        /// <param name="handle">SNI handle</param>
-        /// <param name="packet">Packet</param>
-        /// <returns>SNI error status</returns>
-        public uint ReadAsync(SNIHandle handle, out SNIPacket packet)
-        {
-            packet = null;
-            return handle.ReceiveAsync(ref packet);
-        }
-
-        /// <summary>
-        /// Set packet data
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="data">Data</param>
-        /// <param name="length">Length</param>
-        public void PacketSetData(SNIPacket packet, byte[] data, int length)
-        {
-            packet.AppendData(data, length);
-        }
-
-        /// <summary>
-        /// Release packet
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        public void PacketRelease(SNIPacket packet)
-        {
-            packet.Release();
-        }
-
-        /// <summary>
-        /// Check SNI handle connection
-        /// </summary>
-        /// <param name="handle"></param>
-        /// <returns>SNI error status</returns>
-        public uint CheckConnection(SNIHandle handle)
-        {
-            return handle.CheckConnection();
-        }
-
-        /// <summary>
-        /// Get last SNI error on this thread
-        /// </summary>
-        /// <returns></returns>
-        public SNIError GetLastError()
-        {
-            return SNILoadHandle.SingletonInstance.LastError;
-        }
-
-        /// <summary>
-        /// Gets the Local db Named pipe data source if the input is a localDB server.
-        /// </summary>
-        /// <param name="fullServerName">The data source</param>
-        /// <param name="error">Set true when an error occurred while getting LocalDB up</param>
-        /// <returns></returns>
-        private string GetLocalDBDataSource(string fullServerName, out bool error)
-        {
-            string localDBConnectionString = null;
-            bool isBadLocalDBDataSource;
-            string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out isBadLocalDBDataSource);
-
-            if (isBadLocalDBDataSource)
-            {
-                error = true;
-                return null;
-            }
-
-            else if (!string.IsNullOrEmpty(localDBInstance))
-            {
-                // We have successfully received a localDBInstance which is valid.
-                Debug.Assert(!string.IsNullOrWhiteSpace(localDBInstance), "Local DB Instance name cannot be empty.");
-                localDBConnectionString = LocalDB.GetLocalDBConnectionString(localDBInstance);
-
-                if (fullServerName == null)
-                {
-                    // The Last error is set in LocalDB.GetLocalDBConnectionString. We don't need to set Last here.
-                    error = true;
-                    return null;
-                }
-            }
-            error = false;
-            return localDBConnectionString;
-        }
-    }
-
-    internal class DataSource
-    {
-        private const char BackSlashSeparator = '\\';
-        private const string DefaultHostName = "localhost";
-        private const string DefaultSqlServerInstanceName = "mssqlserver";
-        private const string PipeBeginning = @"\\";
-        private const string PipeToken = "pipe";
-        private const string LocalDbHost = "(localdb)";
-        private const string NamedPipeInstanceNameHeader = "mssql$";
-        private const string DefaultPipeName = "sql\\query";
-
-        internal enum Protocol { TCP, NP, None, Admin };
-
-        internal Protocol ConnectionProtocol = Protocol.None;
-
-        /// <summary>
-        /// Provides the HostName of the server to connect to for TCP protocol.
-        /// This information is also used for finding the SPN of SqlServer
-        /// </summary>
-        internal string ServerName { get; private set; }
-
-        /// <summary>
-        /// Provides the port on which the TCP connection should be made if one was specified in Data Source
-        /// </summary>
-        internal int Port { get; private set; } = -1;
-
-        /// <summary>
-        /// Provides the inferred Instance Name from Server Data Source
-        /// </summary>
-        public string InstanceName { get; internal set; }
-
-        /// <summary>
-        /// Provides the pipe name in case of Named Pipes
-        /// </summary>
-        public string PipeName { get; internal set; }
-
-        /// <summary>
-        /// Provides the HostName to connect to in case of Named pipes Data Source
-        /// </summary>
-        public string PipeHostName { get; internal set; }
-
-        private readonly string _workingDataSource;
-        private readonly string _dataSourceAfterTrimmingProtocol;
-        internal bool IsBadDataSource { get; private set; } = false;
-
-        internal bool IsSsrpRequired { get; private set; } = false;
-
-        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(':');
-
-            PopulateProtocol();
-
-            _dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && ConnectionProtocol != DataSource.Protocol.None
-                ? _workingDataSource.Substring(firstIndexOfColon + 1).Trim() : _workingDataSource;
-
-            // Pipe paths only allow back slashes
-#if NETCOREAPP
-            if (_dataSourceAfterTrimmingProtocol.Contains('/')) // string.Contains(char) is .NetCore2.1+ specific
-#else
-            if (_dataSourceAfterTrimmingProtocol.Contains("/"))
-#endif
-            {
-                if (ConnectionProtocol == DataSource.Protocol.None)
-                    ReportSNIError(SNIProviders.INVALID_PROV);
-                else if (ConnectionProtocol == DataSource.Protocol.NP)
-                    ReportSNIError(SNIProviders.NP_PROV);
-                else if (ConnectionProtocol == DataSource.Protocol.TCP)
-                    ReportSNIError(SNIProviders.TCP_PROV);
-            }
-        }
-
-        private void PopulateProtocol()
-        {
-            string[] splitByColon = _workingDataSource.Split(':');
-
-            if (splitByColon.Length <= 1)
-            {
-                ConnectionProtocol = DataSource.Protocol.None;
-            }
-            else
-            {
-                // We trim before switching because " tcp : server , 1433 " is a valid data source
-                ConnectionProtocol = splitByColon[0].Trim() switch
-                {
-                    TdsEnums.TCP => DataSource.Protocol.TCP,
-                    TdsEnums.NP => DataSource.Protocol.NP,
-                    TdsEnums.ADMIN => DataSource.Protocol.Admin,
-                    _ => DataSource.Protocol.None, // None of the supported protocols were found. This may be an IPv6 address.
-                };
-            }
-        }
-
-        public static string GetLocalDBInstance(string dataSource, out bool error)
-        {
-            string instanceName = null;
-
-            string workingDataSource = dataSource.ToLowerInvariant();
-
-            string[] tokensByBackSlash = workingDataSource.Split(BackSlashSeparator);
-
-            error = false;
-
-            // All LocalDb endpoints are of the format host\instancename where host is always (LocalDb) (case-insensitive)
-            if (tokensByBackSlash.Length == 2 && LocalDbHost.Equals(tokensByBackSlash[0].TrimStart()))
-            {
-                if (!string.IsNullOrWhiteSpace(tokensByBackSlash[1]))
-                {
-                    instanceName = tokensByBackSlash[1].Trim();
-                }
-                else
-                {
-                    SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBNoInstanceName, string.Empty);
-                    error = true;
-                    return null;
-                }
-            }
-
-            return instanceName;
-        }
-
-        public static DataSource ParseServerName(string dataSource)
-        {
-            DataSource details = new DataSource(dataSource);
-
-            if (details.IsBadDataSource)
-            {
-                return null;
-            }
-
-            if (details.InferNamedPipesInformation())
-            {
-                return details;
-            }
-
-            if (details.IsBadDataSource)
-            {
-                return null;
-            }
-
-            if (details.InferConnectionDetails())
-            {
-                return details;
-            }
-
-            return null;
-        }
-
-        private void InferLocalServerName()
-        {
-            // If Server name is empty or localhost, then use "localhost"
-            if (string.IsNullOrEmpty(ServerName) || IsLocalHost(ServerName))
-            {
-                ServerName = ConnectionProtocol == DataSource.Protocol.Admin ?
-                    Environment.MachineName : DefaultHostName;
-            }
-        }
-
-        private bool InferConnectionDetails()
-        {
-            string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator, ',');
-            ServerName = tokensByCommaAndSlash[0].Trim();
-
-            int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(',');
-
-            int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(BackSlashSeparator);
-
-            // 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
-            if (commaIndex > -1)
-            {
-                string parameter = backSlashIndex > -1
-                        ? ((commaIndex > backSlashIndex) ? tokensByCommaAndSlash[2].Trim() : tokensByCommaAndSlash[1].Trim())
-                        : tokensByCommaAndSlash[1].Trim();
-
-                // Bad Data Source like "server, "
-                if (string.IsNullOrEmpty(parameter))
-                {
-                    ReportSNIError(SNIProviders.INVALID_PROV);
-                    return false;
-                }
-
-                // For Tcp and Only Tcp are parameters allowed.
-                if (ConnectionProtocol == DataSource.Protocol.None)
-                {
-                    ConnectionProtocol = DataSource.Protocol.TCP;
-                }
-                else if (ConnectionProtocol != DataSource.Protocol.TCP)
-                {
-                    // Parameter has been specified for non-TCP protocol. This is not allowed.
-                    ReportSNIError(SNIProviders.INVALID_PROV);
-                    return false;
-                }
-
-                int port;
-                if (!int.TryParse(parameter, out port))
-                {
-                    ReportSNIError(SNIProviders.TCP_PROV);
-                    return false;
-                }
-
-                // If the user explicitly specified a invalid port in the connection string.
-                if (port < 1)
-                {
-                    ReportSNIError(SNIProviders.TCP_PROV);
-                    return false;
-                }
-
-                Port = port;
-            }
-            // Instance Name Handling. Only if we found a '\' and we did not find a port in the Data Source
-            else if (backSlashIndex > -1)
-            {
-                // This means that there will not be any part separated by comma.
-                InstanceName = tokensByCommaAndSlash[1].Trim();
-
-                if (string.IsNullOrWhiteSpace(InstanceName))
-                {
-                    ReportSNIError(SNIProviders.INVALID_PROV);
-                    return false;
-                }
-
-                if (DefaultSqlServerInstanceName.Equals(InstanceName))
-                {
-                    ReportSNIError(SNIProviders.INVALID_PROV);
-                    return false;
-                }
-
-                IsSsrpRequired = true;
-            }
-
-            InferLocalServerName();
-
-            return true;
-        }
-
-        private void ReportSNIError(SNIProviders provider)
-        {
-            SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, 0, SNICommon.InvalidConnStringError, string.Empty);
-            IsBadDataSource = true;
-        }
-
-        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 the data source is "np:servername"
-                if (!_dataSourceAfterTrimmingProtocol.Contains(BackSlashSeparator)) // string.Contains(char) is .NetCore2.1+ specific. Else uses Linq (perf warning)
-                {
-                    PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol;
-                    InferLocalServerName();
-                    PipeName = SNINpHandle.DefaultPipePath;
-                    return true;
-                }
-
-                try
-                {
-                    string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator);
-
-                    // The datasource is of the format \\host\pipe\sql\query [0]\[1]\[2]\[3]\[4]\[5]
-                    // It would at least have 6 parts.
-                    // Another valid Sql named pipe for an named instance is \\.\pipe\MSSQL$MYINSTANCE\sql\query
-                    if (tokensByBackSlash.Length < 6)
-                    {
-                        ReportSNIError(SNIProviders.NP_PROV);
-                        return false;
-                    }
-
-                    string host = tokensByBackSlash[2];
-
-                    if (string.IsNullOrEmpty(host))
-                    {
-                        ReportSNIError(SNIProviders.NP_PROV);
-                        return false;
-                    }
-
-                    //Check if the "pipe" keyword is the first part of path
-                    if (!PipeToken.Equals(tokensByBackSlash[3]))
-                    {
-                        ReportSNIError(SNIProviders.NP_PROV);
-                        return false;
-                    }
-
-                    if (tokensByBackSlash[4].StartsWith(NamedPipeInstanceNameHeader))
-                    {
-                        InstanceName = tokensByBackSlash[4].Substring(NamedPipeInstanceNameHeader.Length);
-                    }
-
-                    StringBuilder pipeNameBuilder = new StringBuilder();
-
-                    for (int i = 4; i < tokensByBackSlash.Length - 1; i++)
-                    {
-                        pipeNameBuilder.Append(tokensByBackSlash[i]);
-                        pipeNameBuilder.Append(Path.DirectorySeparatorChar);
-                    }
-                    // Append the last part without a "/"
-                    pipeNameBuilder.Append(tokensByBackSlash[tokensByBackSlash.Length - 1]);
-                    PipeName = pipeNameBuilder.ToString();
-
-                    if (string.IsNullOrWhiteSpace(InstanceName) && !DefaultPipeName.Equals(PipeName))
-                    {
-                        InstanceName = PipeToken + PipeName;
-                    }
-
-                    ServerName = IsLocalHost(host) ? Environment.MachineName : host;
-                    // Pipe hostname is the hostname after leading \\ which should be passed down as is to open Named Pipe.
-                    // For Named Pipes the ServerName makes sense for SPN creation only.
-                    PipeHostName = host;
-                }
-                catch (UriFormatException)
-                {
-                    ReportSNIError(SNIProviders.NP_PROV);
-                    return false;
-                }
-
-                // DataSource is something like "\\pipename"
-                if (ConnectionProtocol == DataSource.Protocol.None)
-                {
-                    ConnectionProtocol = DataSource.Protocol.NP;
-                }
-                else if (ConnectionProtocol != DataSource.Protocol.NP)
-                {
-                    // In case the path began with a "\\" and protocol was not Named Pipes
-                    ReportSNIError(SNIProviders.NP_PROV);
-                    return false;
-                }
-                return true;
-            }
-            return false;
-        }
-
-        private static bool IsLocalHost(string serverName)
-            => ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.Unix.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.Unix.cs
deleted file mode 100644 (file)
index c73cb6e..0000000
+++ /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.Collections.Generic;
-using System.Net.Sockets;
-using System.Text;
-
-namespace System.Data.SqlClient.SNI
-{
-    internal partial class SNITcpHandle
-    {
-        internal static void SetKeepAliveValues(ref Socket socket)
-        {
-#if FEATURE_TCPKEEPALIVE
-            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
-            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 1);
-            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 30);
-#endif
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.Windows.cs
deleted file mode 100644 (file)
index 15c4417..0000000
+++ /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.Collections.Generic;
-using System.Net.Sockets;
-using System.Text;
-
-namespace System.Data.SqlClient.SNI
-{
-    internal partial class SNITcpHandle
-    {
-        internal static void SetKeepAliveValues(ref Socket socket)
-        {
-            //This method will later be setting the KeepAlive, TcpKeepAliveInterval and TcpKeepAliveTime based on Windows platform specific checks.
-            // Link to issue: https://github.com/dotnet/corefx/issues/33209
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.cs
deleted file mode 100644 (file)
index 219809b..0000000
+++ /dev/null
@@ -1,643 +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.Generic;
-using System.ComponentModel;
-using System.IO;
-using System.Net;
-using System.Net.Security;
-using System.Net.Sockets;
-using System.Runtime.CompilerServices;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// TCP connection handle
-    /// </summary>
-    internal sealed class SNITCPHandle : SNIHandle
-    {
-        private readonly string _targetServer;
-        private readonly object _callbackObject;
-        private readonly Socket _socket;
-        private NetworkStream _tcpStream;
-
-        private Stream _stream;
-        private SslStream _sslStream;
-        private SslOverTdsStream _sslOverTdsStream;
-        private SNIAsyncCallback _receiveCallback;
-        private SNIAsyncCallback _sendCallback;
-
-        private bool _validateCert = true;
-        private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE;
-        private uint _status = TdsEnums.SNI_UNINITIALIZED;
-        private Guid _connectionId = Guid.NewGuid();
-
-        private const int MaxParallelIpAddresses = 64;
-
-        /// <summary>
-        /// Dispose object
-        /// </summary>
-        public override void Dispose()
-        {
-            lock (this)
-            {
-                if (_sslOverTdsStream != null)
-                {
-                    _sslOverTdsStream.Dispose();
-                    _sslOverTdsStream = null;
-                }
-
-                if (_sslStream != null)
-                {
-                    _sslStream.Dispose();
-                    _sslStream = null;
-                }
-
-                if (_tcpStream != null)
-                {
-                    _tcpStream.Dispose();
-                    _tcpStream = null;
-                }
-
-                //Release any references held by _stream.
-                _stream = null;
-            }
-        }
-
-        /// <summary>
-        /// Connection ID
-        /// </summary>
-        public override Guid ConnectionId
-        {
-            get
-            {
-                return _connectionId;
-            }
-        }
-
-        /// <summary>
-        /// Connection status
-        /// </summary>
-        public override uint Status
-        {
-            get
-            {
-                return _status;
-            }
-        }
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="serverName">Server name</param>
-        /// <param name="port">TCP port number</param>
-        /// <param name="timerExpire">Connection timer expiration</param>
-        /// <param name="callbackObject">Callback object</param>
-        public SNITCPHandle(string serverName, int port, long timerExpire, object callbackObject, bool parallel)
-        {
-            _callbackObject = callbackObject;
-            _targetServer = serverName;
-
-            try
-            {
-                TimeSpan ts = default(TimeSpan);
-
-                // In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
-                // The infinite Timeout is a function of ConnectionString Timeout=0
-                bool isInfiniteTimeOut = long.MaxValue == timerExpire;
-                if (!isInfiniteTimeOut)
-                {
-                    ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
-                    ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
-                }
-
-                Task<Socket> connectTask;
-                if (parallel)
-                {
-                    Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName);
-                    serverAddrTask.Wait(ts);
-                    IPAddress[] serverAddresses = serverAddrTask.Result;
-
-                    if (serverAddresses.Length > MaxParallelIpAddresses)
-                    {
-                        // Fail if above 64 to match legacy behavior
-                        ReportTcpSNIError(0, SNICommon.MultiSubnetFailoverWithMoreThan64IPs, string.Empty);
-                        return;
-                    }
-
-                    connectTask = ParallelConnectAsync(serverAddresses, port);
-
-                    if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts)))
-                    {
-                        ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
-                        return;
-                    }
-
-                    _socket = connectTask.Result;
-                }
-                else
-                {
-                    _socket = Connect(serverName, port, ts, isInfiniteTimeOut);
-                }
-
-                if (_socket == null || !_socket.Connected)
-                {
-                    if (_socket != null)
-                    {
-                        _socket.Dispose();
-                        _socket = null;
-                    }
-                    ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
-                    return;
-                }
-
-                _socket.NoDelay = true;
-                _tcpStream = new NetworkStream(_socket, true);
-
-                _sslOverTdsStream = new SslOverTdsStream(_tcpStream);
-                _sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
-            }
-            catch (SocketException se)
-            {
-                ReportTcpSNIError(se);
-                return;
-            }
-            catch (Exception e)
-            {
-                ReportTcpSNIError(e);
-                return;
-            }
-
-            _stream = _tcpStream;
-            _status = TdsEnums.SNI_SUCCESS;
-        }
-
-        private static Socket Connect(string serverName, int port, TimeSpan timeout, bool isInfiniteTimeout)
-        {
-            IPAddress[] ipAddresses = Dns.GetHostAddresses(serverName);
-            IPAddress serverIPv4 = null;
-            IPAddress serverIPv6 = null;
-            foreach (IPAddress ipAddress in ipAddresses)
-            {
-                if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
-                {
-                    serverIPv4 = ipAddress;
-                }
-                else if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
-                {
-                    serverIPv6 = ipAddress;
-                }
-            }
-            ipAddresses = new IPAddress[] { serverIPv4, serverIPv6 };
-            Socket[] sockets = new Socket[2];
-
-            CancellationTokenSource cts = null;
-
-            void Cancel()
-            {
-                for (int i = 0; i < sockets.Length; ++i)
-                {
-                    try
-                    {
-                        if (sockets[i] != null && !sockets[i].Connected)
-                        {
-                            sockets[i].Dispose();
-                            sockets[i] = null;
-                        }
-                    }
-                    catch { }
-                }
-            }
-
-            if (!isInfiniteTimeout)
-            {
-                cts = new CancellationTokenSource(timeout);
-                cts.Token.Register(Cancel);
-            }
-
-            Socket availableSocket = null;
-            try
-            {
-                for (int i = 0; i < sockets.Length; ++i)
-                {
-                    try
-                    {
-                        if (ipAddresses[i] != null)
-                        {
-                            sockets[i] = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
-                            // enable keep-alive on socket
-                            SNITcpHandle.SetKeepAliveValues(ref sockets[i]);
-                            sockets[i].Connect(ipAddresses[i], port);
-                            if (sockets[i] != null) // sockets[i] can be null if cancel callback is executed during connect()
-                            {
-                                if (sockets[i].Connected)
-                                {
-                                    availableSocket = sockets[i];
-                                    break;
-                                }
-                                else
-                                {
-                                    sockets[i].Dispose();
-                                    sockets[i] = null;
-                                }
-                            }
-                        }
-                    }
-                    catch { }
-                }
-            }
-            finally
-            {
-                cts?.Dispose();
-            }
-
-            return availableSocket;
-        }
-
-        private static Task<Socket> ParallelConnectAsync(IPAddress[] serverAddresses, int port)
-        {
-            if (serverAddresses == null)
-            {
-                throw new ArgumentNullException(nameof(serverAddresses));
-            }
-            if (serverAddresses.Length == 0)
-            {
-                throw new ArgumentOutOfRangeException(nameof(serverAddresses));
-            }
-
-            var sockets = new List<Socket>(serverAddresses.Length);
-            var connectTasks = new List<Task>(serverAddresses.Length);
-            var tcs = new TaskCompletionSource<Socket>();
-            var lastError = new StrongBox<Exception>();
-            var pendingCompleteCount = new StrongBox<int>(serverAddresses.Length);
-
-            foreach (IPAddress address in serverAddresses)
-            {
-                var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
-                sockets.Add(socket);
-
-                // Start all connection tasks now, to prevent possible race conditions with
-                // calling ConnectAsync on disposed sockets.
-                try
-                {
-                    connectTasks.Add(socket.ConnectAsync(address, port));
-                }
-                catch (Exception e)
-                {
-                    connectTasks.Add(Task.FromException(e));
-                }
-            }
-
-            for (int i = 0; i < sockets.Count; i++)
-            {
-                ParallelConnectHelper(sockets[i], connectTasks[i], tcs, pendingCompleteCount, lastError, sockets);
-            }
-
-            return tcs.Task;
-        }
-
-        private static async void ParallelConnectHelper(
-            Socket socket,
-            Task connectTask,
-            TaskCompletionSource<Socket> tcs,
-            StrongBox<int> pendingCompleteCount,
-            StrongBox<Exception> lastError,
-            List<Socket> sockets)
-        {
-            bool success = false;
-            try
-            {
-                // Try to connect.  If we're successful, store this task into the result task.
-                await connectTask.ConfigureAwait(false);
-                success = tcs.TrySetResult(socket);
-                if (success)
-                {
-                    // Whichever connection completes the return task is responsible for disposing
-                    // all of the sockets (except for whichever one is stored into the result task).
-                    // This ensures that only one thread will attempt to dispose of a socket.
-                    // This is also the closest thing we have to canceling connect attempts.
-                    foreach (Socket otherSocket in sockets)
-                    {
-                        if (otherSocket != socket)
-                        {
-                            otherSocket.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                // Store an exception to be published if no connection succeeds
-                Interlocked.Exchange(ref lastError.Value, e);
-            }
-            finally
-            {
-                // If we didn't successfully transition the result task to completed,
-                // then someone else did and they would have cleaned up, so there's nothing
-                // more to do.  Otherwise, no one completed it yet or we failed; either way,
-                // see if we're the last outstanding connection, and if we are, try to complete
-                // the task, and if we're successful, it's our responsibility to dispose all of the sockets.
-                if (!success && Interlocked.Decrement(ref pendingCompleteCount.Value) == 0)
-                {
-                    if (lastError.Value != null)
-                    {
-                        tcs.TrySetException(lastError.Value);
-                    }
-                    else
-                    {
-                        tcs.TrySetCanceled();
-                    }
-
-                    foreach (Socket s in sockets)
-                    {
-                        s.Dispose();
-                    }
-                }
-            }
-        }
-
-        /// <summary>
-        /// Enable SSL
-        /// </summary>
-        public override uint EnableSsl(uint options)
-        {
-            _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
-
-            try
-            {
-                _sslStream.AuthenticateAsClient(_targetServer);
-                _sslOverTdsStream.FinishHandshake();
-            }
-            catch (AuthenticationException aue)
-            {
-                return ReportTcpSNIError(aue);
-            }
-            catch (InvalidOperationException ioe)
-            {
-                return ReportTcpSNIError(ioe);
-            }
-
-            _stream = _sslStream;
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        /// <summary>
-        /// Disable SSL
-        /// </summary>
-        public override void DisableSsl()
-        {
-            _sslStream.Dispose();
-            _sslStream = null;
-            _sslOverTdsStream.Dispose();
-            _sslOverTdsStream = null;
-            _stream = _tcpStream;
-        }
-
-        /// <summary>
-        /// Validate server certificate callback
-        /// </summary>
-        /// <param name="sender">Sender object</param>
-        /// <param name="cert">X.509 certificate</param>
-        /// <param name="chain">X.509 chain</param>
-        /// <param name="policyErrors">Policy errors</param>
-        /// <returns>True if certificate is valid</returns>
-        private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
-        {
-            if (!_validateCert)
-            {
-                return true;
-            }
-
-            return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors);
-        }
-
-        /// <summary>
-        /// Set buffer size
-        /// </summary>
-        /// <param name="bufferSize">Buffer size</param>
-        public override void SetBufferSize(int bufferSize)
-        {
-            _bufferSize = bufferSize;
-        }
-
-        /// <summary>
-        /// Send a packet synchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        public override uint Send(SNIPacket packet)
-        {
-            lock (this)
-            {
-                try
-                {
-                    packet.WriteToStream(_stream);
-                    return TdsEnums.SNI_SUCCESS;
-                }
-                catch (ObjectDisposedException ode)
-                {
-                    return ReportTcpSNIError(ode);
-                }
-                catch (SocketException se)
-                {
-                    return ReportTcpSNIError(se);
-                }
-                catch (IOException ioe)
-                {
-                    return ReportTcpSNIError(ioe);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Receive a packet synchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param>
-        /// <returns>SNI error code</returns>
-        public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
-        {
-            lock (this)
-            {
-                packet = null;
-                try
-                {
-                    if (timeoutInMilliseconds > 0)
-                    {
-                        _socket.ReceiveTimeout = timeoutInMilliseconds;
-                    }
-                    else if (timeoutInMilliseconds == -1)
-                    {   // SqlCient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0
-                        _socket.ReceiveTimeout = 0;
-                    }
-                    else
-                    {
-                        // otherwise it is timeout for 0 or less than -1
-                        ReportTcpSNIError(0, SNICommon.ConnTimeoutError, string.Empty);
-                        return TdsEnums.SNI_WAIT_TIMEOUT;
-                    }
-
-                    packet = new SNIPacket(headerSize: 0, dataSize: _bufferSize);
-                    packet.ReadFromStream(_stream);
-
-                    if (packet.Length == 0)
-                    {
-                        var e = new Win32Exception();
-                        return ReportErrorAndReleasePacket(packet, (uint)e.NativeErrorCode, 0, e.Message);
-                    }
-
-                    return TdsEnums.SNI_SUCCESS;
-                }
-                catch (ObjectDisposedException ode)
-                {
-                    return ReportErrorAndReleasePacket(packet, ode);
-                }
-                catch (SocketException se)
-                {
-                    return ReportErrorAndReleasePacket(packet, se);
-                }
-                catch (IOException ioe)
-                {
-                    uint errorCode = ReportErrorAndReleasePacket(packet, ioe);
-                    if (ioe.InnerException is SocketException && ((SocketException)(ioe.InnerException)).SocketErrorCode == SocketError.TimedOut)
-                    {
-                        errorCode = TdsEnums.SNI_WAIT_TIMEOUT;
-                    }
-
-                    return errorCode;
-                }
-                finally
-                {
-                    _socket.ReceiveTimeout = 0;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Set async callbacks
-        /// </summary>
-        /// <param name="receiveCallback">Receive callback</param>
-        /// <param name="sendCallback">Send callback</param>
-        public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
-        {
-            _receiveCallback = receiveCallback;
-            _sendCallback = sendCallback;
-        }
-
-        /// <summary>
-        /// Send a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <param name="callback">Completion callback</param>
-        /// <returns>SNI error code</returns>
-        public override uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null)
-        {
-            SNIAsyncCallback cb = callback ?? _sendCallback;
-            lock (this)
-            {
-                packet.WriteToStreamAsync(_stream, cb, SNIProviders.TCP_PROV, disposePacketAfterSendAsync);
-            }
-            return TdsEnums.SNI_SUCCESS_IO_PENDING;
-        }
-
-        /// <summary>
-        /// Receive a packet asynchronously
-        /// </summary>
-        /// <param name="packet">SNI packet</param>
-        /// <returns>SNI error code</returns>
-        public override uint ReceiveAsync(ref SNIPacket packet)
-        {
-            packet = new SNIPacket(headerSize: 0, dataSize: _bufferSize);
-
-            try
-            {
-                packet.ReadFromStreamAsync(_stream, _receiveCallback);
-                return TdsEnums.SNI_SUCCESS_IO_PENDING;
-            }
-            catch (Exception e) when (e is ObjectDisposedException || e is SocketException || e is IOException)
-            {
-                return ReportErrorAndReleasePacket(packet, e);
-            }
-        }
-
-        /// <summary>
-        /// Check SNI handle connection
-        /// </summary>
-        /// <returns>SNI error status</returns>
-        public override uint CheckConnection()
-        {
-            try
-            {
-                // _socket.Poll method with argument SelectMode.SelectRead returns
-                //      True : if Listen has been called and a connection is pending, or
-                //      True : if data is available for reading, or
-                //      True : if the connection has been closed, reset, or terminated, i.e no active connection.
-                //      False : otherwise.
-                // _socket.Available property returns the number of bytes of data available to read.
-                //
-                // Since _socket.Connected alone doesn't guarantee if the connection is still active, we use it in
-                // combination with _socket.Poll method and _socket.Available == 0 check. When both of them
-                // return true we can safely determine that the connection is no longer active.
-                if (!_socket.Connected || (_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0))
-                {
-                    return TdsEnums.SNI_ERROR;
-                }
-            }
-            catch (SocketException se)
-            {
-                return ReportTcpSNIError(se);
-            }
-            catch (ObjectDisposedException ode)
-            {
-                return ReportTcpSNIError(ode);
-            }
-
-            return TdsEnums.SNI_SUCCESS;
-        }
-
-        private uint ReportTcpSNIError(Exception sniException)
-        {
-            _status = TdsEnums.SNI_ERROR;
-            return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, sniException);
-        }
-
-        private uint ReportTcpSNIError(uint nativeError, uint sniError, string errorMessage)
-        {
-            _status = TdsEnums.SNI_ERROR;
-            return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, nativeError, sniError, errorMessage);
-        }
-
-        private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException)
-        {
-            if (packet != null)
-            {
-                packet.Release();
-            }
-            return ReportTcpSNIError(sniException);
-        }
-
-        private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage)
-        {
-            if (packet != null)
-            {
-                packet.Release();
-            }
-            return ReportTcpSNIError(nativeError, sniError, errorMessage);
-        }
-
-#if DEBUG
-        /// <summary>
-        /// Test handle for killing underlying connection
-        /// </summary>
-        public override void KillConnection()
-        {
-            _socket.Shutdown(SocketShutdown.Both);
-        }
-#endif
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SSRP.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SSRP.cs
deleted file mode 100644 (file)
index 078e941..0000000
+++ /dev/null
@@ -1,161 +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.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.SNI
-{
-    internal class SSRP
-    {
-        private const char SemicolonSeparator = ';';
-        private const int SqlServerBrowserPort = 1434;
-
-        /// <summary>
-        /// Finds instance port number for given instance name.
-        /// </summary>
-        /// <param name="browserHostName">SQL Sever Browser hostname</param>
-        /// <param name="instanceName">instance name to find port number</param>
-        /// <returns>port number for given instance name</returns>
-        internal static int GetPortByInstanceName(string browserHostName, string instanceName)
-        {
-            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");
-
-            byte[] instanceInfoRequest = CreateInstanceInfoRequest(instanceName);
-            byte[] responsePacket = null;
-            try
-            {
-                responsePacket = SendUDPRequest(browserHostName, SqlServerBrowserPort, instanceInfoRequest);
-            }
-            catch (SocketException se)
-            {
-                throw new Exception(SQLMessage.SqlServerBrowserNotAccessible(), se);
-            }
-
-            const byte SvrResp = 0x05;
-            if (responsePacket == null || responsePacket.Length <= 3 || responsePacket[0] != SvrResp ||
-                BitConverter.ToUInt16(responsePacket, 1) != responsePacket.Length - 3)
-            {
-                throw new SocketException();
-            }
-
-            string serverMessage = Encoding.ASCII.GetString(responsePacket, 3, responsePacket.Length - 3);
-
-            string[] elements = serverMessage.Split(SemicolonSeparator);
-            int tcpIndex = Array.IndexOf(elements, "tcp");
-            if (tcpIndex < 0 || tcpIndex == elements.Length - 1)
-            {
-                throw new SocketException();
-            }
-
-            return ushort.Parse(elements[tcpIndex + 1]);
-        }
-
-        /// <summary>
-        /// Creates instance port lookup request (CLNT_UCAST_INST) for given instance name.
-        /// </summary>
-        /// <param name="instanceName">instance name to lookup port</param>
-        /// <returns>Byte array of instance port lookup request (CLNT_UCAST_INST)</returns>
-        private static byte[] CreateInstanceInfoRequest(string instanceName)
-        {
-            Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace");
-
-            const byte ClntUcastInst = 0x04;
-            instanceName += char.MinValue;
-            int byteCount = Encoding.ASCII.GetByteCount(instanceName);
-
-            byte[] requestPacket = new byte[byteCount + 1];
-            requestPacket[0] = ClntUcastInst;
-            Encoding.ASCII.GetBytes(instanceName, 0, instanceName.Length, requestPacket, 1);
-
-            return requestPacket;
-        }
-
-        /// <summary>
-        /// Finds DAC port for given instance name.
-        /// </summary>
-        /// <param name="browserHostName">SQL Sever Browser hostname</param>
-        /// <param name="instanceName">instance name to lookup DAC port</param>
-        /// <returns>DAC port for given instance name</returns>
-        internal static int GetDacPortByInstanceName(string browserHostName, string instanceName)
-        {
-            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");
-
-            byte[] dacPortInfoRequest = CreateDacPortInfoRequest(instanceName);
-            byte[] responsePacket = SendUDPRequest(browserHostName, SqlServerBrowserPort, dacPortInfoRequest);
-
-            const byte SvrResp = 0x05;
-            const byte ProtocolVersion = 0x01;
-            const byte RespSize = 0x06;
-            if (responsePacket == null || responsePacket.Length <= 4 || responsePacket[0] != SvrResp ||
-                BitConverter.ToUInt16(responsePacket, 1) != RespSize || responsePacket[3] != ProtocolVersion)
-            {
-                throw new SocketException();
-            }
-
-            int dacPort = BitConverter.ToUInt16(responsePacket, 4);
-            return dacPort;
-        }
-
-        /// <summary>
-        /// Creates DAC port lookup request (CLNT_UCAST_DAC) for given instance name.
-        /// </summary>
-        /// <param name="instanceName">instance name to lookup DAC port</param>
-        /// <returns>Byte array of DAC port lookup request (CLNT_UCAST_DAC)</returns>
-        private static byte[] CreateDacPortInfoRequest(string instanceName)
-        {
-            Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace");
-
-            const byte ClntUcastDac = 0x0F;
-            const byte ProtocolVersion = 0x01;
-            instanceName += char.MinValue;
-            int byteCount = Encoding.ASCII.GetByteCount(instanceName);
-
-            byte[] requestPacket = new byte[byteCount + 2];
-            requestPacket[0] = ClntUcastDac;
-            requestPacket[1] = ProtocolVersion;
-            Encoding.ASCII.GetBytes(instanceName, 0, instanceName.Length, requestPacket, 2);
-
-            return requestPacket;
-        }
-
-        /// <summary>
-        /// Sends request to server, and receives response from server by UDP.
-        /// </summary>
-        /// <param name="browserHostname">UDP server hostname</param>
-        /// <param name="port">UDP server port</param>
-        /// <param name="requestPacket">request packet</param>
-        /// <returns>response packet from UDP server</returns>
-        private static byte[] SendUDPRequest(string browserHostname, int port, byte[] requestPacket)
-        {
-            Debug.Assert(!string.IsNullOrWhiteSpace(browserHostname), "browserhostname should not be null, empty, or whitespace");
-            Debug.Assert(port >= 0 && port <= 65535, "Invalid port");
-            Debug.Assert(requestPacket != null && requestPacket.Length > 0, "requestPacket should not be null or 0-length array");
-
-            const int sendTimeOutMs = 1000;
-            const int receiveTimeOutMs = 1000;
-
-            IPAddress address = null;
-            bool isIpAddress = IPAddress.TryParse(browserHostname, out address);
-
-            byte[] responsePacket = null;
-            using (UdpClient client = new UdpClient(!isIpAddress ? AddressFamily.InterNetwork : address.AddressFamily))
-            {
-                Task<int> sendTask = client.SendAsync(requestPacket, requestPacket.Length, browserHostname, port);
-                Task<UdpReceiveResult> receiveTask = null;
-                if (sendTask.Wait(sendTimeOutMs) && (receiveTask = client.ReceiveAsync()).Wait(receiveTimeOutMs))
-                {
-                    responsePacket = receiveTask.Result.Buffer;
-                }
-            }
-
-            return responsePacket;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SslOverTdsStream.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SslOverTdsStream.cs
deleted file mode 100644 (file)
index 1555a82..0000000
+++ /dev/null
@@ -1,305 +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.Buffers;
-using System.IO;
-using System.IO.Pipes;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.SNI
-{
-    /// <summary>
-    /// SSL encapsulated over TDS transport. During SSL handshake, SSL packets are
-    /// transported in TDS packet type 0x12. Once SSL handshake has completed, SSL
-    /// packets are sent transparently.
-    /// </summary>
-    internal sealed class SslOverTdsStream : Stream
-    {
-        private readonly Stream _stream;
-
-        private int _packetBytes = 0;
-        private bool _encapsulate;
-
-        private const int PACKET_SIZE_WITHOUT_HEADER = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE - TdsEnums.HEADER_LEN;
-        private const int PRELOGIN_PACKET_TYPE = 0x12;
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="stream">Underlying stream</param>
-        public SslOverTdsStream(Stream stream)
-        {
-            _stream = stream;
-            _encapsulate = true;
-        }
-
-        /// <summary>
-        /// Finish SSL handshake. Stop encapsulating in TDS.
-        /// </summary>
-        public void FinishHandshake()
-        {
-            _encapsulate = false;
-        }
-
-        /// <summary>
-        /// Read buffer
-        /// </summary>
-        /// <param name="buffer">Buffer</param>
-        /// <param name="offset">Offset</param>
-        /// <param name="count">Byte count</param>
-        /// <returns>Bytes read</returns>
-        public override int Read(byte[] buffer, int offset, int count) =>
-            ReadInternal(buffer, offset, count, CancellationToken.None, async: false).GetAwaiter().GetResult();
-
-        /// <summary>
-        /// Write Buffer
-        /// </summary>
-        /// <param name="buffer"></param>
-        /// <param name="offset"></param>
-        /// <param name="count"></param>
-        public override void Write(byte[] buffer, int offset, int count)
-            => WriteInternal(buffer, offset, count, CancellationToken.None, async: false).Wait();
-
-        /// <summary>
-        /// Write Buffer Asynchronosly
-        /// </summary>
-        /// <param name="buffer"></param>
-        /// <param name="offset"></param>
-        /// <param name="count"></param>
-        /// <param name="token"></param>
-        /// <returns></returns>
-        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token)
-            => WriteInternal(buffer, offset, count, token, async: true);
-
-        /// <summary>
-        /// Read Buffer Asynchronosly
-        /// </summary>
-        /// <param name="buffer"></param>
-        /// <param name="offset"></param>
-        /// <param name="count"></param>
-        /// <param name="token"></param>
-        /// <returns></returns>
-        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken token)
-            => ReadInternal(buffer, offset, count, token, async: true);
-
-        /// <summary>
-        /// Read Internal is called synchronosly when async is false
-        /// </summary>
-        private async Task<int> ReadInternal(byte[] buffer, int offset, int count, CancellationToken token, bool async)
-        {
-            int readBytes = 0;
-            byte[] packetData = null;
-            byte[] readTarget = buffer;
-            int readOffset = offset;
-            if (_encapsulate)
-            {
-                packetData = ArrayPool<byte>.Shared.Rent(count < TdsEnums.HEADER_LEN ? TdsEnums.HEADER_LEN : count);
-                readTarget = packetData;
-                readOffset = 0;
-                if (_packetBytes == 0)
-                {
-                    // Account for split packets
-                    while (readBytes < TdsEnums.HEADER_LEN)
-                    {
-                        readBytes += async ?
-                            await _stream.ReadAsync(packetData, readBytes, TdsEnums.HEADER_LEN - readBytes, token).ConfigureAwait(false) :
-                            _stream.Read(packetData, readBytes, TdsEnums.HEADER_LEN - readBytes);
-                    }
-
-                    _packetBytes = (packetData[TdsEnums.HEADER_LEN_FIELD_OFFSET] << 8) | packetData[TdsEnums.HEADER_LEN_FIELD_OFFSET + 1];
-                    _packetBytes -= TdsEnums.HEADER_LEN;
-                }
-
-                if (count > _packetBytes)
-                {
-                    count = _packetBytes;
-                }
-            }
-
-            readBytes = async ?
-                await _stream.ReadAsync(readTarget, readOffset, count, token).ConfigureAwait(false) :
-                _stream.Read(readTarget, readOffset, count);
-
-            if (_encapsulate)
-            {
-                _packetBytes -= readBytes;
-            }
-            if (packetData != null)
-            {
-                Buffer.BlockCopy(packetData, 0, buffer, offset, readBytes);
-                ArrayPool<byte>.Shared.Return(packetData, clearArray: true);
-            }
-            return readBytes;
-        }
-
-        /// <summary>
-        /// The internal write method calls Sync APIs when Async flag is false
-        /// </summary>
-        private async Task WriteInternal(byte[] buffer, int offset, int count, CancellationToken token, bool async)
-        {
-            int currentCount = 0;
-            int currentOffset = offset;
-
-            while (count > 0)
-            {
-                // During the SSL negotiation phase, SSL is tunnelled over TDS packet type 0x12. After
-                // negotiation, the underlying socket only sees SSL frames.
-                //
-                if (_encapsulate)
-                {
-                    if (count > PACKET_SIZE_WITHOUT_HEADER)
-                    {
-                        currentCount = PACKET_SIZE_WITHOUT_HEADER;
-                    }
-                    else
-                    {
-                        currentCount = count;
-                    }
-
-                    count -= currentCount;
-
-                    // Prepend buffer data with TDS prelogin header
-                    int combinedLength = TdsEnums.HEADER_LEN + currentCount;
-                    byte[] combinedBuffer = ArrayPool<byte>.Shared.Rent(combinedLength);
-
-                    // We can only send 4088 bytes in one packet. Header[1] is set to 1 if this is a
-                    // partial packet (whether or not count != 0).
-                    //
-                    combinedBuffer[7] = 0; // touch this first for the jit bounds check
-                    combinedBuffer[0] = PRELOGIN_PACKET_TYPE;
-                    combinedBuffer[1] = (byte)(count > 0 ? 0 : 1);
-                    combinedBuffer[2] = (byte)((currentCount + TdsEnums.HEADER_LEN) / 0x100);
-                    combinedBuffer[3] = (byte)((currentCount + TdsEnums.HEADER_LEN) % 0x100);
-                    combinedBuffer[4] = 0;
-                    combinedBuffer[5] = 0;
-                    combinedBuffer[6] = 0;
-
-                    Array.Copy(buffer, currentOffset, combinedBuffer, TdsEnums.HEADER_LEN, (combinedLength - TdsEnums.HEADER_LEN));
-
-                    if (async)
-                    {
-                        await _stream.WriteAsync(combinedBuffer, 0, combinedLength, token).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        _stream.Write(combinedBuffer, 0, combinedLength);
-                    }
-
-                    Array.Clear(combinedBuffer, 0, combinedLength);
-                    ArrayPool<byte>.Shared.Return(combinedBuffer);
-
-                }
-                else
-                {
-                    currentCount = count;
-                    count = 0;
-
-                    if (async)
-                    {
-                        await _stream.WriteAsync(buffer, currentOffset, currentCount, token).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        _stream.Write(buffer, currentOffset, currentCount);
-                    }
-                }
-
-                if (async)
-                {
-                    await _stream.FlushAsync().ConfigureAwait(false);
-                }
-                else
-                {
-                    _stream.Flush();
-                }
-
-                currentOffset += currentCount;
-            }
-        }
-
-        /// <summary>
-        /// Set stream length.
-        /// </summary>
-        /// <param name="value">Length</param>
-        public override void SetLength(long value)
-        {
-            throw new NotSupportedException();
-        }
-
-        /// <summary>
-        /// Flush stream
-        /// </summary>
-        public override void Flush()
-        {
-            // Can sometimes get Pipe broken errors from flushing a PipeStream.
-            // PipeStream.Flush() also doesn't do anything, anyway.
-            if (!(_stream is PipeStream))
-            {
-                _stream.Flush();
-            }
-        }
-
-        /// <summary>
-        /// Get/set stream position
-        /// </summary>
-        public override long Position
-        {
-            get
-            {
-                throw new NotSupportedException();
-            }
-            set
-            {
-                throw new NotSupportedException();
-            }
-        }
-
-        /// <summary>
-        /// Seek in stream
-        /// </summary>
-        /// <param name="offset">Offset</param>
-        /// <param name="origin">Origin</param>
-        /// <returns>Position</returns>
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            throw new NotSupportedException();
-        }
-
-        /// <summary>
-        /// Check if stream can be read from
-        /// </summary>
-        public override bool CanRead
-        {
-            get { return _stream.CanRead; }
-        }
-
-        /// <summary>
-        /// Check if stream can be written to
-        /// </summary>
-        public override bool CanWrite
-        {
-            get { return _stream.CanWrite; }
-        }
-
-        /// <summary>
-        /// Check if stream can be seeked
-        /// </summary>
-        public override bool CanSeek
-        {
-            get { return false; } // Seek not supported
-        }
-
-        /// <summary>
-        /// Get stream length
-        /// </summary>
-        public override long Length
-        {
-            get
-            {
-                throw new NotSupportedException();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SspiClientContextStatus.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SspiClientContextStatus.cs
deleted file mode 100644 (file)
index 21cf9aa..0000000
+++ /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.Net;
-using System.Net.Security;
-
-
-namespace System.Data.SqlClient.SNI
-{
-    internal class SspiClientContextStatus
-    {
-        public SafeFreeCredentials CredentialsHandle
-        {
-            get;
-            set;
-        }
-
-        public SafeDeleteContext SecurityContext
-        {
-            get;
-            set;
-        }
-
-        public ContextFlagsPal ContextFlags
-        {
-            get;
-            set;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SessionHandle.Unix.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SessionHandle.Unix.cs
deleted file mode 100644 (file)
index deca227..0000000
+++ /dev/null
@@ -1,34 +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.Data.SqlClient
-{
-    // this structure is used for transporting packet handle references between the TdsParserStateObject
-    //  base class and Managed or Native implementations.
-    // It carries type information so that assertions about the type of handle can be made in the
-    //  implemented abstract methods
-    // it is a ref struct so that it can only be used to transport the handles and not store them
-
-    // N.B. If you change this type you must also change the version for the other platform
-
-    internal readonly ref struct SessionHandle
-    {
-        public const int NativeHandleType = 1;
-        public const int ManagedHandleType = 2;
-
-        public readonly SNI.SNIHandle ManagedHandle;
-        public readonly int Type;
-
-        public SessionHandle(SNI.SNIHandle managedHandle, int type)
-        {
-            Type = type;
-            ManagedHandle = managedHandle;
-        }
-
-        public bool IsNull => ManagedHandle is null;
-
-        public static SessionHandle FromManagedSession(SNI.SNIHandle managedSessionHandle) => new SessionHandle(managedSessionHandle, ManagedHandleType);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SessionHandle.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SessionHandle.Windows.cs
deleted file mode 100644 (file)
index 573880d..0000000
+++ /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.
-
-
-namespace System.Data.SqlClient
-{
-    // this structure is used for transporting packet handle references between the TdsParserStateObject
-    //  base class and Managed or Native implementations.
-    // It carries type information so that assertions about the type of handle can be made in the
-    //  implemented abstract methods
-    // it is a ref struct so that it can only be used to transport the handles and not store them
-
-    // N.B. If you change this type you must also change the version for the other platform
-
-    internal readonly ref struct SessionHandle
-    {
-        public const int NativeHandleType = 1;
-        public const int ManagedHandleType = 2;
-
-        public readonly SNI.SNIHandle ManagedHandle;
-        public readonly SNIHandle NativeHandle;
-
-        public readonly int Type;
-
-        public SessionHandle(SNI.SNIHandle managedHandle, SNIHandle nativeHandle, int type)
-        {
-            Type = type;
-            ManagedHandle = managedHandle;
-            NativeHandle = nativeHandle;
-        }
-
-        public bool IsNull => (Type == NativeHandleType) ? NativeHandle is null : ManagedHandle is null;
-
-        public static SessionHandle FromManagedSession(SNI.SNIHandle managedSessionHandle) => new SessionHandle(managedSessionHandle, default, ManagedHandleType);
-
-        public static SessionHandle FromNativeHandle(SNIHandle nativeSessionHandle) => new SessionHandle(default, nativeSessionHandle, NativeHandleType);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SortOrder.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SortOrder.cs
deleted file mode 100644 (file)
index 214bc50..0000000
+++ /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.
-
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-//------------------------------------------------------------------------------
-
-
-namespace System.Data.SqlClient
-{
-    public enum SortOrder
-    {
-        Unspecified = -1,
-        Ascending = 0,
-        Descending = 1
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBuffer.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBuffer.cs
deleted file mode 100644 (file)
index dbae465..0000000
+++ /dev/null
@@ -1,1189 +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.Data.SqlTypes;
-using System.Globalization;
-using System.Runtime.InteropServices;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlBuffer
-    {
-        internal enum StorageType
-        {
-            Empty = 0,
-            Boolean,
-            Byte,
-            DateTime,
-            Decimal,
-            Double,
-            Int16,
-            Int32,
-            Int64,
-            Guid,
-            Money,
-            Single,
-            String,
-            SqlBinary,
-            SqlCachedBuffer,
-            SqlGuid,
-            SqlXml,
-            Date,
-            DateTime2,
-            DateTimeOffset,
-            Time,
-        }
-
-        internal struct DateTimeInfo
-        {
-            // This is used to store DateTime
-            internal int daypart;
-            internal int timepart;
-        }
-
-        internal struct NumericInfo
-        {
-            // This is used to store Decimal data
-            internal int data1;
-            internal int data2;
-            internal int data3;
-            internal int data4;
-            internal byte precision;
-            internal byte scale;
-            internal bool positive;
-        }
-
-        internal struct TimeInfo
-        {
-            internal long ticks;
-            internal byte scale;
-        }
-
-        internal struct DateTime2Info
-        {
-            internal int date;
-            internal TimeInfo timeInfo;
-        }
-
-        internal struct DateTimeOffsetInfo
-        {
-            internal DateTime2Info dateTime2Info;
-            internal short offset;
-        }
-
-        [StructLayout(LayoutKind.Explicit)]
-        internal struct Storage
-        {
-            [FieldOffset(0)]
-            internal bool _boolean;
-            [FieldOffset(0)]
-            internal byte _byte;
-            [FieldOffset(0)]
-            internal DateTimeInfo _dateTimeInfo;
-            [FieldOffset(0)]
-            internal double _double;
-            [FieldOffset(0)]
-            internal NumericInfo _numericInfo;
-            [FieldOffset(0)]
-            internal short _int16;
-            [FieldOffset(0)]
-            internal int _int32;
-            [FieldOffset(0)]
-            internal long _int64;     // also used to store Money, UtcDateTime, Date , and Time
-            [FieldOffset(0)]
-            internal Guid _guid;
-            [FieldOffset(0)]
-            internal float _single;
-            [FieldOffset(0)]
-            internal TimeInfo _timeInfo;
-            [FieldOffset(0)]
-            internal DateTime2Info _dateTime2Info;
-            [FieldOffset(0)]
-            internal DateTimeOffsetInfo _dateTimeOffsetInfo;
-        }
-
-        private bool _isNull;
-        private StorageType _type;
-        private Storage _value;
-        private object _object;    // String, SqlBinary, SqlCachedBuffer, SqlGuid, SqlString, SqlXml
-
-        internal SqlBuffer()
-        {
-        }
-
-        private SqlBuffer(SqlBuffer value)
-        { // Clone
-            // value types
-            _isNull = value._isNull;
-            _type = value._type;
-            // ref types - should also be read only unless at some point we allow this data
-            // to be mutable, then we will need to copy
-            _value = value._value;
-            _object = value._object;
-        }
-
-        internal bool IsEmpty
-        {
-            get
-            {
-                return (StorageType.Empty == _type);
-            }
-        }
-
-        internal bool IsNull
-        {
-            get
-            {
-                return _isNull;
-            }
-        }
-
-        internal StorageType VariantInternalStorageType
-        {
-            get { return _type; }
-        }
-
-        internal bool Boolean
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Boolean == _type)
-                {
-                    return _value._boolean;
-                }
-                return (bool)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _value._boolean = value;
-                _type = StorageType.Boolean;
-                _isNull = false;
-            }
-        }
-
-        internal byte Byte
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Byte == _type)
-                {
-                    return _value._byte;
-                }
-                return (byte)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _value._byte = value;
-                _type = StorageType.Byte;
-                _isNull = false;
-            }
-        }
-
-        internal byte[] ByteArray
-        {
-            get
-            {
-                ThrowIfNull();
-                return this.SqlBinary.Value;
-            }
-        }
-
-        internal DateTime DateTime
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Date == _type)
-                {
-                    return DateTime.MinValue.AddDays(_value._int32);
-                }
-                if (StorageType.DateTime2 == _type)
-                {
-                    return new DateTime(GetTicksFromDateTime2Info(_value._dateTime2Info));
-                }
-                if (StorageType.DateTime == _type)
-                {
-                    return SqlTypeWorkarounds.SqlDateTimeToDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart);
-                }
-                return (DateTime)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal decimal Decimal
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Decimal == _type)
-                {
-                    if (_value._numericInfo.data4 != 0 || _value._numericInfo.scale > 28)
-                    {
-                        throw new OverflowException(SQLResource.ConversionOverflowMessage);
-                    }
-                    return new decimal(_value._numericInfo.data1, _value._numericInfo.data2, _value._numericInfo.data3, !_value._numericInfo.positive, _value._numericInfo.scale);
-                }
-                if (StorageType.Money == _type)
-                {
-                    long l = _value._int64;
-                    bool isNegative = false;
-                    if (l < 0)
-                    {
-                        isNegative = true;
-                        l = -l;
-                    }
-                    return new decimal((int)(l & 0xffffffff), (int)(l >> 32), 0, isNegative, 4);
-                }
-                return (decimal)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal double Double
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Double == _type)
-                {
-                    return _value._double;
-                }
-                return (double)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _value._double = value;
-                _type = StorageType.Double;
-                _isNull = false;
-            }
-        }
-
-        internal Guid Guid
-        {
-            get
-            {
-                ThrowIfNull();
-                if (StorageType.Guid == _type)
-                {
-                    return _value._guid;
-                }
-                else if (StorageType.SqlGuid == _type)
-                {
-                    return ((SqlGuid)_object).Value;
-                }
-                return (Guid)this.Value;
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-
-                _type = StorageType.Guid;
-                _value._guid = value;
-                _isNull = false;
-            }
-        }
-
-        internal short Int16
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Int16 == _type)
-                {
-                    return _value._int16;
-                }
-                return (short)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _value._int16 = value;
-                _type = StorageType.Int16;
-                _isNull = false;
-            }
-        }
-
-        internal int Int32
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Int32 == _type)
-                {
-                    return _value._int32;
-                }
-                return (int)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _value._int32 = value;
-                _type = StorageType.Int32;
-                _isNull = false;
-            }
-        }
-
-        internal long Int64
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Int64 == _type)
-                {
-                    return _value._int64;
-                }
-                return (long)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _value._int64 = value;
-                _type = StorageType.Int64;
-                _isNull = false;
-            }
-        }
-
-        internal float Single
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Single == _type)
-                {
-                    return _value._single;
-                }
-                return (float)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _value._single = value;
-                _type = StorageType.Single;
-                _isNull = false;
-            }
-        }
-
-        internal string String
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.String == _type)
-                {
-                    return (string)_object;
-                }
-                else if (StorageType.SqlCachedBuffer == _type)
-                {
-                    return ((SqlCachedBuffer)(_object)).ToString();
-                }
-                return (string)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        // use static list of format strings indexed by scale for perf
-        private static readonly string[] s_katmaiDateTimeOffsetFormatByScale = new string[] {
-                "yyyy-MM-dd HH:mm:ss zzz",
-                "yyyy-MM-dd HH:mm:ss.f zzz",
-                "yyyy-MM-dd HH:mm:ss.ff zzz",
-                "yyyy-MM-dd HH:mm:ss.fff zzz",
-                "yyyy-MM-dd HH:mm:ss.ffff zzz",
-                "yyyy-MM-dd HH:mm:ss.fffff zzz",
-                "yyyy-MM-dd HH:mm:ss.ffffff zzz",
-                "yyyy-MM-dd HH:mm:ss.fffffff zzz",
-        };
-
-        private static readonly string[] s_katmaiDateTime2FormatByScale = new string[] {
-                "yyyy-MM-dd HH:mm:ss",
-                "yyyy-MM-dd HH:mm:ss.f",
-                "yyyy-MM-dd HH:mm:ss.ff",
-                "yyyy-MM-dd HH:mm:ss.fff",
-                "yyyy-MM-dd HH:mm:ss.ffff",
-                "yyyy-MM-dd HH:mm:ss.fffff",
-                "yyyy-MM-dd HH:mm:ss.ffffff",
-                "yyyy-MM-dd HH:mm:ss.fffffff",
-        };
-
-        private static readonly string[] s_katmaiTimeFormatByScale = new string[] {
-                "HH:mm:ss",
-                "HH:mm:ss.f",
-                "HH:mm:ss.ff",
-                "HH:mm:ss.fff",
-                "HH:mm:ss.ffff",
-                "HH:mm:ss.fffff",
-                "HH:mm:ss.ffffff",
-                "HH:mm:ss.fffffff",
-        };
-
-        internal string KatmaiDateTimeString
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Date == _type)
-                {
-                    return this.DateTime.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
-                }
-                if (StorageType.Time == _type)
-                {
-                    byte scale = _value._timeInfo.scale;
-                    return new DateTime(_value._timeInfo.ticks).ToString(s_katmaiTimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
-                }
-                if (StorageType.DateTime2 == _type)
-                {
-                    byte scale = _value._dateTime2Info.timeInfo.scale;
-                    return this.DateTime.ToString(s_katmaiDateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
-                }
-                if (StorageType.DateTimeOffset == _type)
-                {
-                    DateTimeOffset dto = this.DateTimeOffset;
-                    byte scale = _value._dateTimeOffsetInfo.dateTime2Info.timeInfo.scale;
-                    return dto.ToString(s_katmaiDateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
-                }
-                return (string)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlString KatmaiDateTimeSqlString
-        {
-            get
-            {
-                if (StorageType.Date == _type ||
-                    StorageType.Time == _type ||
-                    StorageType.DateTime2 == _type ||
-                    StorageType.DateTimeOffset == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlString.Null;
-                    }
-                    return new SqlString(KatmaiDateTimeString);
-                }
-                return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal TimeSpan Time
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.Time == _type)
-                {
-                    return new TimeSpan(_value._timeInfo.ticks);
-                }
-
-                return (TimeSpan)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal DateTimeOffset DateTimeOffset
-        {
-            get
-            {
-                ThrowIfNull();
-
-                if (StorageType.DateTimeOffset == _type)
-                {
-                    TimeSpan offset = new TimeSpan(0, _value._dateTimeOffsetInfo.offset, 0);
-                    // datetime part presents time in UTC
-                    return new DateTimeOffset(GetTicksFromDateTime2Info(_value._dateTimeOffsetInfo.dateTime2Info) + offset.Ticks, offset);
-                }
-
-                return (DateTimeOffset)this.Value; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        private static long GetTicksFromDateTime2Info(DateTime2Info dateTime2Info)
-        {
-            return (dateTime2Info.date * TimeSpan.TicksPerDay + dateTime2Info.timeInfo.ticks);
-        }
-
-        internal SqlBinary SqlBinary
-        {
-            get
-            {
-                if (StorageType.SqlBinary == _type)
-                {
-                    return (SqlBinary)_object;
-                }
-                return (SqlBinary)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _object = value;
-                _type = StorageType.SqlBinary;
-                _isNull = value.IsNull;
-            }
-        }
-
-        internal SqlBoolean SqlBoolean
-        {
-            get
-            {
-                if (StorageType.Boolean == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlBoolean.Null;
-                    }
-                    return new SqlBoolean(_value._boolean);
-                }
-                return (SqlBoolean)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlByte SqlByte
-        {
-            get
-            {
-                if (StorageType.Byte == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlByte.Null;
-                    }
-                    return new SqlByte(_value._byte);
-                }
-                return (SqlByte)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlCachedBuffer SqlCachedBuffer
-        {
-            get
-            {
-                if (StorageType.SqlCachedBuffer == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlCachedBuffer.Null;
-                    }
-                    return (SqlCachedBuffer)_object;
-                }
-                return (SqlCachedBuffer)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _object = value;
-                _type = StorageType.SqlCachedBuffer;
-                _isNull = value.IsNull;
-            }
-        }
-
-        internal SqlXml SqlXml
-        {
-            get
-            {
-                if (StorageType.SqlXml == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlXml.Null;
-                    }
-                    return (SqlXml)_object;
-                }
-                return (SqlXml)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _object = value;
-                _type = StorageType.SqlXml;
-                _isNull = value.IsNull;
-            }
-        }
-
-        internal SqlDateTime SqlDateTime
-        {
-            get
-            {
-                if (StorageType.DateTime == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlDateTime.Null;
-                    }
-                    return new SqlDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart);
-                }
-                return (SqlDateTime)SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlDecimal SqlDecimal
-        {
-            get
-            {
-                if (StorageType.Decimal == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlDecimal.Null;
-                    }
-                    return new SqlDecimal(_value._numericInfo.precision,
-                                          _value._numericInfo.scale,
-                                          _value._numericInfo.positive,
-                                          _value._numericInfo.data1,
-                                          _value._numericInfo.data2,
-                                          _value._numericInfo.data3,
-                                          _value._numericInfo.data4
-                                          );
-                }
-                return (SqlDecimal)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlDouble SqlDouble
-        {
-            get
-            {
-                if (StorageType.Double == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlDouble.Null;
-                    }
-                    return new SqlDouble(_value._double);
-                }
-                return (SqlDouble)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlGuid SqlGuid
-        {
-            get
-            {
-                if (StorageType.Guid == _type)
-                {
-                    return new SqlGuid(_value._guid);
-                }
-                else if (StorageType.SqlGuid == _type)
-                {
-                    return IsNull ? SqlGuid.Null : (SqlGuid)_object;
-                }
-                return (SqlGuid)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-            set
-            {
-                Debug.Assert(IsEmpty, "setting value a second time?");
-                _object = value;
-                _type = StorageType.SqlGuid;
-                _isNull = value.IsNull;
-            }
-        }
-
-        internal SqlInt16 SqlInt16
-        {
-            get
-            {
-                if (StorageType.Int16 == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlInt16.Null;
-                    }
-                    return new SqlInt16(_value._int16);
-                }
-                return (SqlInt16)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlInt32 SqlInt32
-        {
-            get
-            {
-                if (StorageType.Int32 == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlInt32.Null;
-                    }
-                    return new SqlInt32(_value._int32);
-                }
-                return (SqlInt32)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlInt64 SqlInt64
-        {
-            get
-            {
-                if (StorageType.Int64 == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlInt64.Null;
-                    }
-                    return new SqlInt64(_value._int64);
-                }
-                return (SqlInt64)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlMoney SqlMoney
-        {
-            get
-            {
-                if (StorageType.Money == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlMoney.Null;
-                    }
-                    return SqlTypeWorkarounds.SqlMoneyCtor(_value._int64, 1/*ignored*/);
-                }
-                return (SqlMoney)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlSingle SqlSingle
-        {
-            get
-            {
-                if (StorageType.Single == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlSingle.Null;
-                    }
-                    return new SqlSingle(_value._single);
-                }
-                return (SqlSingle)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal SqlString SqlString
-        {
-            get
-            {
-                if (StorageType.String == _type)
-                {
-                    if (IsNull)
-                    {
-                        return SqlString.Null;
-                    }
-                    return new SqlString((string)_object);
-                }
-                else if (StorageType.SqlCachedBuffer == _type)
-                {
-                    SqlCachedBuffer data = (SqlCachedBuffer)(_object);
-                    if (data.IsNull)
-                    {
-                        return SqlString.Null;
-                    }
-                    return data.ToSqlString();
-                }
-                return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing.
-            }
-        }
-
-        internal object SqlValue
-        {
-            get
-            {
-                switch (_type)
-                {
-                    case StorageType.Empty: return DBNull.Value;
-                    case StorageType.Boolean: return SqlBoolean;
-                    case StorageType.Byte: return SqlByte;
-                    case StorageType.DateTime: return SqlDateTime;
-                    case StorageType.Decimal: return SqlDecimal;
-                    case StorageType.Double: return SqlDouble;
-                    case StorageType.Int16: return SqlInt16;
-                    case StorageType.Int32: return SqlInt32;
-                    case StorageType.Int64: return SqlInt64;
-                    case StorageType.Guid: return SqlGuid;
-                    case StorageType.Money: return SqlMoney;
-                    case StorageType.Single: return SqlSingle;
-                    case StorageType.String: return SqlString;
-
-                    case StorageType.SqlCachedBuffer:
-                        {
-                            SqlCachedBuffer data = (SqlCachedBuffer)(_object);
-                            if (data.IsNull)
-                            {
-                                return SqlXml.Null;
-                            }
-                            return data.ToSqlXml();
-                        }
-
-                    case StorageType.SqlBinary:
-                    case StorageType.SqlGuid:
-                        return _object;
-
-                    case StorageType.SqlXml:
-                        if (_isNull)
-                        {
-                            return SqlXml.Null;
-                        }
-                        Debug.Assert(null != _object);
-                        return (SqlXml)_object;
-
-                    case StorageType.Date:
-                    case StorageType.DateTime2:
-                        if (_isNull)
-                        {
-                            return DBNull.Value;
-                        }
-                        return DateTime;
-
-                    case StorageType.DateTimeOffset:
-                        if (_isNull)
-                        {
-                            return DBNull.Value;
-                        }
-                        return DateTimeOffset;
-
-                    case StorageType.Time:
-                        if (_isNull)
-                        {
-                            return DBNull.Value;
-                        }
-                        return Time;
-                }
-                return null; // need to return the value as an object of some SQL type
-            }
-        }
-
-        private static readonly object s_cachedTrueObject = true;
-        private static readonly object s_cachedFalseObject = false;
-
-        internal object Value
-        {
-            get
-            {
-                if (IsNull)
-                {
-                    return DBNull.Value;
-                }
-                switch (_type)
-                {
-                    case StorageType.Empty: return DBNull.Value;
-                    case StorageType.Boolean: return Boolean ? s_cachedTrueObject : s_cachedFalseObject;
-                    case StorageType.Byte: return Byte;
-                    case StorageType.DateTime: return DateTime;
-                    case StorageType.Decimal: return Decimal;
-                    case StorageType.Double: return Double;
-                    case StorageType.Int16: return Int16;
-                    case StorageType.Int32: return Int32;
-                    case StorageType.Int64: return Int64;
-                    case StorageType.Guid: return Guid;
-                    case StorageType.Money: return Decimal;
-                    case StorageType.Single: return Single;
-                    case StorageType.String: return String;
-                    case StorageType.SqlBinary: return ByteArray;
-                    case StorageType.SqlCachedBuffer:
-                        {
-                            // If we have a CachedBuffer, it's because it's an XMLTYPE column
-                            // and we have to return a string when they're asking for the CLS
-                            // value of the column.
-                            return ((SqlCachedBuffer)(_object)).ToString();
-                        }
-                    case StorageType.SqlGuid: return Guid;
-                    case StorageType.SqlXml:
-                        {
-                            // XMLTYPE columns must be returned as string when asking for the CLS value
-                            SqlXml data = (SqlXml)_object;
-                            string s = data.Value;
-                            return s;
-                        }
-                    case StorageType.Date: return DateTime;
-                    case StorageType.DateTime2: return DateTime;
-                    case StorageType.DateTimeOffset: return DateTimeOffset;
-                    case StorageType.Time: return Time;
-                }
-                return null; // need to return the value as an object of some CLS type
-            }
-        }
-
-        internal Type GetTypeFromStorageType(bool isSqlType)
-        {
-            if (isSqlType)
-            {
-                switch (_type)
-                {
-                    case StorageType.Empty: return null;
-                    case StorageType.Boolean: return typeof(SqlBoolean);
-                    case StorageType.Byte: return typeof(SqlByte);
-                    case StorageType.DateTime: return typeof(SqlDateTime);
-                    case StorageType.Decimal: return typeof(SqlDecimal);
-                    case StorageType.Double: return typeof(SqlDouble);
-                    case StorageType.Int16: return typeof(SqlInt16);
-                    case StorageType.Int32: return typeof(SqlInt32);
-                    case StorageType.Int64: return typeof(SqlInt64);
-                    case StorageType.Guid: return typeof(SqlGuid);
-                    case StorageType.Money: return typeof(SqlMoney);
-                    case StorageType.Single: return typeof(SqlSingle);
-                    case StorageType.String: return typeof(SqlString);
-                    case StorageType.SqlCachedBuffer: return typeof(SqlString);
-                    case StorageType.SqlBinary: return typeof(object);
-                    case StorageType.SqlGuid: return typeof(SqlGuid);
-                    case StorageType.SqlXml: return typeof(SqlXml);
-                    // Date DateTime2 and DateTimeOffset have no direct Sql type to contain them
-                }
-            }
-            else
-            { //Is CLR Type
-                switch (_type)
-                {
-                    case StorageType.Empty: return null;
-                    case StorageType.Boolean: return typeof(bool);
-                    case StorageType.Byte: return typeof(byte);
-                    case StorageType.DateTime: return typeof(DateTime);
-                    case StorageType.Decimal: return typeof(decimal);
-                    case StorageType.Double: return typeof(double);
-                    case StorageType.Int16: return typeof(short);
-                    case StorageType.Int32: return typeof(int);
-                    case StorageType.Int64: return typeof(long);
-                    case StorageType.Guid: return typeof(Guid);
-                    case StorageType.Money: return typeof(decimal);
-                    case StorageType.Single: return typeof(float);
-                    case StorageType.String: return typeof(string);
-                    case StorageType.SqlBinary: return typeof(byte[]);
-                    case StorageType.SqlCachedBuffer: return typeof(string);
-                    case StorageType.SqlGuid: return typeof(Guid);
-                    case StorageType.SqlXml: return typeof(string);
-                    case StorageType.Date: return typeof(DateTime);
-                    case StorageType.DateTime2: return typeof(DateTime);
-                    case StorageType.DateTimeOffset: return typeof(DateTimeOffset);
-                }
-            }
-
-            return null; // need to return the value as an object of some CLS type
-        }
-
-        internal static SqlBuffer[] CreateBufferArray(int length)
-        {
-            SqlBuffer[] buffers = new SqlBuffer[length];
-            for (int i = 0; i < buffers.Length; ++i)
-            {
-                buffers[i] = new SqlBuffer();
-            }
-            return buffers;
-        }
-
-        internal static SqlBuffer[] CloneBufferArray(SqlBuffer[] values)
-        {
-            SqlBuffer[] copy = new SqlBuffer[values.Length];
-            for (int i = 0; i < values.Length; i++)
-            {
-                copy[i] = new SqlBuffer(values[i]);
-            }
-            return copy;
-        }
-
-        internal static void Clear(SqlBuffer[] values)
-        {
-            if (null != values)
-            {
-                for (int i = 0; i < values.Length; ++i)
-                {
-                    values[i].Clear();
-                }
-            }
-        }
-
-        internal void Clear()
-        {
-            _isNull = false;
-            _type = StorageType.Empty;
-            _object = null;
-        }
-
-        internal void SetToDateTime(int daypart, int timepart)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            _value._dateTimeInfo.daypart = daypart;
-            _value._dateTimeInfo.timepart = timepart;
-            _type = StorageType.DateTime;
-            _isNull = false;
-        }
-
-        internal void SetToDecimal(byte precision, byte scale, bool positive, int[] bits)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            _value._numericInfo.precision = precision;
-            _value._numericInfo.scale = scale;
-            _value._numericInfo.positive = positive;
-            _value._numericInfo.data1 = bits[0];
-            _value._numericInfo.data2 = bits[1];
-            _value._numericInfo.data3 = bits[2];
-            _value._numericInfo.data4 = bits[3];
-            _type = StorageType.Decimal;
-            _isNull = false;
-        }
-
-        internal void SetToMoney(long value)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            _value._int64 = value;
-            _type = StorageType.Money;
-            _isNull = false;
-        }
-
-        internal void SetToNullOfType(StorageType storageType)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            _type = storageType;
-            _isNull = true;
-            _object = null;
-        }
-
-        internal void SetToString(string value)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            _object = value;
-            _type = StorageType.String;
-            _isNull = false;
-        }
-
-        internal void SetToDate(ReadOnlySpan<byte> bytes)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-
-            _type = StorageType.Date;
-            _value._int32 = GetDateFromByteArray(bytes);
-            _isNull = false;
-        }
-
-        internal void SetToTime(ReadOnlySpan<byte> bytes, byte scale)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            _type = StorageType.Time;
-            FillInTimeInfo(ref _value._timeInfo, bytes, scale);
-            _isNull = false;
-        }
-
-        internal void SetToDateTime2(ReadOnlySpan<byte> bytes, byte scale)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            int length = bytes.Length;
-            _type = StorageType.DateTime2;
-            FillInTimeInfo(ref _value._dateTime2Info.timeInfo, bytes.Slice(0, length - 3), scale); // remaining 3 bytes is for date
-            _value._dateTime2Info.date = GetDateFromByteArray(bytes.Slice(length - 3)); // 3 bytes for date
-            _isNull = false;
-        }
-
-        internal void SetToDateTimeOffset(ReadOnlySpan<byte> bytes, byte scale)
-        {
-            Debug.Assert(IsEmpty, "setting value a second time?");
-            int length = bytes.Length;
-            _type = StorageType.DateTimeOffset;
-            FillInTimeInfo(ref _value._dateTimeOffsetInfo.dateTime2Info.timeInfo, bytes.Slice(0, length - 5), scale); // remaining 5 bytes are for date and offset
-            _value._dateTimeOffsetInfo.dateTime2Info.date = GetDateFromByteArray(bytes.Slice(length - 5)); // 3 bytes for date
-            _value._dateTimeOffsetInfo.offset = (short)(bytes[length - 2] + (bytes[length - 1] << 8)); // 2 bytes for offset (Int16)
-            _isNull = false;
-        }
-
-        private static void FillInTimeInfo(ref TimeInfo timeInfo, ReadOnlySpan<byte> timeBytes, byte scale)
-        {
-            int length = timeBytes.Length;
-            Debug.Assert(3 <= length && length <= 5, "invalid data length for timeInfo: " + length);
-            Debug.Assert(0 <= scale && scale <= 7, "invalid scale: " + scale);
-
-            long tickUnits = (long)timeBytes[0] + ((long)timeBytes[1] << 8) + ((long)timeBytes[2] << 16);
-            if (length > 3)
-            {
-                tickUnits += ((long)timeBytes[3] << 24);
-            }
-            if (length > 4)
-            {
-                tickUnits += ((long)timeBytes[4] << 32);
-            }
-            timeInfo.ticks = tickUnits * TdsEnums.TICKS_FROM_SCALE[scale];
-            timeInfo.scale = scale;
-        }
-
-        private static int GetDateFromByteArray(ReadOnlySpan<byte> buf)
-        {
-            byte thirdByte = buf[2]; // reordered to optimize JIT generated bounds checks to a single instance, review generated asm before changing
-            return buf[0] + (buf[1] << 8) + (thirdByte << 16);
-        }
-
-        private void ThrowIfNull()
-        {
-            if (IsNull)
-            {
-                throw new SqlNullValueException();
-            }
-        }
-
-        // [Field]As<T> method explanation:
-        // these methods are used to bridge generic to non-generic access to value type fields on the storage struct
-        // where typeof(T) == typeof(field)
-        //   1) RyuJIT will recognise the pattern of (T)(object)T as being redundant and eliminate
-        //   the T and object casts leaving T, so while this looks like it will put every value type instance in a box the
-        //   enerated assembly will be short and direct
-        //   2) another jit may not recognise the pattern and should emit the code as seen. this will box and then unbox the
-        //   value type which is no worse than the mechanism that this code replaces
-        // where typeof(T) != typeof(field)
-        //   the jit will emit all the cast operations as written. this will put the value into a box and then attempt to
-        //   cast it, because it is an object even no conversions are use and this will generate the desired InvalidCastException
-        //   so users cannot widen a short to an int preserving external expectations
-
-        internal T ByteAs<T>()
-        {
-            ThrowIfNull();
-            return (T)(object)_value._byte;
-        }
-
-        internal T BooleanAs<T>()
-        {
-            ThrowIfNull();
-            return (T)(object)_value._boolean;
-        }
-
-        internal T Int32As<T>()
-        {
-            ThrowIfNull();
-            return (T)(object)_value._int32;
-        }
-
-        internal T Int16As<T>()
-        {
-            ThrowIfNull();
-            return (T)(object)_value._int16;
-        }
-
-        internal T Int64As<T>()
-        {
-            ThrowIfNull();
-            return (T)(object)_value._int64;
-        }
-
-        internal T DoubleAs<T>()
-        {
-            ThrowIfNull();
-            return (T)(object)_value._double;
-        }
-
-        internal T SingleAs<T>()
-        {
-            ThrowIfNull();
-            return (T)(object)_value._single;
-        }
-    }
-}// namespace
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopy.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopy.cs
deleted file mode 100644 (file)
index 8effcec..0000000
+++ /dev/null
@@ -1,2953 +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.Data.Common;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-
-namespace System.Data.SqlClient
-{
-    // This internal class helps us to associate the metadata from the target
-    // with the ColumnOrdinals from the source.
-    internal sealed class _ColumnMapping
-    {
-        internal int _sourceColumnOrdinal;
-        internal _SqlMetaData _metadata;
-
-        internal _ColumnMapping(int columnId, _SqlMetaData metadata)
-        {
-            _sourceColumnOrdinal = columnId;
-            _metadata = metadata;
-        }
-    }
-
-    internal sealed class Row
-    {
-        private readonly object[] _dataFields;
-
-        internal Row(int rowCount)
-        {
-            _dataFields = new object[rowCount];
-        }
-
-        internal object[] DataFields
-        {
-            get
-            {
-                return _dataFields;
-            }
-        }
-
-        internal object this[int index]
-        {
-            get
-            {
-                return _dataFields[index];
-            }
-        }
-    }
-
-    // The controlling class for one result (metadata + rows)
-    internal sealed class Result
-    {
-        private readonly _SqlMetaDataSet _metadata;
-        private readonly List<Row> _rowset;
-
-        internal Result(_SqlMetaDataSet metadata)
-        {
-            _metadata = metadata;
-            _rowset = new List<Row>();
-        }
-
-        internal int Count => _rowset.Count;
-
-        internal _SqlMetaDataSet MetaData => _metadata;
-
-        internal Row this[int index] => _rowset[index];
-
-        internal void AddRow(Row row)
-        {
-            _rowset.Add(row);
-        }
-    }
-
-    // A wrapper object for metadata and rowsets returned by our initial queries
-    internal sealed class BulkCopySimpleResultSet
-    {
-        private readonly List<Result> _results;        // The list of results
-        private Result _resultSet;                     // The current result
-        private int[] _indexmap;                       // Associates columnids with indexes in the rowarray
-
-        internal BulkCopySimpleResultSet()
-        {
-            _results = new List<Result>();
-        }
-
-        // Indexer
-        internal Result this[int idx] => _results[idx];
-
-        // Callback function for the tdsparser
-        // (note that setting the metadata adds a resultset)
-        internal void SetMetaData(_SqlMetaDataSet metadata)
-        {
-            _resultSet = new Result(metadata);
-            _results.Add(_resultSet);
-
-            _indexmap = new int[_resultSet.MetaData.Length];
-            for (int i = 0; i < _indexmap.Length; i++)
-            {
-                _indexmap[i] = i;
-            }
-        }
-
-        // Callback function for the tdsparser.
-        // This will create an indexmap for the active resultset.
-        internal int[] CreateIndexMap() => _indexmap;
-
-        // Callback function for the tdsparser.
-        // This will return an array of rows to store the rowdata.
-        internal object[] CreateRowBuffer()
-        {
-            Row row = new Row(_resultSet.MetaData.Length);
-            _resultSet.AddRow(row);
-            return row.DataFields;
-        }
-    }
-
-    public sealed class SqlBulkCopy : IDisposable
-    {
-        private enum ValueSourceType
-        {
-            Unspecified = 0,
-            IDataReader,
-            DataTable,
-            RowArray,
-            DbDataReader
-        }
-
-        // Enum for specifying SqlDataReader.Get method used
-        private enum ValueMethod : byte
-        {
-            GetValue,
-            SqlTypeSqlDecimal,
-            SqlTypeSqlDouble,
-            SqlTypeSqlSingle,
-            DataFeedStream,
-            DataFeedText,
-            DataFeedXml
-        }
-
-        // Used to hold column metadata for SqlDataReader case
-        private readonly struct SourceColumnMetadata
-        {
-            public SourceColumnMetadata(ValueMethod method, bool isSqlType, bool isDataFeed)
-            {
-                Method = method;
-                IsSqlType = isSqlType;
-                IsDataFeed = isDataFeed;
-            }
-
-            public readonly ValueMethod Method;
-            public readonly bool IsSqlType;
-            public readonly bool IsDataFeed;
-        }
-
-        // The initial query will return three tables.
-        // Transaction count has only one value in one column and one row
-        // MetaData has n columns but no rows
-        // Collation has 4 columns and n rows
-
-        private const int MetaDataResultId = 1;
-
-        private const int CollationResultId = 2;
-        private const int CollationId = 3;
-
-        private const int MAX_LENGTH = 0x7FFFFFFF;
-
-        private const int DefaultCommandTimeout = 30;
-
-        private bool _enableStreaming = false;
-        private int _batchSize;
-        private readonly bool _ownConnection;
-        private readonly SqlBulkCopyOptions _copyOptions;
-        private int _timeout = DefaultCommandTimeout;
-        private string _destinationTableName;
-        private int _rowsCopied;
-        private int _notifyAfter;
-        private int _rowsUntilNotification;
-        private bool _insideRowsCopiedEvent;
-
-        private object _rowSource;
-        private SqlDataReader _SqlDataReaderRowSource;
-        private DbDataReader _DbDataReaderRowSource;
-        private DataTable _dataTableSource;
-
-        private SqlBulkCopyColumnMappingCollection _columnMappings;
-        private SqlBulkCopyColumnMappingCollection _localColumnMappings;
-
-        private SqlConnection _connection;
-        private SqlTransaction _internalTransaction;
-        private readonly SqlTransaction _externalTransaction;
-
-        private ValueSourceType _rowSourceType = ValueSourceType.Unspecified;
-        private DataRow _currentRow;
-        private int _currentRowLength;
-        private DataRowState _rowStateToSkip;
-        private IEnumerator _rowEnumerator;
-
-        private TdsParser _parser;
-        private TdsParserStateObject _stateObj;
-        private List<_ColumnMapping> _sortedColumnMappings;
-
-        private SqlRowsCopiedEventHandler _rowsCopiedEventHandler;
-
-        // Newly added member variables for Async modification, m = member variable to bcp.
-        private int _savedBatchSize = 0; // Save the batchsize so that changes are not affected unexpectedly.
-        private bool _hasMoreRowToCopy = false;
-        private bool _isAsyncBulkCopy = false;
-        private bool _isBulkCopyingInProgress = false;
-        private SqlInternalConnectionTds.SyncAsyncLock _parserLock = null;
-
-        private SourceColumnMetadata[] _currentRowMetadata;
-
-#if DEBUG
-        internal static bool _setAlwaysTaskOnWrite = false; //when set and in DEBUG mode, TdsParser::WriteBulkCopyValue will always return a task
-        internal static bool SetAlwaysTaskOnWrite
-        {
-            get
-            {
-                return _setAlwaysTaskOnWrite;
-            }
-            set
-            {
-                _setAlwaysTaskOnWrite = value;
-            }
-        }
-#endif
-
-        public SqlBulkCopy(SqlConnection connection)
-        {
-            if (connection == null)
-            {
-                throw ADP.ArgumentNull(nameof(connection));
-            }
-            _connection = connection;
-            _columnMappings = new SqlBulkCopyColumnMappingCollection();
-        }
-
-        public SqlBulkCopy(SqlConnection connection, SqlBulkCopyOptions copyOptions, SqlTransaction externalTransaction)
-            : this(connection)
-        {
-            _copyOptions = copyOptions;
-            if (externalTransaction != null && IsCopyOption(SqlBulkCopyOptions.UseInternalTransaction))
-            {
-                throw SQL.BulkLoadConflictingTransactionOption();
-            }
-
-            if (!IsCopyOption(SqlBulkCopyOptions.UseInternalTransaction))
-            {
-                _externalTransaction = externalTransaction;
-            }
-        }
-
-        public SqlBulkCopy(string connectionString)
-        {
-            if (connectionString == null)
-            {
-                throw ADP.ArgumentNull(nameof(connectionString));
-            }
-            _connection = new SqlConnection(connectionString);
-            _columnMappings = new SqlBulkCopyColumnMappingCollection();
-            _ownConnection = true;
-        }
-
-        public SqlBulkCopy(string connectionString, SqlBulkCopyOptions copyOptions)
-            : this(connectionString)
-        {
-            _copyOptions = copyOptions;
-        }
-
-        public int BatchSize
-        {
-            get
-            {
-                return _batchSize;
-            }
-            set
-            {
-                if (value >= 0)
-                {
-                    _batchSize = value;
-                }
-                else
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(BatchSize));
-                }
-            }
-        }
-
-        public int BulkCopyTimeout
-        {
-            get
-            {
-                return _timeout;
-            }
-            set
-            {
-                if (value < 0)
-                {
-                    throw SQL.BulkLoadInvalidTimeout(value);
-                }
-                _timeout = value;
-            }
-        }
-
-        public bool EnableStreaming
-        {
-            get
-            {
-                return _enableStreaming;
-            }
-            set
-            {
-                _enableStreaming = value;
-            }
-        }
-
-        public SqlBulkCopyColumnMappingCollection ColumnMappings
-        {
-            get
-            {
-                return _columnMappings;
-            }
-        }
-
-        public string DestinationTableName
-        {
-            get
-            {
-                return _destinationTableName;
-            }
-            set
-            {
-                if (value == null)
-                {
-                    throw ADP.ArgumentNull(nameof(DestinationTableName));
-                }
-                else if (value.Length == 0)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(DestinationTableName));
-                }
-                _destinationTableName = value;
-            }
-        }
-
-        public int NotifyAfter
-        {
-            get
-            {
-                return _notifyAfter;
-            }
-            set
-            {
-                if (value >= 0)
-                {
-                    _notifyAfter = value;
-                }
-                else
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(NotifyAfter));
-                }
-            }
-        }
-
-        public event SqlRowsCopiedEventHandler SqlRowsCopied
-        {
-            add
-            {
-                _rowsCopiedEventHandler += value;
-            }
-            remove
-            {
-                _rowsCopiedEventHandler -= value;
-            }
-        }
-
-        internal SqlStatistics Statistics
-        {
-            get
-            {
-                if (null != _connection)
-                {
-                    if (_connection.StatisticsEnabled)
-                    {
-                        return _connection.Statistics;
-                    }
-                }
-                return null;
-            }
-        }
-
-        void IDisposable.Dispose()
-        {
-            this.Dispose(true);
-            GC.SuppressFinalize(this);
-        }
-
-        private bool IsCopyOption(SqlBulkCopyOptions copyOption) => ((_copyOptions & copyOption) == copyOption);
-
-        //Creates the initial query string, but does not execute it.
-        private string CreateInitialQuery()
-        {
-            string[] parts;
-            try
-            {
-                parts = MultipartIdentifier.ParseMultipartIdentifier(this.DestinationTableName, "[\"", "]\"", SR.SQL_BulkCopyDestinationTableName, true);
-            }
-            catch (Exception e)
-            {
-                throw SQL.BulkLoadInvalidDestinationTable(this.DestinationTableName, e);
-            }
-            if (string.IsNullOrEmpty(parts[MultipartIdentifier.TableIndex]))
-            {
-                throw SQL.BulkLoadInvalidDestinationTable(this.DestinationTableName, null);
-            }
-            string TDSCommand;
-
-
-            TDSCommand = "select @@trancount; SET FMTONLY ON select * from " + this.DestinationTableName + " SET FMTONLY OFF ";
-
-            string TableCollationsStoredProc;
-            if (_connection.IsKatmaiOrNewer)
-            {
-                TableCollationsStoredProc = "sp_tablecollations_100";
-            }
-            else
-            {
-                TableCollationsStoredProc = "sp_tablecollations_90";
-            }
-
-            string TableName = parts[MultipartIdentifier.TableIndex];
-            bool isTempTable = TableName.Length > 0 && '#' == TableName[0];
-            if (!string.IsNullOrEmpty(TableName))
-            {
-                // Escape table name to be put inside TSQL literal block (within N'').
-                TableName = SqlServerEscapeHelper.EscapeStringAsLiteral(TableName);
-                // Escape the table name
-                TableName = SqlServerEscapeHelper.EscapeIdentifier(TableName);
-            }
-
-            string SchemaName = parts[MultipartIdentifier.SchemaIndex];
-            if (!string.IsNullOrEmpty(SchemaName))
-            {
-                // Escape schema name to be put inside TSQL literal block (within N'').
-                SchemaName = SqlServerEscapeHelper.EscapeStringAsLiteral(SchemaName);
-                // Escape the schema name
-                SchemaName = SqlServerEscapeHelper.EscapeIdentifier(SchemaName);
-            }
-
-            string CatalogName = parts[MultipartIdentifier.CatalogIndex];
-            if (isTempTable && string.IsNullOrEmpty(CatalogName))
-            {
-                TDSCommand += string.Format("exec tempdb..{0} N'{1}.{2}'",
-                    TableCollationsStoredProc,
-                    SchemaName,
-                    TableName
-                );
-            }
-            else
-            {
-                // Escape the catalog name
-                if (!string.IsNullOrEmpty(CatalogName))
-                {
-                    CatalogName = SqlServerEscapeHelper.EscapeIdentifier(CatalogName);
-                }
-                TDSCommand += string.Format("exec {0}..{1} N'{2}.{3}'",
-                    CatalogName,
-                    TableCollationsStoredProc,
-                    SchemaName,
-                    TableName
-                );
-            }
-            return TDSCommand;
-        }
-
-        // Creates and then executes initial query to get information about the targettable
-        // When __isAsyncBulkCopy == false (i.e. it is Sync copy): out result contains the resulset. Returns null.
-        // When __isAsyncBulkCopy == true (i.e. it is Async copy): This still uses the _parser.Run method synchronously and return Task<BulkCopySimpleResultSet>.
-        // We need to have a _parser.RunAsync to make it real async.
-        private Task<BulkCopySimpleResultSet> CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result)
-        {
-            string TDSCommand = CreateInitialQuery();
-
-            Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true);
-
-            if (executeTask == null)
-            {
-                result = new BulkCopySimpleResultSet();
-                RunParser(result);
-                return null;
-            }
-            else
-            {
-                Debug.Assert(_isAsyncBulkCopy, "Execution pended when not doing async bulk copy");
-                result = null;
-                return executeTask.ContinueWith<BulkCopySimpleResultSet>(t =>
-                {
-                    Debug.Assert(!t.IsCanceled, "Execution task was canceled");
-                    if (t.IsFaulted)
-                    {
-                        throw t.Exception.InnerException;
-                    }
-                    else
-                    {
-                        var internalResult = new BulkCopySimpleResultSet();
-                        RunParserReliably(internalResult);
-                        return internalResult;
-                    }
-                }, TaskScheduler.Default);
-            }
-        }
-
-        // Matches associated columns with metadata from initial query.
-        // Builds and executes the update bulk command.
-        private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet internalResults)
-        {
-            Debug.Assert(internalResults != null, "Where are the results from the initial query?");
-
-            StringBuilder updateBulkCommandText = new StringBuilder();
-
-            if (0 == internalResults[CollationResultId].Count)
-            {
-                throw SQL.BulkLoadNoCollation();
-            }
-
-            updateBulkCommandText.AppendFormat("insert bulk {0} (", this.DestinationTableName);
-            int nmatched = 0;  // Number of columns that match and are accepted
-            int nrejected = 0; // Number of columns that match but were rejected
-            bool rejectColumn; // True if a column is rejected because of an excluded type
-
-            bool isInTransaction;
-
-            isInTransaction = _connection.HasLocalTransaction;
-            // Throw if there is a transaction but no flag is set
-            if (isInTransaction && null == _externalTransaction && null == _internalTransaction && (_connection.Parser != null && _connection.Parser.CurrentTransaction != null && _connection.Parser.CurrentTransaction.IsLocal))
-            {
-                throw SQL.BulkLoadExistingTransaction();
-            }
-
-            // Loop over the metadata for each column
-            _SqlMetaDataSet metaDataSet = internalResults[MetaDataResultId].MetaData;
-            _sortedColumnMappings = new List<_ColumnMapping>(metaDataSet.Length);
-            for (int i = 0; i < metaDataSet.Length; i++)
-            {
-                _SqlMetaData metadata = metaDataSet[i];
-                rejectColumn = false;
-
-                // Check for excluded types
-                if ((metadata.type == SqlDbType.Timestamp)
-                    || ((metadata.IsIdentity) && !IsCopyOption(SqlBulkCopyOptions.KeepIdentity)))
-                {
-                    // Remove metadata for excluded columns
-                    metaDataSet[i] = null;
-                    rejectColumn = true;
-                    // We still need to find a matching column association
-                }
-
-                // Find out if this column is associated
-                int assocId;
-                for (assocId = 0; assocId < _localColumnMappings.Count; assocId++)
-                {
-                    if ((_localColumnMappings[assocId]._destinationColumnOrdinal == metadata.ordinal) ||
-                        (UnquotedName(_localColumnMappings[assocId]._destinationColumnName) == metadata.column))
-                    {
-                        if (rejectColumn)
-                        {
-                            nrejected++; // Count matched columns only
-                            break;
-                        }
-
-                        _sortedColumnMappings.Add(new _ColumnMapping(_localColumnMappings[assocId]._internalSourceColumnOrdinal, metadata));
-                        nmatched++;
-
-                        if (nmatched > 1)
-                        {
-                            updateBulkCommandText.Append(", "); // A leading comma for all but the first one
-                        }
-
-                        // Some datatypes need special handling ...
-                        if (metadata.type == SqlDbType.Variant)
-                        {
-                            AppendColumnNameAndTypeName(updateBulkCommandText, metadata.column, "sql_variant");
-                        }
-                        else if (metadata.type == SqlDbType.Udt)
-                        {
-                            AppendColumnNameAndTypeName(updateBulkCommandText, metadata.column, "varbinary");
-                        }
-                        else
-                        {
-                            AppendColumnNameAndTypeName(updateBulkCommandText, metadata.column, metadata.type.ToString());
-                        }
-
-                        switch (metadata.metaType.NullableType)
-                        {
-                            case TdsEnums.SQLNUMERICN:
-                            case TdsEnums.SQLDECIMALN:
-                                // Decimal and numeric need to include precision and scale
-                                updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0},{1})", metadata.precision, metadata.scale);
-                                break;
-                            case TdsEnums.SQLUDT:
-                                {
-                                    if (metadata.IsLargeUdt)
-                                    {
-                                        updateBulkCommandText.Append("(max)");
-                                    }
-                                    else
-                                    {
-                                        int size = metadata.length;
-                                        updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0})", size);
-                                    }
-                                    break;
-                                }
-                            case TdsEnums.SQLTIME:
-                            case TdsEnums.SQLDATETIME2:
-                            case TdsEnums.SQLDATETIMEOFFSET:
-                                // date, dateime2, and datetimeoffset need to include scale
-                                updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0})", metadata.scale);
-                                break;
-                            default:
-                                {
-                                    // For non-long non-fixed types we need to add the Size
-                                    if (!metadata.metaType.IsFixed && !metadata.metaType.IsLong)
-                                    {
-                                        int size = metadata.length;
-                                        switch (metadata.metaType.NullableType)
-                                        {
-                                            case TdsEnums.SQLNCHAR:
-                                            case TdsEnums.SQLNVARCHAR:
-                                            case TdsEnums.SQLNTEXT:
-                                                size /= 2;
-                                                break;
-                                            default:
-                                                break;
-                                        }
-                                        updateBulkCommandText.AppendFormat((IFormatProvider)null, "({0})", size);
-                                    }
-                                    else if (metadata.metaType.IsPlp && metadata.metaType.SqlDbType != SqlDbType.Xml)
-                                    {
-                                        // Partial length column prefix (max)
-                                        updateBulkCommandText.Append("(max)");
-                                    }
-                                    break;
-                                }
-                        }
-
-                        // Get collation for column i
-                        Result rowset = internalResults[CollationResultId];
-                        object rowvalue = rowset[i][CollationId];
-
-                        bool shouldSendCollation;
-                        switch (metadata.type)
-                        {
-                            case SqlDbType.Char:
-                            case SqlDbType.NChar:
-                            case SqlDbType.VarChar:
-                            case SqlDbType.NVarChar:
-                            case SqlDbType.Text:
-                            case SqlDbType.NText:
-                                shouldSendCollation = true;
-                                break;
-
-                            default:
-                                shouldSendCollation = false;
-                                break;
-                        }
-
-                        if (rowvalue != null && shouldSendCollation)
-                        {
-                            Debug.Assert(rowvalue is SqlString);
-                            SqlString collation_name = (SqlString)rowvalue;
-                            if (!collation_name.IsNull)
-                            {
-                                updateBulkCommandText.Append(" COLLATE " + collation_name.Value);
-                                // Compare collations only if the collation value was set on the metadata
-                                if (null != _SqlDataReaderRowSource && metadata.collation != null)
-                                {
-                                    // On SqlDataReader we can verify the sourcecolumn collation!
-                                    int sourceColumnId = _localColumnMappings[assocId]._internalSourceColumnOrdinal;
-                                    int destinationLcid = metadata.collation.LCID;
-                                    int sourceLcid = _SqlDataReaderRowSource.GetLocaleId(sourceColumnId);
-                                    if (sourceLcid != destinationLcid)
-                                    {
-                                        throw SQL.BulkLoadLcidMismatch(sourceLcid, _SqlDataReaderRowSource.GetName(sourceColumnId), destinationLcid, metadata.column);
-                                    }
-                                }
-                            }
-                        }
-                        break;
-                    }
-                }
-                if (assocId == _localColumnMappings.Count)
-                {
-                    // Remove metadata for unmatched columns
-                    metaDataSet[i] = null;
-                }
-            }
-
-            // All columnmappings should have matched up
-            if (nmatched + nrejected != _localColumnMappings.Count)
-            {
-                throw (SQL.BulkLoadNonMatchingColumnMapping());
-            }
-
-            updateBulkCommandText.Append(")");
-
-            if ((_copyOptions & (
-                    SqlBulkCopyOptions.KeepNulls
-                    | SqlBulkCopyOptions.TableLock
-                    | SqlBulkCopyOptions.CheckConstraints
-                    | SqlBulkCopyOptions.FireTriggers)) != SqlBulkCopyOptions.Default)
-            {
-                bool addSeparator = false; // Insert a comma character if multiple options in list
-                updateBulkCommandText.Append(" with (");
-                if (IsCopyOption(SqlBulkCopyOptions.KeepNulls))
-                {
-                    updateBulkCommandText.Append("KEEP_NULLS");
-                    addSeparator = true;
-                }
-                if (IsCopyOption(SqlBulkCopyOptions.TableLock))
-                {
-                    updateBulkCommandText.Append((addSeparator ? ", " : "") + "TABLOCK");
-                    addSeparator = true;
-                }
-                if (IsCopyOption(SqlBulkCopyOptions.CheckConstraints))
-                {
-                    updateBulkCommandText.Append((addSeparator ? ", " : "") + "CHECK_CONSTRAINTS");
-                    addSeparator = true;
-                }
-                if (IsCopyOption(SqlBulkCopyOptions.FireTriggers))
-                {
-                    updateBulkCommandText.Append((addSeparator ? ", " : "") + "FIRE_TRIGGERS");
-                    addSeparator = true;
-                }
-                updateBulkCommandText.Append(")");
-            }
-            return (updateBulkCommandText.ToString());
-        }
-
-        private Task SubmitUpdateBulkCommand(string TDSCommand)
-        {
-            Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true);
-
-            if (executeTask == null)
-            {
-                RunParser();
-                return null;
-            }
-            else
-            {
-                Debug.Assert(_isAsyncBulkCopy, "Execution pended when not doing async bulk copy");
-                return executeTask.ContinueWith(t =>
-                {
-                    Debug.Assert(!t.IsCanceled, "Execution task was canceled");
-                    if (t.IsFaulted)
-                    {
-                        throw t.Exception.InnerException;
-                    }
-                    else
-                    {
-                        RunParserReliably();
-                    }
-                }, TaskScheduler.Default);
-            }
-        }
-
-        // Starts writing the Bulkcopy data stream
-        private void WriteMetaData(BulkCopySimpleResultSet internalResults)
-        {
-            _stateObj.SetTimeoutSeconds(this.BulkCopyTimeout);
-
-            _SqlMetaDataSet metadataCollection = internalResults[MetaDataResultId].MetaData;
-            _stateObj._outputMessageType = TdsEnums.MT_BULK;
-            _parser.WriteBulkCopyMetaData(metadataCollection, _sortedColumnMappings.Count, _stateObj);
-        }
-
-        // Terminates the bulk copy operation.
-        // Must be called at the end of the bulk copy session.
-        public void Close()
-        {
-            if (_insideRowsCopiedEvent)
-            {
-                throw SQL.InvalidOperationInsideEvent();
-            }
-            Dispose(true);
-            GC.SuppressFinalize(this);
-        }
-
-        private void Dispose(bool disposing)
-        {
-            if (disposing)
-            {
-                // Dispose dependent objects
-                _columnMappings = null;
-                _parser = null;
-                try
-                {
-                    // Just in case there is a lingering transaction (which there shouldn't be)
-                    try
-                    {
-                        Debug.Assert(_internalTransaction == null, "Internal transaction exists during dispose");
-                        if (null != _internalTransaction)
-                        {
-                            _internalTransaction.Rollback();
-                            _internalTransaction.Dispose();
-                            _internalTransaction = null;
-                        }
-                    }
-                    catch (Exception e)
-                    {
-                        if (!ADP.IsCatchableExceptionType(e))
-                        {
-                            throw;
-                        }
-                    }
-                }
-                finally
-                {
-                    if (_connection != null)
-                    {
-                        if (_ownConnection)
-                        {
-                            _connection.Dispose();
-                        }
-                        _connection = null;
-                    }
-                }
-            }
-        }
-
-        // Unified method to read a value from the current row
-        private object GetValueFromSourceRow(int destRowIndex, out bool isSqlType, out bool isDataFeed, out bool isNull)
-        {
-            _SqlMetaData metadata = _sortedColumnMappings[destRowIndex]._metadata;
-            int sourceOrdinal = _sortedColumnMappings[destRowIndex]._sourceColumnOrdinal;
-
-            switch (_rowSourceType)
-            {
-                case ValueSourceType.IDataReader:
-                case ValueSourceType.DbDataReader:
-                    // Handle data feeds (common for both DbDataReader and SqlDataReader)
-                    if (_currentRowMetadata[destRowIndex].IsDataFeed)
-                    {
-                        if (_DbDataReaderRowSource.IsDBNull(sourceOrdinal))
-                        {
-                            isSqlType = false;
-                            isDataFeed = false;
-                            isNull = true;
-                            return DBNull.Value;
-                        }
-                        else
-                        {
-                            isSqlType = false;
-                            isDataFeed = true;
-                            isNull = false;
-                            switch (_currentRowMetadata[destRowIndex].Method)
-                            {
-                                case ValueMethod.DataFeedStream:
-                                    return new StreamDataFeed(_DbDataReaderRowSource.GetStream(sourceOrdinal));
-                                case ValueMethod.DataFeedText:
-                                    return new TextDataFeed(_DbDataReaderRowSource.GetTextReader(sourceOrdinal));
-                                case ValueMethod.DataFeedXml:
-                                    // Only SqlDataReader supports an XmlReader
-                                    // There is no GetXmlReader on DbDataReader, however if GetValue returns XmlReader we will read it as stream if it is assigned to XML field
-                                    Debug.Assert(_SqlDataReaderRowSource != null, "Should not be reading row as an XmlReader if bulk copy source is not a SqlDataReader");
-                                    return new XmlDataFeed(_SqlDataReaderRowSource.GetXmlReader(sourceOrdinal));
-                                default:
-                                    Debug.Fail($"Current column is marked as being a DataFeed, but no DataFeed compatible method was provided. Method: {_currentRowMetadata[destRowIndex].Method}");
-                                    isDataFeed = false;
-                                    object columnValue = _DbDataReaderRowSource.GetValue(sourceOrdinal);
-                                    ADP.IsNullOrSqlType(columnValue, out isNull, out isSqlType);
-                                    return columnValue;
-                            }
-                        }
-                    }
-                    // SqlDataReader-specific logic
-                    else if (null != _SqlDataReaderRowSource)
-                    {
-                        if (_currentRowMetadata[destRowIndex].IsSqlType)
-                        {
-                            INullable value;
-                            isSqlType = true;
-                            isDataFeed = false;
-                            switch (_currentRowMetadata[destRowIndex].Method)
-                            {
-                                case ValueMethod.SqlTypeSqlDecimal:
-                                    value = _SqlDataReaderRowSource.GetSqlDecimal(sourceOrdinal);
-                                    break;
-                                case ValueMethod.SqlTypeSqlDouble:
-                                    value = (SqlDecimal)_SqlDataReaderRowSource.GetSqlDouble(sourceOrdinal); // use cast to handle IsNull correctly because no public constructor allows it
-                                    break;
-                                case ValueMethod.SqlTypeSqlSingle:
-                                    value = (SqlDecimal)_SqlDataReaderRowSource.GetSqlSingle(sourceOrdinal); // use cast to handle IsNull correctly because no public constructor allows it
-                                    break;
-                                default:
-                                    Debug.Fail($"Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {_currentRowMetadata[destRowIndex].Method}");
-                                    value = (INullable)_SqlDataReaderRowSource.GetSqlValue(sourceOrdinal);
-                                    break;
-                            }
-
-                            isNull = value.IsNull;
-                            return value;
-                        }
-                        else
-                        {
-                            isSqlType = false;
-                            isDataFeed = false;
-
-                            object value = _SqlDataReaderRowSource.GetValue(sourceOrdinal);
-                            isNull = ((value == null) || (value == DBNull.Value));
-                            if ((!isNull) && (metadata.type == SqlDbType.Udt))
-                            {
-                                var columnAsINullable = value as INullable;
-                                isNull = (columnAsINullable != null) && columnAsINullable.IsNull;
-                            }
-#if DEBUG
-                            else if (!isNull)
-                            {
-                                Debug.Assert(!(value is INullable) || !((INullable)value).IsNull, "IsDBNull returned false, but GetValue returned a null INullable");
-                            }
-#endif
-                            return value;
-                        }
-                    }
-                    else
-                    {
-                        isDataFeed = false;
-
-                        IDataReader rowSourceAsIDataReader = (IDataReader)_rowSource;
-
-                        // Only use IsDbNull when streaming is enabled and only for non-SqlDataReader
-                        if ((_enableStreaming) && (_SqlDataReaderRowSource == null) && (rowSourceAsIDataReader.IsDBNull(sourceOrdinal)))
-                        {
-                            isSqlType = false;
-                            isNull = true;
-                            return DBNull.Value;
-                        }
-                        else
-                        {
-                            object columnValue = rowSourceAsIDataReader.GetValue(sourceOrdinal);
-                            ADP.IsNullOrSqlType(columnValue, out isNull, out isSqlType);
-                            return columnValue;
-                        }
-                    }
-                case ValueSourceType.DataTable:
-                case ValueSourceType.RowArray:
-                    {
-                        Debug.Assert(_currentRow != null, "uninitialized _currentRow");
-                        Debug.Assert(sourceOrdinal < _currentRowLength, "inconsistency of length of rows from rowsource!");
-
-                        isDataFeed = false;
-                        object currentRowValue = _currentRow[sourceOrdinal];
-                        ADP.IsNullOrSqlType(currentRowValue, out isNull, out isSqlType);
-
-                        // If this row is not null, and there are special storage types for this row, then handle the special storage types
-                        if ((!isNull) && (_currentRowMetadata[destRowIndex].IsSqlType))
-                        {
-                            switch (_currentRowMetadata[destRowIndex].Method)
-                            {
-                                case ValueMethod.SqlTypeSqlSingle:
-                                    {
-                                        if (isSqlType)
-                                        {
-                                            return new SqlDecimal(((SqlSingle)currentRowValue).Value);
-                                        }
-                                        else
-                                        {
-                                            float f = (float)currentRowValue;
-                                            if (!float.IsNaN(f))
-                                            {
-                                                isSqlType = true;
-                                                return new SqlDecimal(f);
-                                            }
-                                            break;
-                                        }
-                                    }
-                                case ValueMethod.SqlTypeSqlDouble:
-                                    {
-                                        if (isSqlType)
-                                        {
-                                            return new SqlDecimal(((SqlDouble)currentRowValue).Value);
-                                        }
-                                        else
-                                        {
-                                            double d = (double)currentRowValue;
-                                            if (!double.IsNaN(d))
-                                            {
-                                                isSqlType = true;
-                                                return new SqlDecimal(d);
-                                            }
-                                            break;
-                                        }
-                                    }
-                                case ValueMethod.SqlTypeSqlDecimal:
-                                    {
-                                        if (isSqlType)
-                                        {
-                                            return (SqlDecimal)currentRowValue;
-                                        }
-                                        else
-                                        {
-                                            isSqlType = true;
-                                            return new SqlDecimal((decimal)currentRowValue);
-                                        }
-                                    }
-                                default:
-                                    {
-                                        Debug.Fail($"Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {_currentRowMetadata[destRowIndex].Method}");
-                                        break;
-                                    }
-                            }
-                        }
-
-                        // If we are here then either the value is null, there was no special storage type for this column or the special storage type wasn't handled (e.g. if the currentRowValue is NaN)
-                        return currentRowValue;
-                    }
-                default:
-                    {
-                        Debug.Fail("ValueSourcType unspecified");
-                        throw ADP.NotSupported();
-                    }
-            }
-        }
-
-        // Unified method to read a row from the current rowsource.
-        // When _isAsyncBulkCopy == true (i.e. async copy): returns Task<bool> when IDataReader is a DbDataReader, Null for others.
-        // When _isAsyncBulkCopy == false (i.e. sync copy): returns null. Uses ReadFromRowSource to get the boolean value.
-        // "more" -- should be used by the caller only when the return value is null.
-        private Task ReadFromRowSourceAsync(CancellationToken cts)
-        {
-            if (_isAsyncBulkCopy && _DbDataReaderRowSource != null)
-            {
-                // This will call ReadAsync for DbDataReader (for SqlDataReader it will be truly async read; for non-SqlDataReader it may block.)
-                return _DbDataReaderRowSource.ReadAsync(cts).ContinueWith((t) =>
-                {
-                    if (t.Status == TaskStatus.RanToCompletion)
-                    {
-                        _hasMoreRowToCopy = t.Result;
-                    }
-                    return t;
-                }, TaskScheduler.Default).Unwrap();
-            }
-            else
-            { // This will call Read for DataRows, DataTable and IDataReader (this includes all IDataReader except DbDataReader)
-                _hasMoreRowToCopy = false;
-                try
-                {
-                    _hasMoreRowToCopy = ReadFromRowSource(); // Synchronous calls for DataRows and DataTable won't block. For IDataReader, it may block.
-                }
-                catch (Exception ex)
-                {
-                    if (_isAsyncBulkCopy)
-                    {
-                        return Task.FromException<bool>(ex);
-                    }
-                    else
-                    {
-                        throw;
-                    }
-                }
-                return null;
-            }
-        }
-
-        private bool ReadFromRowSource()
-        {
-            switch (_rowSourceType)
-            {
-                case ValueSourceType.DbDataReader:
-                case ValueSourceType.IDataReader:
-                    return ((IDataReader)_rowSource).Read();
-
-                // Treatment for RowArray case is same as for DataTable, prevent code duplicate
-                case ValueSourceType.RowArray:
-                case ValueSourceType.DataTable:
-                    Debug.Assert(_rowEnumerator != null, "uninitialized _rowEnumerator");
-                    Debug.Assert((_rowStateToSkip & DataRowState.Deleted) != 0, "Deleted is a permitted rowstate?");
-
-                    // Repeat until we get a row that is not deleted or there are no more rows
-                    do
-                    {
-                        if (!_rowEnumerator.MoveNext())
-                        {
-                            return false;
-                        }
-                        _currentRow = (DataRow)_rowEnumerator.Current;
-                    } while ((_currentRow.RowState & _rowStateToSkip) != 0); // Repeat if there is an unexpected rowstate
-
-                    _currentRowLength = _currentRow.ItemArray.Length;
-                    return true;
-
-                default:
-                    Debug.Fail("ValueSourcType unspecified");
-                    throw ADP.NotSupported();
-            }
-        }
-
-        private SourceColumnMetadata GetColumnMetadata(int ordinal)
-        {
-            int sourceOrdinal = _sortedColumnMappings[ordinal]._sourceColumnOrdinal;
-            _SqlMetaData metadata = _sortedColumnMappings[ordinal]._metadata;
-
-            // Handle special Sql data types for SqlDataReader and DataTables
-            ValueMethod method;
-            bool isSqlType;
-            bool isDataFeed;
-            if (((_SqlDataReaderRowSource != null) || (_dataTableSource != null)) && ((metadata.metaType.NullableType == TdsEnums.SQLDECIMALN) || (metadata.metaType.NullableType == TdsEnums.SQLNUMERICN)))
-            {
-                isDataFeed = false;
-
-                Type t;
-                switch (_rowSourceType)
-                {
-                    case ValueSourceType.DbDataReader:
-                    case ValueSourceType.IDataReader:
-                        t = _SqlDataReaderRowSource.GetFieldType(sourceOrdinal);
-                        break;
-                    case ValueSourceType.DataTable:
-                    case ValueSourceType.RowArray:
-                        t = _dataTableSource.Columns[sourceOrdinal].DataType;
-                        break;
-                    default:
-                        t = null;
-                        Debug.Fail($"Unknown value source: {_rowSourceType}");
-                        break;
-                }
-
-                if (typeof(SqlDecimal) == t || typeof(decimal) == t)
-                {
-                    isSqlType = true;
-                    method = ValueMethod.SqlTypeSqlDecimal;  // Source Type Decimal
-                }
-                else if (typeof(SqlDouble) == t || typeof(double) == t)
-                {
-                    isSqlType = true;
-                    method = ValueMethod.SqlTypeSqlDouble;  // Source Type SqlDouble
-                }
-                else if (typeof(SqlSingle) == t || typeof(float) == t)
-                {
-                    isSqlType = true;
-                    method = ValueMethod.SqlTypeSqlSingle;  // Source Type SqlSingle
-                }
-                else
-                {
-                    isSqlType = false;
-                    method = ValueMethod.GetValue;
-                }
-            }
-            // Check for data streams
-            else if ((_enableStreaming) && (metadata.length == MAX_LENGTH))
-            {
-                isSqlType = false;
-
-                if (_SqlDataReaderRowSource != null)
-                {
-                    // MetaData property is not set for SMI, but since streaming is disabled we do not need it
-                    MetaType mtSource = _SqlDataReaderRowSource.MetaData[sourceOrdinal].metaType;
-
-                    // There is no memory gain for non-sequential access for binary
-                    if ((metadata.type == SqlDbType.VarBinary) && (mtSource.IsBinType) && (mtSource.SqlDbType != SqlDbType.Timestamp) && _SqlDataReaderRowSource.IsCommandBehavior(CommandBehavior.SequentialAccess))
-                    {
-                        isDataFeed = true;
-                        method = ValueMethod.DataFeedStream;
-                    }
-                    // For text and XML there is memory gain from streaming on destination side even if reader is non-sequential
-                    else if (((metadata.type == SqlDbType.VarChar) || (metadata.type == SqlDbType.NVarChar)) && (mtSource.IsCharType) && (mtSource.SqlDbType != SqlDbType.Xml))
-                    {
-                        isDataFeed = true;
-                        method = ValueMethod.DataFeedText;
-                    }
-                    else if ((metadata.type == SqlDbType.Xml) && (mtSource.SqlDbType == SqlDbType.Xml))
-                    {
-                        isDataFeed = true;
-                        method = ValueMethod.DataFeedXml;
-                    }
-                    else
-                    {
-                        isDataFeed = false;
-                        method = ValueMethod.GetValue;
-                    }
-                }
-                else if (_DbDataReaderRowSource != null)
-                {
-                    if (metadata.type == SqlDbType.VarBinary)
-                    {
-                        isDataFeed = true;
-                        method = ValueMethod.DataFeedStream;
-                    }
-                    else if ((metadata.type == SqlDbType.VarChar) || (metadata.type == SqlDbType.NVarChar))
-                    {
-                        isDataFeed = true;
-                        method = ValueMethod.DataFeedText;
-                    }
-                    else
-                    {
-                        isDataFeed = false;
-                        method = ValueMethod.GetValue;
-                    }
-                }
-                else
-                {
-                    isDataFeed = false;
-                    method = ValueMethod.GetValue;
-                }
-            }
-            else
-            {
-                isSqlType = false;
-                isDataFeed = false;
-                method = ValueMethod.GetValue;
-            }
-
-            return new SourceColumnMetadata(method, isSqlType, isDataFeed);
-        }
-
-        private void CreateOrValidateConnection(string method)
-        {
-            if (null == _connection)
-            {
-                throw ADP.ConnectionRequired(method);
-            }
-
-            if (_ownConnection && _connection.State != ConnectionState.Open)
-            {
-                _connection.Open();
-            }
-
-            // Close any non-MARS dead readers, if applicable, and then throw if still busy.
-            _connection.ValidateConnectionForExecute(method, null);
-
-            // If we have a transaction, check to ensure that the active
-            // connection property matches the connection associated with
-            // the transaction.
-            if (null != _externalTransaction && _connection != _externalTransaction.Connection)
-            {
-                throw ADP.TransactionConnectionMismatch();
-            }
-        }
-
-        // Runs the _parser until it is done and ensures that ThreadHasParserLockForClose is correctly set and unset
-        // Ensure that you only call this inside of a Reliability Section
-        private void RunParser(BulkCopySimpleResultSet bulkCopyHandler = null)
-        {
-            // In case of error while reading, we should let the connection know that we already own the _parserLock
-            SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-
-            internalConnection.ThreadHasParserLockForClose = true;
-            try
-            {
-                _parser.Run(RunBehavior.UntilDone, null, null, bulkCopyHandler, _stateObj);
-            }
-            finally
-            {
-                internalConnection.ThreadHasParserLockForClose = false;
-            }
-        }
-
-        // Runs the _parser until it is done and ensures that ThreadHasParserLockForClose is correctly set and unset
-        // This takes care of setting up the Reliability Section, and will doom the connect if there is a catastrophic (OOM, StackOverflow, ThreadAbort) error
-        private void RunParserReliably(BulkCopySimpleResultSet bulkCopyHandler = null)
-        {
-            // In case of error while reading, we should let the connection know that we already own the _parserLock
-            SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-            internalConnection.ThreadHasParserLockForClose = true;
-            try
-            {
-                _parser.Run(RunBehavior.UntilDone, null, null, bulkCopyHandler, _stateObj);
-            }
-            finally
-            {
-                internalConnection.ThreadHasParserLockForClose = false;
-            }
-        }
-
-        private void CommitTransaction()
-        {
-            if (null != _internalTransaction)
-            {
-                SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-                internalConnection.ThreadHasParserLockForClose = true; // In case of error, let the connection know that we have the lock
-                try
-                {
-                    _internalTransaction.Commit();
-                    _internalTransaction.Dispose();
-                    _internalTransaction = null;
-                }
-                finally
-                {
-                    internalConnection.ThreadHasParserLockForClose = false;
-                }
-            }
-        }
-
-        private void AbortTransaction()
-        {
-            if (_internalTransaction != null)
-            {
-                if (!_internalTransaction.IsZombied)
-                {
-                    SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-                    internalConnection.ThreadHasParserLockForClose = true; // In case of error, let the connection know that we have the lock
-                    try
-                    {
-                        _internalTransaction.Rollback();
-                    }
-                    finally
-                    {
-                        internalConnection.ThreadHasParserLockForClose = false;
-                    }
-                }
-                _internalTransaction.Dispose();
-                _internalTransaction = null;
-            }
-        }
-
-        // Appends columnname in square brackets, a space, and the typename to the query.
-        // Putting the name in quotes also requires doubling existing ']' so that they are not mistaken for
-        // the closing quote.
-        // example: abc will become [abc] but abc[] will become [abc[]]]
-        private void AppendColumnNameAndTypeName(StringBuilder query, string columnName, string typeName)
-        {
-            SqlServerEscapeHelper.EscapeIdentifier(query, columnName);
-            query.Append(" ");
-            query.Append(typeName);
-        }
-
-        private string UnquotedName(string name)
-        {
-            if (string.IsNullOrEmpty(name)) return null;
-            if (name[0] == '[')
-            {
-                int l = name.Length;
-                Debug.Assert(name[l - 1] == ']', "Name starts with [ but does not end with ]");
-                name = name.Substring(1, l - 2);
-            }
-            return name;
-        }
-
-        private object ValidateBulkCopyVariant(object value)
-        {
-            // From the spec:
-            // "The only acceptable types are ..."
-            // GUID, BIGVARBINARY, BIGBINARY, BIGVARCHAR, BIGCHAR, NVARCHAR, NCHAR, BIT, INT1, INT2, INT4, INT8,
-            // MONEY4, MONEY, DECIMALN, NUMERICN, FTL4, FLT8, DATETIME4 and DATETIME
-            MetaType metatype = MetaType.GetMetaTypeFromValue(value);
-            switch (metatype.TDSType)
-            {
-                case TdsEnums.SQLFLT4:
-                case TdsEnums.SQLFLT8:
-                case TdsEnums.SQLINT8:
-                case TdsEnums.SQLINT4:
-                case TdsEnums.SQLINT2:
-                case TdsEnums.SQLINT1:
-                case TdsEnums.SQLBIT:
-                case TdsEnums.SQLBIGVARBINARY:
-                case TdsEnums.SQLBIGVARCHAR:
-                case TdsEnums.SQLUNIQUEID:
-                case TdsEnums.SQLNVARCHAR:
-                case TdsEnums.SQLDATETIME:
-                case TdsEnums.SQLMONEY:
-                case TdsEnums.SQLNUMERICN:
-                case TdsEnums.SQLDATE:
-                case TdsEnums.SQLTIME:
-                case TdsEnums.SQLDATETIME2:
-                case TdsEnums.SQLDATETIMEOFFSET:
-                    if (value is INullable)
-                    {   // Current limitation in the SqlBulkCopy Variant code limits BulkCopy to CLR/COM Types.
-                        return MetaType.GetComValueFromSqlVariant(value);
-                    }
-                    else
-                    {
-                        return value;
-                    }
-                default:
-                    throw SQL.BulkLoadInvalidVariantValue();
-            }
-        }
-
-        private object ConvertValue(object value, _SqlMetaData metadata, bool isNull, ref bool isSqlType, out bool coercedToDataFeed)
-        {
-            coercedToDataFeed = false;
-
-            if (isNull)
-            {
-                if (!metadata.IsNullable)
-                {
-                    throw SQL.BulkLoadBulkLoadNotAllowDBNull(metadata.column);
-                }
-                return value;
-            }
-
-            MetaType type = metadata.metaType;
-            bool typeChanged = false;
-            try
-            {
-                MetaType mt;
-                switch (type.NullableType)
-                {
-                    case TdsEnums.SQLNUMERICN:
-                    case TdsEnums.SQLDECIMALN:
-                        mt = MetaType.GetMetaTypeFromSqlDbType(type.SqlDbType, false);
-                        value = SqlParameter.CoerceValue(value, mt, out coercedToDataFeed, out typeChanged, false);
-
-                        // Convert Source Decimal Precision and Scale to Destination Precision and Scale
-                        // Sql decimal data could get corrupted on insert if the scale of
-                        // the source and destination weren't the same. The BCP protocol, specifies the
-                        // scale of the incoming data in the insert statement, we just tell the server we
-                        // are inserting the same scale back.
-                        SqlDecimal sqlValue;
-                        if ((isSqlType) && (!typeChanged))
-                        {
-                            sqlValue = (SqlDecimal)value;
-                        }
-                        else
-                        {
-                            sqlValue = new SqlDecimal((decimal)value);
-                        }
-
-                        if (sqlValue.Scale != metadata.scale)
-                        {
-                            sqlValue = TdsParser.AdjustSqlDecimalScale(sqlValue, metadata.scale);
-                        }
-
-                        if (sqlValue.Precision > metadata.precision)
-                        {
-                            try
-                            {
-                                sqlValue = SqlDecimal.ConvertToPrecScale(sqlValue, metadata.precision, sqlValue.Scale);
-                            }
-                            catch (SqlTruncateException)
-                            {
-                                throw SQL.BulkLoadCannotConvertValue(value.GetType(), mt, ADP.ParameterValueOutOfRange(sqlValue));
-                            }
-                        }
-
-                        // Perf: It is more efficient to write a SqlDecimal than a decimal since we need to break it into its 'bits' when writing
-                        value = sqlValue;
-                        isSqlType = true;
-                        typeChanged = false; // Setting this to false as SqlParameter.CoerceValue will only set it to true when converting to a CLR type
-                        break;
-
-                    case TdsEnums.SQLINTN:
-                    case TdsEnums.SQLFLTN:
-                    case TdsEnums.SQLFLT4:
-                    case TdsEnums.SQLFLT8:
-                    case TdsEnums.SQLMONEYN:
-                    case TdsEnums.SQLDATETIM4:
-                    case TdsEnums.SQLDATETIME:
-                    case TdsEnums.SQLDATETIMN:
-                    case TdsEnums.SQLBIT:
-                    case TdsEnums.SQLBITN:
-                    case TdsEnums.SQLUNIQUEID:
-                    case TdsEnums.SQLBIGBINARY:
-                    case TdsEnums.SQLBIGVARBINARY:
-                    case TdsEnums.SQLIMAGE:
-                    case TdsEnums.SQLBIGCHAR:
-                    case TdsEnums.SQLBIGVARCHAR:
-                    case TdsEnums.SQLTEXT:
-                    case TdsEnums.SQLDATE:
-                    case TdsEnums.SQLTIME:
-                    case TdsEnums.SQLDATETIME2:
-                    case TdsEnums.SQLDATETIMEOFFSET:
-                        mt = MetaType.GetMetaTypeFromSqlDbType(type.SqlDbType, false);
-                        value = SqlParameter.CoerceValue(value, mt, out coercedToDataFeed, out typeChanged, false);
-                        break;
-                    case TdsEnums.SQLNCHAR:
-                    case TdsEnums.SQLNVARCHAR:
-                    case TdsEnums.SQLNTEXT:
-                        mt = MetaType.GetMetaTypeFromSqlDbType(type.SqlDbType, false);
-                        value = SqlParameter.CoerceValue(value, mt, out coercedToDataFeed, out typeChanged, false);
-                        if (!coercedToDataFeed)
-                        {   // We do not need to test for TextDataFeed as it is only assigned to (N)VARCHAR(MAX)
-                            int len = ((isSqlType) && (!typeChanged)) ? ((SqlString)value).Value.Length : ((string)value).Length;
-                            if (len > metadata.length / 2)
-                            {
-                                throw SQL.BulkLoadStringTooLong();
-                            }
-                        }
-                        break;
-                    case TdsEnums.SQLVARIANT:
-                        value = ValidateBulkCopyVariant(value);
-                        typeChanged = true;
-                        break;
-                    case TdsEnums.SQLUDT:
-                        // UDTs are sent as varbinary so we need to get the raw bytes
-                        // unlike other types the parser does not like SQLUDT in form of SqlType
-                        // so we cast to a CLR type.
-
-                        // Hack for type system version knob - only call GetBytes if the value is not already
-                        // in byte[] form.
-                        if (!(value is byte[]))
-                        {
-                            value = _connection.GetBytes(value);
-                            typeChanged = true;
-                        }
-                        break;
-                    case TdsEnums.SQLXMLTYPE:
-                        // Could be either string, SqlCachedBuffer, XmlReader or XmlDataFeed
-                        Debug.Assert((value is XmlReader) || (value is SqlCachedBuffer) || (value is string) || (value is SqlString) || (value is XmlDataFeed), "Invalid value type of Xml datatype");
-                        if (value is XmlReader)
-                        {
-                            value = new XmlDataFeed((XmlReader)value);
-                            typeChanged = true;
-                            coercedToDataFeed = true;
-                        }
-                        break;
-
-                    default:
-                        Debug.Fail("Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
-                        throw SQL.BulkLoadCannotConvertValue(value.GetType(), metadata.metaType, null);
-                }
-
-                if (typeChanged)
-                {
-                    // All type changes change to CLR types
-                    isSqlType = false;
-                }
-
-                return value;
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-                throw SQL.BulkLoadCannotConvertValue(value.GetType(), metadata.metaType, e);
-            }
-        }
-
-        public void WriteToServer(DbDataReader reader)
-        {
-            if (reader == null)
-            {
-                throw new ArgumentNullException(nameof(reader));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            SqlStatistics statistics = Statistics;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                _rowSource = reader;
-                _DbDataReaderRowSource = reader;
-                _SqlDataReaderRowSource = reader as SqlDataReader;
-
-                _dataTableSource = null;
-                _rowSourceType = ValueSourceType.DbDataReader;
-
-                _isAsyncBulkCopy = false;
-                WriteRowSourceToServerAsync(reader.FieldCount, CancellationToken.None); //It returns null since _isAsyncBulkCopy = false;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public void WriteToServer(IDataReader reader)
-        {
-            if (reader == null)
-            {
-                throw new ArgumentNullException(nameof(reader));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            SqlStatistics statistics = Statistics;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                _rowSource = reader;
-                _SqlDataReaderRowSource = _rowSource as SqlDataReader;
-                _DbDataReaderRowSource = _rowSource as DbDataReader;
-                _dataTableSource = null;
-                _rowSourceType = ValueSourceType.IDataReader;
-                _isAsyncBulkCopy = false;
-                WriteRowSourceToServerAsync(reader.FieldCount, CancellationToken.None); //It returns null since _isAsyncBulkCopy = false;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public void WriteToServer(DataTable table) => WriteToServer(table, 0);
-
-        public void WriteToServer(DataTable table, DataRowState rowState)
-        {
-            if (table == null)
-            {
-                throw new ArgumentNullException(nameof(table));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            SqlStatistics statistics = Statistics;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                _rowStateToSkip = ((rowState == 0) || (rowState == DataRowState.Deleted)) ? DataRowState.Deleted : ~rowState | DataRowState.Deleted;
-                _rowSource = table;
-                _dataTableSource = table;
-                _SqlDataReaderRowSource = null;
-                _rowSourceType = ValueSourceType.DataTable;
-                _rowEnumerator = table.Rows.GetEnumerator();
-                _isAsyncBulkCopy = false;
-
-                WriteRowSourceToServerAsync(table.Columns.Count, CancellationToken.None); //It returns null since _isAsyncBulkCopy = false;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public void WriteToServer(DataRow[] rows)
-        {
-            SqlStatistics statistics = Statistics;
-
-            if (rows == null)
-            {
-                throw new ArgumentNullException(nameof(rows));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            if (rows.Length == 0)
-            {
-                return; // Nothing to do. user passed us an empty array
-            }
-
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                DataTable table = rows[0].Table;
-                Debug.Assert(null != table, "How can we have rows without a table?");
-                _rowStateToSkip = DataRowState.Deleted;      // Don't allow deleted rows
-                _rowSource = rows;
-                _dataTableSource = table;
-                _SqlDataReaderRowSource = null;
-                _rowSourceType = ValueSourceType.RowArray;
-                _rowEnumerator = rows.GetEnumerator();
-                _isAsyncBulkCopy = false;
-
-                WriteRowSourceToServerAsync(table.Columns.Count, CancellationToken.None); //It returns null since _isAsyncBulkCopy = false;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public Task WriteToServerAsync(DataRow[] rows) => WriteToServerAsync(rows, CancellationToken.None);
-
-        public Task WriteToServerAsync(DataRow[] rows, CancellationToken cancellationToken)
-        {
-            Task resultTask = null;
-
-            if (rows == null)
-            {
-                throw new ArgumentNullException(nameof(rows));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            SqlStatistics statistics = Statistics;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                if (rows.Length == 0)
-                {
-                    return cancellationToken.IsCancellationRequested ?
-                            Task.FromCanceled(cancellationToken) :
-                            Task.CompletedTask;
-                }
-
-                DataTable table = rows[0].Table;
-                Debug.Assert(null != table, "How can we have rows without a table?");
-                _rowStateToSkip = DataRowState.Deleted; // Don't allow deleted rows
-                _rowSource = rows;
-                _dataTableSource = table;
-                _SqlDataReaderRowSource = null;
-                _rowSourceType = ValueSourceType.RowArray;
-                _rowEnumerator = rows.GetEnumerator();
-                _isAsyncBulkCopy = true;
-                resultTask = WriteRowSourceToServerAsync(table.Columns.Count, cancellationToken); // It returns Task since _isAsyncBulkCopy = true;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-            return resultTask;
-        }
-
-        public Task WriteToServerAsync(DbDataReader reader) => WriteToServerAsync(reader, CancellationToken.None);
-
-        public Task WriteToServerAsync(DbDataReader reader, CancellationToken cancellationToken)
-        {
-            Task resultTask = null;
-            if (reader == null)
-            {
-                throw new ArgumentNullException(nameof(reader));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            SqlStatistics statistics = Statistics;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                _rowSource = reader;
-                _SqlDataReaderRowSource = reader as SqlDataReader;
-                _DbDataReaderRowSource = reader;
-                _dataTableSource = null;
-                _rowSourceType = ValueSourceType.DbDataReader;
-                _isAsyncBulkCopy = true;
-                resultTask = WriteRowSourceToServerAsync(reader.FieldCount, cancellationToken); // It returns Task since _isAsyncBulkCopy = true;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-            return resultTask;
-        }
-
-        public Task WriteToServerAsync(IDataReader reader) => WriteToServerAsync(reader, CancellationToken.None);
-
-        public Task WriteToServerAsync(IDataReader reader, CancellationToken cancellationToken)
-        {
-            Task resultTask = null;
-
-            if (reader == null)
-            {
-                throw new ArgumentNullException(nameof(reader));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            SqlStatistics statistics = Statistics;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                _rowSource = reader;
-                _SqlDataReaderRowSource = _rowSource as SqlDataReader;
-                _DbDataReaderRowSource = _rowSource as DbDataReader;
-                _dataTableSource = null;
-                _rowSourceType = ValueSourceType.IDataReader;
-                _isAsyncBulkCopy = true;
-                resultTask = WriteRowSourceToServerAsync(reader.FieldCount, cancellationToken); // It returns Task since _isAsyncBulkCopy = true;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-            return resultTask;
-        }
-
-        public Task WriteToServerAsync(DataTable table) => WriteToServerAsync(table, 0, CancellationToken.None);
-
-        public Task WriteToServerAsync(DataTable table, CancellationToken cancellationToken) => WriteToServerAsync(table, 0, cancellationToken);
-
-        public Task WriteToServerAsync(DataTable table, DataRowState rowState) => WriteToServerAsync(table, rowState, CancellationToken.None);
-
-        public Task WriteToServerAsync(DataTable table, DataRowState rowState, CancellationToken cancellationToken)
-        {
-            Task resultTask = null;
-
-            if (table == null)
-            {
-                throw new ArgumentNullException(nameof(table));
-            }
-
-            if (_isBulkCopyingInProgress)
-            {
-                throw SQL.BulkLoadPendingOperation();
-            }
-
-            SqlStatistics statistics = Statistics;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                _rowStateToSkip = ((rowState == 0) || (rowState == DataRowState.Deleted)) ? DataRowState.Deleted : ~rowState | DataRowState.Deleted;
-                _rowSource = table;
-                _SqlDataReaderRowSource = null;
-                _dataTableSource = table;
-                _rowSourceType = ValueSourceType.DataTable;
-                _rowEnumerator = table.Rows.GetEnumerator();
-                _isAsyncBulkCopy = true;
-                resultTask = WriteRowSourceToServerAsync(table.Columns.Count, cancellationToken); // It returns Task since _isAsyncBulkCopy = true;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-            return resultTask;
-        }
-
-        private Task WriteRowSourceToServerAsync(int columnCount, CancellationToken ctoken)
-        {
-            Task reconnectTask = _connection._currentReconnectionTask;
-            if (reconnectTask != null && !reconnectTask.IsCompleted)
-            {
-                if (_isAsyncBulkCopy)
-                {
-                    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
-                    reconnectTask.ContinueWith((t) =>
-                    {
-                        Task writeTask = WriteRowSourceToServerAsync(columnCount, ctoken);
-                        if (writeTask == null)
-                        {
-                            tcs.SetResult(null);
-                        }
-                        else
-                        {
-                            AsyncHelper.ContinueTaskWithState(writeTask, tcs,
-                                state: tcs,
-                                onSuccess: state => ((TaskCompletionSource<object>)state).SetResult(null)
-                            );
-                        }
-                    }, ctoken, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); // We do not need to propagate exception, etc, from reconnect task, we just need to wait for it to finish.
-                    return tcs.Task;
-                }
-                else
-                {
-                    AsyncHelper.WaitForCompletion(reconnectTask, BulkCopyTimeout, () => { throw SQL.CR_ReconnectTimeout(); }, rethrowExceptions: false);
-                }
-            }
-
-            bool finishedSynchronously = true;
-            _isBulkCopyingInProgress = true;
-
-            CreateOrValidateConnection(nameof(WriteToServer));
-            SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-
-            Debug.Assert(_parserLock == null, "Previous parser lock not cleaned");
-            _parserLock = internalConnection._parserLock;
-            _parserLock.Wait(canReleaseFromAnyThread: _isAsyncBulkCopy);
-
-            try
-            {
-                WriteRowSourceToServerCommon(columnCount); // This is common in both sync and async
-                Task resultTask = WriteToServerInternalAsync(ctoken); // resultTask is null for sync, but Task for async.
-                if (resultTask != null)
-                {
-                    finishedSynchronously = false;
-                    return resultTask.ContinueWith((t) =>
-                    {
-                        try
-                        {
-                            AbortTransaction(); // If there is one, on success transactions will be committed.
-                        }
-                        finally
-                        {
-                            _isBulkCopyingInProgress = false;
-                            if (_parser != null)
-                            {
-                                _parser._asyncWrite = false;
-                            }
-                            if (_parserLock != null)
-                            {
-                                _parserLock.Release();
-                                _parserLock = null;
-                            }
-                        }
-                        return t;
-                    }, TaskScheduler.Default).Unwrap();
-                }
-                return null;
-            }
-            catch (System.OutOfMemoryException e)
-            {
-                _connection.Abort(e);
-                throw;
-            }
-            catch (System.StackOverflowException e)
-            {
-                _connection.Abort(e);
-                throw;
-            }
-            catch (System.Threading.ThreadAbortException e)
-            {
-                _connection.Abort(e);
-                throw;
-            }
-            finally
-            {
-                _columnMappings.ReadOnly = false;
-                if (finishedSynchronously)
-                {
-                    try
-                    {
-                        AbortTransaction(); // If there is one, on success transactions will be committed.
-                    }
-                    finally
-                    {
-                        _isBulkCopyingInProgress = false;
-                        if (_parser != null)
-                        {
-                            _parser._asyncWrite = false;
-                        }
-                        if (_parserLock != null)
-                        {
-                            _parserLock.Release();
-                            _parserLock = null;
-                        }
-                    }
-                }
-            }
-        }
-
-        // Handles the column mapping.
-        private void WriteRowSourceToServerCommon(int columnCount)
-        {
-            bool unspecifiedColumnOrdinals = false;
-
-            _columnMappings.ReadOnly = true;
-            _localColumnMappings = _columnMappings;
-            if (_localColumnMappings.Count > 0)
-            {
-                _localColumnMappings.ValidateCollection();
-                foreach (SqlBulkCopyColumnMapping bulkCopyColumn in _localColumnMappings)
-                {
-                    if (bulkCopyColumn._internalSourceColumnOrdinal == -1)
-                    {
-                        unspecifiedColumnOrdinals = true;
-                        break;
-                    }
-                }
-            }
-            else
-            {
-                _localColumnMappings = new SqlBulkCopyColumnMappingCollection();
-                _localColumnMappings.CreateDefaultMapping(columnCount);
-            }
-
-            // perf: If the user specified all column ordinals we do not need to get a schematable
-            if (unspecifiedColumnOrdinals)
-            {
-                int index = -1;
-                unspecifiedColumnOrdinals = false;
-
-                // Match up sourceColumn names with sourceColumn ordinals
-                if (_localColumnMappings.Count > 0)
-                {
-                    foreach (SqlBulkCopyColumnMapping bulkCopyColumn in _localColumnMappings)
-                    {
-                        if (bulkCopyColumn._internalSourceColumnOrdinal == -1)
-                        {
-                            string unquotedColumnName = UnquotedName(bulkCopyColumn.SourceColumn);
-
-                            switch (_rowSourceType)
-                            {
-                                case ValueSourceType.DataTable:
-                                    index = ((DataTable)_rowSource).Columns.IndexOf(unquotedColumnName);
-                                    break;
-                                case ValueSourceType.RowArray:
-                                    index = ((DataRow[])_rowSource)[0].Table.Columns.IndexOf(unquotedColumnName);
-                                    break;
-                                case ValueSourceType.DbDataReader:
-                                case ValueSourceType.IDataReader:
-                                    try
-                                    {
-                                        index = ((IDataReader)_rowSource).GetOrdinal(unquotedColumnName);
-                                    }
-                                    catch (IndexOutOfRangeException e)
-                                    {
-                                        throw (SQL.BulkLoadNonMatchingColumnName(unquotedColumnName, e));
-                                    }
-                                    break;
-                            }
-
-                            if (index == -1)
-                            {
-                                throw (SQL.BulkLoadNonMatchingColumnName(unquotedColumnName));
-                            }
-                            bulkCopyColumn._internalSourceColumnOrdinal = index;
-                        }
-                    }
-                }
-            }
-        }
-
-        internal void OnConnectionClosed()
-        {
-            TdsParserStateObject stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                stateObj.OnConnectionClosed();
-            }
-        }
-
-        private void OnRowsCopied(SqlRowsCopiedEventArgs value)
-        {
-            SqlRowsCopiedEventHandler handler = _rowsCopiedEventHandler;
-            if (handler != null)
-            {
-                handler(this, value);
-            }
-        }
-
-        private bool FireRowsCopiedEvent(long rowsCopied)
-        {
-            // Release lock to prevent possible deadlocks
-            SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-            bool semaphoreLock = internalConnection._parserLock.CanBeReleasedFromAnyThread;
-            internalConnection._parserLock.Release();
-
-            SqlRowsCopiedEventArgs eventArgs = new SqlRowsCopiedEventArgs(rowsCopied);
-            try
-            {
-                _insideRowsCopiedEvent = true;
-                this.OnRowsCopied(eventArgs);
-            }
-            finally
-            {
-                _insideRowsCopiedEvent = false;
-                internalConnection._parserLock.Wait(canReleaseFromAnyThread: semaphoreLock);
-            }
-            return eventArgs.Abort;
-        }
-
-        // Reads a cell and then writes it.
-        // Read may block at this moment since there is no getValueAsync or DownStream async at this moment.
-        // When _isAsyncBulkCopy == true: Write will return Task (when async method runs asynchronously) or Null (when async call actually ran synchronously) for performance.
-        // When _isAsyncBulkCopy == false: Writes are purely sync. This method return null at the end.
-        private Task ReadWriteColumnValueAsync(int col)
-        {
-            bool isSqlType;
-            bool isDataFeed;
-            bool isNull;
-            object value = GetValueFromSourceRow(col, out isSqlType, out isDataFeed, out isNull); //this will return Task/null in future: as rTask
-
-            _SqlMetaData metadata = _sortedColumnMappings[col]._metadata;
-            if (!isDataFeed)
-            {
-                value = ConvertValue(value, metadata, isNull, ref isSqlType, out isDataFeed);
-            }
-
-            //write part
-            Task writeTask = null;
-            if (metadata.type != SqlDbType.Variant)
-            {
-                //this is the most common path
-                writeTask = _parser.WriteBulkCopyValue(value, metadata, _stateObj, isSqlType, isDataFeed, isNull); //returns Task/Null
-            }
-            else
-            {
-                SqlBuffer.StorageType variantInternalType = SqlBuffer.StorageType.Empty;
-                if ((_SqlDataReaderRowSource != null) && (_connection.IsKatmaiOrNewer))
-                {
-                    variantInternalType = _SqlDataReaderRowSource.GetVariantInternalStorageType(_sortedColumnMappings[col]._sourceColumnOrdinal);
-                }
-
-                if (variantInternalType == SqlBuffer.StorageType.DateTime2)
-                {
-                    _parser.WriteSqlVariantDateTime2(((DateTime)value), _stateObj);
-                }
-                else if (variantInternalType == SqlBuffer.StorageType.Date)
-                {
-                    _parser.WriteSqlVariantDate(((DateTime)value), _stateObj);
-                }
-                else
-                {
-                    writeTask = _parser.WriteSqlVariantDataRowValue(value, _stateObj); //returns Task/Null
-                }
-            }
-
-            return writeTask;
-        }
-
-        private void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask)
-        {
-            SqlConnection connection = _connection;
-            if (connection == null)
-            {
-                // No connection
-                throw ADP.ClosedConnectionError();
-            }
-
-            connection.RegisterForConnectionCloseNotification<T>(ref outerTask, this, SqlReferenceCollection.BulkCopyTag);
-        }
-
-        // Runs a loop to copy all columns of a single row.
-        // Maintains a state by remembering #columns copied so far (int col).
-        // Returned Task could be null in two cases: (1) _isAsyncBulkCopy == false, (2) _isAsyncBulkCopy == true but all async writes finished synchronously.
-        private Task CopyColumnsAsync(int col, TaskCompletionSource<object> source = null)
-        {
-            Task resultTask = null, task = null;
-            int i;
-            try
-            {
-                for (i = col; i < _sortedColumnMappings.Count; i++)
-                {
-                    task = ReadWriteColumnValueAsync(i); //First reads and then writes one cell value. Task 'task' is completed when reading task and writing task both are complete.
-                    if (task != null) break; //task != null means we have a pending read/write Task.
-                }
-                if (task != null)
-                {
-                    if (source == null)
-                    {
-                        source = new TaskCompletionSource<object>();
-                        resultTask = source.Task;
-                    }
-                    CopyColumnsAsyncSetupContinuation(source, task, i);
-                    return resultTask; //associated task will be completed when all columns (i.e. the entire row) is written
-                }
-                if (source != null)
-                {
-                    source.SetResult(null);
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                }
-                else
-                {
-                    throw;
-                }
-            }
-            return resultTask;
-        }
-
-        // This is in its own method to avoid always allocating the lambda in CopyColumnsAsync
-        private void CopyColumnsAsyncSetupContinuation(TaskCompletionSource<object> source, Task task, int i)
-        {
-            AsyncHelper.ContinueTask(task, source, () =>
-                {
-                    if (i + 1 < _sortedColumnMappings.Count)
-                    {
-                        CopyColumnsAsync(i + 1, source); //continue from the next column
-                    }
-                    else
-                    {
-                        source.SetResult(null);
-                    }
-                }
-            );
-        }
-
-        // The notification logic.
-        private void CheckAndRaiseNotification()
-        {
-            bool abortOperation = false; //returns if the operation needs to be aborted.
-            Exception exception = null;
-
-            _rowsCopied++;
-
-            // Fire event logic
-            if (_notifyAfter > 0)
-            {
-                if (_rowsUntilNotification > 0)
-                {
-                    if (--_rowsUntilNotification == 0)
-                    {
-                        // Fire event during operation. This is the users chance to abort the operation.
-                        try
-                        {
-                            // It's also the user's chance to cause an exception.
-                            _stateObj.BcpLock = true;
-                            abortOperation = FireRowsCopiedEvent(_rowsCopied);
-
-                            // In case the target connection is closed accidentally.
-                            if (ConnectionState.Open != _connection.State)
-                            {
-                                exception = ADP.OpenConnectionRequired(nameof(CheckAndRaiseNotification), _connection.State);
-                            }
-                        }
-                        catch (Exception e)
-                        {
-                            if (!ADP.IsCatchableExceptionType(e))
-                            {
-                                exception = e;
-                            }
-                            else
-                            {
-                                exception = OperationAbortedException.Aborted(e);
-                            }
-                        }
-                        finally
-                        {
-                            _stateObj.BcpLock = false;
-                        }
-                        if (!abortOperation)
-                        {
-                            _rowsUntilNotification = _notifyAfter;
-                        }
-                    }
-                }
-            }
-            if (!abortOperation && _rowsUntilNotification > _notifyAfter)
-            {
-                _rowsUntilNotification = _notifyAfter;      // Update on decrement of count
-            }
-            if (exception == null && abortOperation)
-            {
-                exception = OperationAbortedException.Aborted(null);
-            }
-            if (_connection.State != ConnectionState.Open)
-            {
-                throw ADP.OpenConnectionRequired(nameof(WriteToServer), _connection.State);
-            }
-            if (exception != null)
-            {
-                _parser._asyncWrite = false;
-                Task writeTask = _parser.WriteBulkCopyDone(_stateObj); //We should complete the current batch up to this row.
-                Debug.Assert(writeTask == null, "Task should not pend while doing sync bulk copy");
-                RunParser();
-                AbortTransaction();
-                throw exception; //this will be caught and put inside the Task's exception.
-            }
-        }
-
-        // Checks for cancellation. If cancel requested, cancels the task and returns the cancelled task
-        private Task CheckForCancellation(CancellationToken cts, TaskCompletionSource<object> tcs)
-        {
-            if (cts.IsCancellationRequested)
-            {
-                if (tcs == null)
-                {
-                    tcs = new TaskCompletionSource<object>();
-                }
-                tcs.SetCanceled();
-                return tcs.Task;
-            }
-            else
-            {
-                return null;
-            }
-        }
-
-        // Copies all the rows in a batch.
-        // Maintains state machine with state variable: rowSoFar.
-        // Returned Task could be null in two cases: (1) _isAsyncBulkCopy == false, or (2) _isAsyncBulkCopy == true but all async writes finished synchronously.
-        private Task CopyRowsAsync(int rowsSoFar, int totalRows, CancellationToken cts, TaskCompletionSource<object> source = null)
-        {
-            Task resultTask = null;
-            Task task = null;
-            int i;
-            try
-            {
-                // totalRows is batchsize which is 0 by default. In that case, we keep copying till the end (until _hasMoreRowToCopy == false).
-                for (i = rowsSoFar; (totalRows <= 0 || i < totalRows) && _hasMoreRowToCopy == true; i++)
-                {
-                    if (_isAsyncBulkCopy == true)
-                    {
-                        resultTask = CheckForCancellation(cts, source);
-                        if (resultTask != null)
-                        {
-                            return resultTask; // Task got cancelled!
-                        }
-                    }
-
-                    _stateObj.WriteByte(TdsEnums.SQLROW);
-
-                    task = CopyColumnsAsync(0); // Copy 1 row
-
-                    if (task == null)
-                    {   // Task is done.
-                        CheckAndRaiseNotification(); // Check notification logic after copying the row
-
-                        // Now we will read the next row.
-                        Task readTask = ReadFromRowSourceAsync(cts); // Read the next row. Caution: more is only valid if the task returns null. Otherwise, we wait for Task.Result
-                        if (readTask != null)
-                        {
-                            if (source == null)
-                            {
-                                source = new TaskCompletionSource<object>();
-                            }
-                            resultTask = source.Task;
-
-                            AsyncHelper.ContinueTask(readTask, source, () => CopyRowsAsync(i + 1, totalRows, cts, source));
-                            return resultTask; // Associated task will be completed when all rows are copied to server/exception/cancelled.
-                        }
-                    }
-                    else
-                    {   // task != null, so add continuation for it.
-                        source = source ?? new TaskCompletionSource<object>();
-                        resultTask = source.Task;
-
-                        AsyncHelper.ContinueTask(task, source, onSuccess: () =>
-                            {
-                                CheckAndRaiseNotification(); // Check for notification now as the current row copy is done at this moment.
-
-                                Task readTask = ReadFromRowSourceAsync(cts);
-                                if (readTask == null)
-                                {
-                                    CopyRowsAsync(i + 1, totalRows, cts, source);
-                                }
-                                else
-                                {
-                                    AsyncHelper.ContinueTask(readTask, source, onSuccess: () => CopyRowsAsync(i + 1, totalRows, cts, source));
-                                }
-                            }
-                        );
-                        return resultTask;
-                    }
-                }
-
-                if (source != null)
-                {
-                    source.TrySetResult(null); // This is set only on the last call of async copy. But may not be set if everything runs synchronously.
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                }
-                else
-                {
-                    throw;
-                }
-            }
-            return resultTask;
-        }
-
-        // Copies all the batches in a loop. One iteration for one batch.
-        // state variable is essentially not needed. (however, _hasMoreRowToCopy might be thought as a state variable)
-        // Returned Task could be null in two cases: (1) _isAsyncBulkCopy == false, or (2) _isAsyncBulkCopy == true but all async writes finished synchronously.
-        private Task CopyBatchesAsync(BulkCopySimpleResultSet internalResults, string updateBulkCommandText, CancellationToken cts, TaskCompletionSource<object> source = null)
-        {
-            Debug.Assert(source == null || !source.Task.IsCompleted, "Called into CopyBatchesAsync with a completed task!");
-            try
-            {
-                while (_hasMoreRowToCopy)
-                {
-                    //pre->before every batch: Transaction, BulkCmd and metadata are done.
-                    SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-
-                    if (IsCopyOption(SqlBulkCopyOptions.UseInternalTransaction))
-                    { //internal transaction is started prior to each batch if the Option is set.
-                        internalConnection.ThreadHasParserLockForClose = true;     // In case of error, tell the connection we already have the parser lock
-                        try
-                        {
-                            _internalTransaction = _connection.BeginTransaction();
-                        }
-                        finally
-                        {
-                            internalConnection.ThreadHasParserLockForClose = false;
-                        }
-                    }
-
-                    Task commandTask = SubmitUpdateBulkCommand(updateBulkCommandText);
-
-                    if (commandTask == null)
-                    {
-                        Task continuedTask = CopyBatchesAsyncContinued(internalResults, updateBulkCommandText, cts, source);
-                        if (continuedTask != null)
-                        {
-                            // Continuation will take care of re-calling CopyBatchesAsync
-                            return continuedTask;
-                        }
-                    }
-                    else
-                    {
-                        Debug.Assert(_isAsyncBulkCopy, "Task should not pend while doing sync bulk copy");
-                        if (source == null)
-                        {
-                            source = new TaskCompletionSource<object>();
-                        }
-
-                        AsyncHelper.ContinueTask(commandTask, source,
-                            () =>
-                            {
-                                Task continuedTask = CopyBatchesAsyncContinued(internalResults, updateBulkCommandText, cts, source);
-                                if (continuedTask == null)
-                                {
-                                    // Continuation finished sync, recall into CopyBatchesAsync to continue
-                                    CopyBatchesAsync(internalResults, updateBulkCommandText, cts, source);
-                                }
-                            }
-                        );
-                        return source.Task;
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                    return source.Task;
-                }
-                else
-                {
-                    throw;
-                }
-            }
-
-            // If we are here, then we finished everything
-            if (source != null)
-            {
-                source.SetResult(null);
-                return source.Task;
-            }
-            else
-            {
-                return null;
-            }
-        }
-
-        // Writes the MetaData and a single batch.
-        // If this returns true, then the caller is responsible for starting the next stage.
-        private Task CopyBatchesAsyncContinued(BulkCopySimpleResultSet internalResults, string updateBulkCommandText, CancellationToken cts, TaskCompletionSource<object> source)
-        {
-            Debug.Assert(source == null || !source.Task.IsCompleted, "Called into CopyBatchesAsync with a completed task!");
-            try
-            {
-                WriteMetaData(internalResults);
-                Task task = CopyRowsAsync(0, _savedBatchSize, cts); // This is copying 1 batch of rows and setting _hasMoreRowToCopy = true/false.
-
-                // post->after every batch
-                if (task != null)
-                {
-                    Debug.Assert(_isAsyncBulkCopy, "Task should not pend while doing sync bulk copy");
-                    if (source == null)
-                    {   // First time only
-                        source = new TaskCompletionSource<object>();
-                    }
-                    AsyncHelper.ContinueTask(task, source,
-                        onSuccess: () =>
-                        {
-                            Task continuedTask = CopyBatchesAsyncContinuedOnSuccess(internalResults, updateBulkCommandText, cts, source);
-                            if (continuedTask == null)
-                            {
-                                // Continuation finished sync, recall into CopyBatchesAsync to continue
-                                CopyBatchesAsync(internalResults, updateBulkCommandText, cts, source);
-                            }
-                        },
-                        onFailure: (_) => CopyBatchesAsyncContinuedOnError(cleanupParser: false),
-                        onCancellation: () => CopyBatchesAsyncContinuedOnError(cleanupParser: true)
-                    );
-
-                    return source.Task;
-                }
-                else
-                {
-                    return CopyBatchesAsyncContinuedOnSuccess(internalResults, updateBulkCommandText, cts, source);
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                    return source.Task;
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        // Takes care of finishing a single batch (write done, run parser, commit transaction).
-        // If this returns true, then the caller is responsible for starting the next stage.
-        private Task CopyBatchesAsyncContinuedOnSuccess(BulkCopySimpleResultSet internalResults, string updateBulkCommandText, CancellationToken cts, TaskCompletionSource<object> source)
-        {
-            Debug.Assert(source == null || !source.Task.IsCompleted, "Called into CopyBatchesAsync with a completed task!");
-            try
-            {
-                Task writeTask = _parser.WriteBulkCopyDone(_stateObj);
-
-                if (writeTask == null)
-                {
-                    RunParser();
-                    CommitTransaction();
-
-                    return null;
-                }
-                else
-                {
-                    Debug.Assert(_isAsyncBulkCopy, "Task should not pend while doing sync bulk copy");
-                    if (source == null)
-                    {
-                        source = new TaskCompletionSource<object>();
-                    }
-
-                    AsyncHelper.ContinueTask(writeTask, source,
-                        onSuccess: () =>
-                        {
-                            try
-                            {
-                                RunParser();
-                                CommitTransaction();
-                            }
-                            catch (Exception)
-                            {
-                                CopyBatchesAsyncContinuedOnError(cleanupParser: false);
-                                throw;
-                            }
-
-                            // Always call back into CopyBatchesAsync
-                            CopyBatchesAsync(internalResults, updateBulkCommandText, cts, source);
-                        },
-                        onFailure: (_) => CopyBatchesAsyncContinuedOnError(cleanupParser: false)
-                    );
-                    return source.Task;
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                    return source.Task;
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        // Takes care of cleaning up the parser, stateObj and transaction when CopyBatchesAsync fails.
-        private void CopyBatchesAsyncContinuedOnError(bool cleanupParser)
-        {
-            SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-            try
-            {
-                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();
-                }
-            }
-            catch (OutOfMemoryException)
-            {
-                internalConnection.DoomThisConnection();
-                throw;
-            }
-            catch (StackOverflowException)
-            {
-                internalConnection.DoomThisConnection();
-                throw;
-            }
-            catch (ThreadAbortException)
-            {
-                internalConnection.DoomThisConnection();
-                throw;
-            }
-
-            AbortTransaction();
-        }
-
-        // Cleans the stateobj. Used in a number of places, specially in  exceptions.
-        private void CleanUpStateObject(bool isCancelRequested = true)
-        {
-            if (_stateObj != null)
-            {
-                _parser.Connection.ThreadHasParserLockForClose = true;
-                try
-                {
-                    _stateObj.ResetBuffer();
-                    _stateObj.ResetPacketCounters();
-                    // If _parser is closed, sending attention will raise debug assertion, so we avoid it (but not calling CancelRequest).
-                    if (isCancelRequested && (_parser.State == TdsParserState.OpenNotLoggedIn || _parser.State == TdsParserState.OpenLoggedIn))
-                    {
-                        _stateObj.CancelRequest();
-                    }
-                    _stateObj._internalTimeout = false;
-                    _stateObj.CloseSession();
-                    _stateObj._bulkCopyOpperationInProgress = false;
-                    _stateObj._bulkCopyWriteTimeout = false;
-                    _stateObj = null;
-                }
-                finally
-                {
-                    _parser.Connection.ThreadHasParserLockForClose = false;
-                }
-            }
-        }
-
-        // The continuation part of WriteToServerInternalRest. Executes when the initial query task is completed. (see, WriteToServerInternalRest).
-        // It carries on the source which is passed from the WriteToServerInternalRest and performs SetResult when the entire copy is done.
-        // The carried on source may be null in case of Sync copy. So no need to SetResult at that time.
-        // It launches the copy operation.
-        private void WriteToServerInternalRestContinuedAsync(BulkCopySimpleResultSet internalResults, CancellationToken cts, TaskCompletionSource<object> source)
-        {
-            Task task = null;
-            string updateBulkCommandText = null;
-
-            try
-            {
-                updateBulkCommandText = AnalyzeTargetAndCreateUpdateBulkCommand(internalResults);
-
-                if (_sortedColumnMappings.Count != 0)
-                {
-                    _stateObj.SniContext = SniContext.Snix_SendRows;
-                    _savedBatchSize = _batchSize; // For safety. If someone changes the batchsize during copy we still be using _savedBatchSize.
-                    _rowsUntilNotification = _notifyAfter;
-                    _rowsCopied = 0;
-
-                    _currentRowMetadata = new SourceColumnMetadata[_sortedColumnMappings.Count];
-                    for (int i = 0; i < _currentRowMetadata.Length; i++)
-                    {
-                        _currentRowMetadata[i] = GetColumnMetadata(i);
-                    }
-
-                    task = CopyBatchesAsync(internalResults, updateBulkCommandText, cts); // Launch the BulkCopy
-                }
-
-                if (task != null)
-                {
-                    if (source == null)
-                    {
-                        source = new TaskCompletionSource<object>();
-                    }
-                    AsyncHelper.ContinueTask(task, source,
-                        () =>
-                        {
-                            // Bulk copy task is completed at this moment.
-                            if (task.IsCanceled)
-                            {
-                                _localColumnMappings = null;
-                                try
-                                {
-                                    CleanUpStateObject();
-                                }
-                                finally
-                                {
-                                    source.SetCanceled();
-                                }
-                            }
-                            else if (task.Exception != null)
-                            {
-                                source.SetException(task.Exception.InnerException);
-                            }
-                            else
-                            {
-                                _localColumnMappings = null;
-                                try
-                                {
-                                    CleanUpStateObject(isCancelRequested: false);
-                                }
-                                finally
-                                {
-                                    if (source != null)
-                                    {
-                                        if (cts.IsCancellationRequested)
-                                        {   // We may get cancellation req even after the entire copy.
-                                            source.SetCanceled();
-                                        }
-                                        else
-                                        {
-                                            source.SetResult(null);
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    );
-                    return;
-                }
-                else
-                {
-                    _localColumnMappings = null;
-
-                    try
-                    {
-                        CleanUpStateObject(isCancelRequested: false);
-                    }
-                    catch (Exception cleanupEx)
-                    {
-                        Debug.Fail($"Unexpected exception during {nameof(CleanUpStateObject)} (ignored)", cleanupEx.ToString());
-                    }
-
-                    if (source != null)
-                    {
-                        source.SetResult(null);
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                _localColumnMappings = null;
-
-                try
-                {
-                    CleanUpStateObject();
-                }
-                catch (Exception cleanupEx)
-                {
-                    Debug.Fail($"Unexpected exception during {nameof(CleanUpStateObject)} (ignored)", cleanupEx.ToString());
-                }
-
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        // Rest of the WriteToServerInternalAsync method.
-        // It carries on the source from its caller WriteToServerInternal.
-        // source is null in case of Sync bcp. But valid in case of Async bcp.
-        // It calls the WriteToServerInternalRestContinuedAsync as a continuation of the initial query task.
-        private void WriteToServerInternalRestAsync(CancellationToken cts, TaskCompletionSource<object> source)
-        {
-            Debug.Assert(_hasMoreRowToCopy, "first time it is true, otherwise this method would not have been called.");
-            _hasMoreRowToCopy = true;
-            Task<BulkCopySimpleResultSet> internalResultsTask = null;
-            BulkCopySimpleResultSet internalResults = new BulkCopySimpleResultSet();
-            SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection();
-            try
-            {
-                _parser = _connection.Parser;
-                _parser._asyncWrite = _isAsyncBulkCopy; // Very important!
-
-                Task reconnectTask;
-                try
-                {
-                    reconnectTask = _connection.ValidateAndReconnect(
-                        () =>
-                        {
-                            if (_parserLock != null)
-                            {
-                                _parserLock.Release();
-                                _parserLock = null;
-                            }
-                        }, BulkCopyTimeout);
-                }
-                catch (SqlException ex)
-                {
-                    throw SQL.BulkLoadInvalidDestinationTable(_destinationTableName, ex);
-                }
-
-                if (reconnectTask != null)
-                {
-                    if (_isAsyncBulkCopy)
-                    {
-                        CancellationTokenRegistration regReconnectCancel = default;
-                        TaskCompletionSource<object> cancellableReconnectTS = new TaskCompletionSource<object>();
-                        if (cts.CanBeCanceled)
-                        {
-                            regReconnectCancel = cts.Register(s => ((TaskCompletionSource<object>)s).TrySetCanceled(), cancellableReconnectTS);
-                        }
-                        AsyncHelper.ContinueTaskWithState(reconnectTask, cancellableReconnectTS,
-                            state: cancellableReconnectTS,
-                            onSuccess: (state) => { ((TaskCompletionSource<object>)state).SetResult(null); }
-                        );
-                        // No need to cancel timer since SqlBulkCopy creates specific task source for reconnection.
-                        AsyncHelper.SetTimeoutException(cancellableReconnectTS, BulkCopyTimeout,
-                                () => { return SQL.BulkLoadInvalidDestinationTable(_destinationTableName, SQL.CR_ReconnectTimeout()); }, CancellationToken.None);
-                        AsyncHelper.ContinueTask(cancellableReconnectTS.Task, source,
-                            onSuccess: () =>
-                            {
-                                regReconnectCancel.Dispose();
-                                if (_parserLock != null)
-                                {
-                                    _parserLock.Release();
-                                    _parserLock = null;
-                                }
-                                _parserLock = _connection.GetOpenTdsConnection()._parserLock;
-                                _parserLock.Wait(canReleaseFromAnyThread: true);
-                                WriteToServerInternalRestAsync(cts, source);
-                            },
-                            onFailure: (e) => { regReconnectCancel.Dispose(); },
-                            onCancellation: () => { regReconnectCancel.Dispose(); },
-                            exceptionConverter: (ex) => SQL.BulkLoadInvalidDestinationTable(_destinationTableName, ex));
-                        return;
-                    }
-                    else
-                    {
-                        try
-                        {
-                            AsyncHelper.WaitForCompletion(reconnectTask, this.BulkCopyTimeout, () => { throw SQL.CR_ReconnectTimeout(); });
-                        }
-                        catch (SqlException ex)
-                        {
-                            throw SQL.BulkLoadInvalidDestinationTable(_destinationTableName, ex); // Preserve behavior (throw InvalidOperationException on failure to connect)
-                        }
-                        _parserLock = _connection.GetOpenTdsConnection()._parserLock;
-                        _parserLock.Wait(canReleaseFromAnyThread: false);
-                        WriteToServerInternalRestAsync(cts, source);
-                        return;
-                    }
-                }
-                if (_isAsyncBulkCopy)
-                {
-                    _connection.AddWeakReference(this, SqlReferenceCollection.BulkCopyTag);
-                }
-
-                internalConnection.ThreadHasParserLockForClose = true;    // In case of error, let the connection know that we already have the parser lock.
-
-                try
-                {
-                    _stateObj = _parser.GetSession(this);
-                    _stateObj._bulkCopyOpperationInProgress = true;
-                    _stateObj.StartSession(this);
-                }
-                finally
-                {
-                    internalConnection.ThreadHasParserLockForClose = false;
-                }
-
-                try
-                {
-                    internalResultsTask = CreateAndExecuteInitialQueryAsync(out internalResults); // Task/Null
-                }
-                catch (SqlException ex)
-                {
-                    throw SQL.BulkLoadInvalidDestinationTable(_destinationTableName, ex);
-                }
-
-                if (internalResultsTask != null)
-                {
-                    AsyncHelper.ContinueTask(internalResultsTask, source, () => WriteToServerInternalRestContinuedAsync(internalResultsTask.Result, cts, source));
-                }
-                else
-                {
-                    Debug.Assert(internalResults != null, "Executing initial query finished synchronously, but there were no results");
-                    WriteToServerInternalRestContinuedAsync(internalResults, cts, source); // internalResults is valid here.
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        // This returns Task for Async, Null for Sync
-        private Task WriteToServerInternalAsync(CancellationToken ctoken)
-        {
-            TaskCompletionSource<object> source = null;
-            Task<object> resultTask = null;
-
-            if (_isAsyncBulkCopy)
-            {
-                source = new TaskCompletionSource<object>(); // Creating the completion source/Task that we pass to application
-                resultTask = source.Task;
-
-                RegisterForConnectionCloseNotification(ref resultTask);
-            }
-
-            if (_destinationTableName == null)
-            {
-                if (source != null)
-                {
-                    source.SetException(SQL.BulkLoadMissingDestinationTable()); // No table to copy
-                }
-                else
-                {
-                    throw SQL.BulkLoadMissingDestinationTable();
-                }
-                return resultTask;
-            }
-
-            try
-            {
-                Task readTask = ReadFromRowSourceAsync(ctoken); // readTask == reading task. This is the first read call. "more" is valid only if readTask == null;
-
-                if (readTask == null)
-                {   // Synchronously finished reading.
-                    if (!_hasMoreRowToCopy)
-                    {   // No rows in the source to copy!
-                        if (source != null)
-                        {
-                            source.SetResult(null);
-                        }
-                        return resultTask;
-                    }
-                    else
-                    {   // True, we have more rows.
-                        WriteToServerInternalRestAsync(ctoken, source); //rest of the method, passing the same completion and returning the incomplete task (ret).
-                        return resultTask;
-                    }
-                }
-                else
-                {
-                    Debug.Assert(_isAsyncBulkCopy, "Read must not return a Task in the Sync mode");
-                    AsyncHelper.ContinueTask(readTask, source,
-                        () =>
-                        {
-                            if (!_hasMoreRowToCopy)
-                            {
-                                source.SetResult(null); // No rows to copy!
-                            }
-                            else
-                            {
-                                WriteToServerInternalRestAsync(ctoken, source); // Passing the same completion which will be completed by the Callee.
-                            }
-                        }
-                    );
-                    return resultTask;
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source != null)
-                {
-                    source.TrySetException(ex);
-                }
-                else
-                {
-                    throw;
-                }
-            }
-            return resultTask;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyColumnMapping.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyColumnMapping.cs
deleted file mode 100644 (file)
index 10d0f11..0000000
+++ /dev/null
@@ -1,130 +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.Data.Common;
-
-
-namespace System.Data.SqlClient
-{
-    // -------------------------------------------------------------------------------------------------
-    // this class helps allows the user to create association between source- and targetcolumns
-    //
-    //
-
-    public sealed class SqlBulkCopyColumnMapping
-    {
-        internal string _destinationColumnName;
-        internal int _destinationColumnOrdinal;
-        internal string _sourceColumnName;
-        internal int _sourceColumnOrdinal;
-
-        // devnote: we don't want the user to detect the columnordinal after WriteToServer call.
-        // _sourceColumnOrdinal(s) will be copied to _internalSourceColumnOrdinal when WriteToServer executes.
-        internal int _internalDestinationColumnOrdinal;
-        internal int _internalSourceColumnOrdinal;   // -1 indicates an undetermined value
-
-        public string DestinationColumn
-        {
-            get
-            {
-                if (_destinationColumnName != null)
-                {
-                    return _destinationColumnName;
-                }
-                return string.Empty;
-            }
-            set
-            {
-                _destinationColumnOrdinal = _internalDestinationColumnOrdinal = -1;
-                _destinationColumnName = value;
-            }
-        }
-
-        public int DestinationOrdinal
-        {
-            get
-            {
-                return _destinationColumnOrdinal;
-            }
-            set
-            {
-                if (value >= 0)
-                {
-                    _destinationColumnName = null;
-                    _destinationColumnOrdinal = _internalDestinationColumnOrdinal = value;
-                }
-                else
-                {
-                    throw ADP.IndexOutOfRange(value);
-                }
-            }
-        }
-
-        public string SourceColumn
-        {
-            get
-            {
-                if (_sourceColumnName != null)
-                {
-                    return _sourceColumnName;
-                }
-                return string.Empty;
-            }
-            set
-            {
-                _sourceColumnOrdinal = _internalSourceColumnOrdinal = -1;
-                _sourceColumnName = value;
-            }
-        }
-
-        public int SourceOrdinal
-        {
-            get
-            {
-                return _sourceColumnOrdinal;
-            }
-            set
-            {
-                if (value >= 0)
-                {
-                    _sourceColumnName = null;
-                    _sourceColumnOrdinal = _internalSourceColumnOrdinal = value;
-                }
-                else
-                {
-                    throw ADP.IndexOutOfRange(value);
-                }
-            }
-        }
-
-        public SqlBulkCopyColumnMapping()
-        {
-            _internalSourceColumnOrdinal = -1;
-        }
-
-        public SqlBulkCopyColumnMapping(string sourceColumn, string destinationColumn)
-        {
-            SourceColumn = sourceColumn;
-            DestinationColumn = destinationColumn;
-        }
-
-        public SqlBulkCopyColumnMapping(int sourceColumnOrdinal, string destinationColumn)
-        {
-            SourceOrdinal = sourceColumnOrdinal;
-            DestinationColumn = destinationColumn;
-        }
-
-        public SqlBulkCopyColumnMapping(string sourceColumn, int destinationOrdinal)
-        {
-            SourceColumn = sourceColumn;
-            DestinationOrdinal = destinationOrdinal;
-        }
-
-        public SqlBulkCopyColumnMapping(int sourceColumnOrdinal, int destinationOrdinal)
-        {
-            SourceOrdinal = sourceColumnOrdinal;
-            DestinationOrdinal = destinationOrdinal;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyColumnMappingCollection.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyColumnMappingCollection.cs
deleted file mode 100644 (file)
index 73785b6..0000000
+++ /dev/null
@@ -1,136 +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.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlBulkCopyColumnMappingCollection : CollectionBase
-    {
-        private enum MappingSchema
-        {
-            Undefined = 0,
-            NamesNames = 1,
-            NemesOrdinals = 2,
-            OrdinalsNames = 3,
-            OrdinalsOrdinals = 4,
-        }
-
-        private MappingSchema _mappingSchema = MappingSchema.Undefined;
-
-        internal SqlBulkCopyColumnMappingCollection()
-        {
-        }
-
-        internal bool ReadOnly { get; set; }
-
-        public SqlBulkCopyColumnMapping this[int index] => (SqlBulkCopyColumnMapping)this.List[index];
-
-        public SqlBulkCopyColumnMapping Add(SqlBulkCopyColumnMapping bulkCopyColumnMapping)
-        {
-            AssertWriteAccess();
-            Debug.Assert(string.IsNullOrEmpty(bulkCopyColumnMapping.SourceColumn) || bulkCopyColumnMapping._internalSourceColumnOrdinal == -1, "BulkLoadAmbiguousSourceColumn");
-            if (((string.IsNullOrEmpty(bulkCopyColumnMapping.SourceColumn)) && (bulkCopyColumnMapping.SourceOrdinal == -1))
-                || ((string.IsNullOrEmpty(bulkCopyColumnMapping.DestinationColumn)) && (bulkCopyColumnMapping.DestinationOrdinal == -1)))
-            {
-                throw SQL.BulkLoadNonMatchingColumnMapping();
-            }
-            InnerList.Add(bulkCopyColumnMapping);
-            return bulkCopyColumnMapping;
-        }
-
-        public SqlBulkCopyColumnMapping Add(string sourceColumn, string destinationColumn)
-        {
-            AssertWriteAccess();
-            return Add(new SqlBulkCopyColumnMapping(sourceColumn, destinationColumn));
-        }
-
-        public SqlBulkCopyColumnMapping Add(int sourceColumnIndex, string destinationColumn)
-        {
-            AssertWriteAccess();
-            return Add(new SqlBulkCopyColumnMapping(sourceColumnIndex, destinationColumn));
-        }
-
-        public SqlBulkCopyColumnMapping Add(string sourceColumn, int destinationColumnIndex)
-        {
-            AssertWriteAccess();
-            return Add(new SqlBulkCopyColumnMapping(sourceColumn, destinationColumnIndex));
-        }
-        public SqlBulkCopyColumnMapping Add(int sourceColumnIndex, int destinationColumnIndex)
-        {
-            AssertWriteAccess();
-            return Add(new SqlBulkCopyColumnMapping(sourceColumnIndex, destinationColumnIndex));
-        }
-
-        private void AssertWriteAccess()
-        {
-            if (ReadOnly)
-            {
-                throw SQL.BulkLoadMappingInaccessible();
-            }
-        }
-
-        public new void Clear()
-        {
-            AssertWriteAccess();
-            base.Clear();
-        }
-
-        public bool Contains(SqlBulkCopyColumnMapping value) => InnerList.Contains(value);
-
-        public void CopyTo(SqlBulkCopyColumnMapping[] array, int index) => InnerList.CopyTo(array, index);
-
-        internal void CreateDefaultMapping(int columnCount)
-        {
-            for (int i = 0; i < columnCount; i++)
-            {
-                InnerList.Add(new SqlBulkCopyColumnMapping(i, i));
-            }
-        }
-
-        public int IndexOf(SqlBulkCopyColumnMapping value) => InnerList.IndexOf(value);
-
-        public void Insert(int index, SqlBulkCopyColumnMapping value)
-        {
-            AssertWriteAccess();
-            InnerList.Insert(index, value);
-        }
-
-        public void Remove(SqlBulkCopyColumnMapping value)
-        {
-            AssertWriteAccess();
-            InnerList.Remove(value);
-        }
-
-        public new void RemoveAt(int index)
-        {
-            AssertWriteAccess();
-            base.RemoveAt(index);
-        }
-
-        internal void ValidateCollection()
-        {
-            MappingSchema mappingSchema;
-            foreach (SqlBulkCopyColumnMapping a in InnerList)
-            {
-                mappingSchema = a.SourceOrdinal != -1 ?
-                    (a.DestinationOrdinal != -1 ? MappingSchema.OrdinalsOrdinals : MappingSchema.OrdinalsNames) :
-                    (a.DestinationOrdinal != -1 ? MappingSchema.NemesOrdinals : MappingSchema.NamesNames);
-
-                if (_mappingSchema == MappingSchema.Undefined)
-                {
-                    _mappingSchema = mappingSchema;
-                }
-                else
-                {
-                    if (_mappingSchema != mappingSchema)
-                    {
-                        throw SQL.BulkLoadMappingsNamesOrOrdinalsOnly();
-                    }
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyOptions.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlBulkCopyOptions.cs
deleted file mode 100644 (file)
index 7011fcd..0000000
+++ /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.Data.SqlClient
-{
-    [Flags]
-    public enum SqlBulkCopyOptions
-    {
-        Default = 0,
-        KeepIdentity = 1 << 0,
-        CheckConstraints = 1 << 1,
-        TableLock = 1 << 2,
-        KeepNulls = 1 << 3,
-        FireTriggers = 1 << 4,
-        UseInternalTransaction = 1 << 5,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCachedBuffer.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCachedBuffer.cs
deleted file mode 100644 (file)
index 56ecd8f..0000000
+++ /dev/null
@@ -1,153 +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.Generic;
-using System.Diagnostics;
-using System.Xml;
-using System.Data.SqlTypes;
-using System.IO;
-using System.Runtime.CompilerServices;
-using System.Data.Common;
-
-namespace System.Data.SqlClient
-{
-    // Caches the bytes returned from partial length prefixed datatypes, like XML
-    internal sealed class SqlCachedBuffer : System.Data.SqlTypes.INullable
-    {
-        public static readonly SqlCachedBuffer Null = new SqlCachedBuffer();
-        private const int _maxChunkSize = 2048; // Arbitrary value for chunk size. Revisit this later for better perf
-
-        private readonly List<byte[]> _cachedBytes;
-
-        private SqlCachedBuffer()
-        {
-            // For constructing Null
-        }
-
-        private SqlCachedBuffer(List<byte[]> cachedBytes)
-        {
-            _cachedBytes = cachedBytes;
-        }
-
-        internal List<byte[]> CachedBytes
-        {
-            get { return _cachedBytes; }
-        }
-
-        // Reads off from the network buffer and caches bytes. Only reads one column value in the current row.
-        internal static bool TryCreate(SqlMetaDataPriv metadata, TdsParser parser, TdsParserStateObject stateObj, out SqlCachedBuffer buffer)
-        {
-            int cb = 0;
-            ulong plplength;
-            byte[] byteArr;
-
-            List<byte[]> cachedBytes = new List<byte[]>();
-            buffer = null;
-
-            // the very first length is already read.
-            if (!parser.TryPlpBytesLeft(stateObj, out plplength))
-            {
-                return false;
-            }
-            // For now we  only handle Plp data from the parser directly.
-            Debug.Assert(metadata.metaType.IsPlp, "SqlCachedBuffer call on a non-plp data");
-            do
-            {
-                if (plplength == 0)
-                    break;
-                do
-                {
-                    cb = (plplength > (ulong)_maxChunkSize) ? _maxChunkSize : (int)plplength;
-                    byteArr = new byte[cb];
-                    if (!stateObj.TryReadPlpBytes(ref byteArr, 0, cb, out cb))
-                    {
-                        return false;
-                    }
-                    Debug.Assert(cb == byteArr.Length);
-                    if (cachedBytes.Count == 0)
-                    {
-                        // Add the Byte order mark if needed if we read the first array
-                        AddByteOrderMark(byteArr, cachedBytes);
-                    }
-                    cachedBytes.Add(byteArr);
-                    plplength -= (ulong)cb;
-                } while (plplength > 0);
-                if (!parser.TryPlpBytesLeft(stateObj, out plplength))
-                {
-                    return false;
-                }
-            } while (plplength > 0);
-            Debug.Assert(stateObj._longlen == 0 && stateObj._longlenleft == 0);
-
-            buffer = new SqlCachedBuffer(cachedBytes);
-            return true;
-        }
-
-        private static void AddByteOrderMark(byte[] byteArr, List<byte[]> cachedBytes)
-        {
-            // Need to find out if we should add byte order mark or not.
-            // We need to add this if we are getting ntext xml, not if we are getting binary xml
-            // Binary Xml always begins with the bytes 0xDF and 0xFF
-            // If we aren't getting these, then we are getting Unicode xml
-            if ((byteArr.Length < 2) || (byteArr[0] != 0xDF) || (byteArr[1] != 0xFF))
-            {
-                Debug.Assert(cachedBytes.Count == 0);
-                cachedBytes.Add(TdsEnums.XMLUNICODEBOMBYTES);
-            }
-        }
-
-        internal Stream ToStream()
-        {
-            return new SqlCachedStream(this);
-        }
-
-        public override string ToString()
-        {
-            if (IsNull)
-                throw new SqlNullValueException();
-
-            if (_cachedBytes.Count == 0)
-            {
-                return string.Empty;
-            }
-            SqlXml sxml = new SqlXml(ToStream());
-            return sxml.Value;
-        }
-
-        internal SqlString ToSqlString()
-        {
-            if (IsNull)
-                return SqlString.Null;
-            string str = ToString();
-            return new SqlString(str);
-        }
-
-        internal SqlXml ToSqlXml()
-        {
-            SqlXml sx = new SqlXml(ToStream());
-            return sx;
-        }
-
-        // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        internal XmlReader ToXmlReader()
-        {
-            return SqlTypeWorkarounds.SqlXmlCreateSqlXmlReader(ToStream(), closeInput: false);
-        }
-
-        public bool IsNull
-        {
-            get
-            {
-                return (_cachedBytes == null) ? true : false;
-            }
-        }
-
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientDiagnosticListenerExtensions.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientDiagnosticListenerExtensions.cs
deleted file mode 100644 (file)
index 0fc8035..0000000
+++ /dev/null
@@ -1,336 +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.Diagnostics;
-using System.Runtime.CompilerServices;
-
-namespace System.Data.SqlClient
-{
-    /// <summary>
-    /// Extension methods on the DiagnosticListener class to log SqlCommand data
-    /// </summary>
-    internal static class SqlClientDiagnosticListenerExtensions
-    {
-        public const string DiagnosticListenerName = "SqlClientDiagnosticListener";
-
-        private const string SqlClientPrefix = "System.Data.SqlClient.";
-
-        public const string SqlBeforeExecuteCommand = SqlClientPrefix + nameof(WriteCommandBefore);
-        public const string SqlAfterExecuteCommand = SqlClientPrefix + nameof(WriteCommandAfter);
-        public const string SqlErrorExecuteCommand = SqlClientPrefix + nameof(WriteCommandError);
-
-        public const string SqlBeforeOpenConnection = SqlClientPrefix + nameof(WriteConnectionOpenBefore);
-        public const string SqlAfterOpenConnection = SqlClientPrefix + nameof(WriteConnectionOpenAfter);
-        public const string SqlErrorOpenConnection = SqlClientPrefix + nameof(WriteConnectionOpenError);
-
-        public const string SqlBeforeCloseConnection = SqlClientPrefix + nameof(WriteConnectionCloseBefore);
-        public const string SqlAfterCloseConnection = SqlClientPrefix + nameof(WriteConnectionCloseAfter);
-        public const string SqlErrorCloseConnection = SqlClientPrefix + nameof(WriteConnectionCloseError);
-
-        public const string SqlBeforeCommitTransaction = SqlClientPrefix + nameof(WriteTransactionCommitBefore);
-        public const string SqlAfterCommitTransaction = SqlClientPrefix + nameof(WriteTransactionCommitAfter);
-        public const string SqlErrorCommitTransaction = SqlClientPrefix + nameof(WriteTransactionCommitError);
-
-        public const string SqlBeforeRollbackTransaction = SqlClientPrefix + nameof(WriteTransactionRollbackBefore);
-        public const string SqlAfterRollbackTransaction = SqlClientPrefix + nameof(WriteTransactionRollbackAfter);
-        public const string SqlErrorRollbackTransaction = SqlClientPrefix + nameof(WriteTransactionRollbackError);
-
-        public static Guid WriteCommandBefore(this DiagnosticListener @this, SqlCommand sqlCommand, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlBeforeExecuteCommand))
-            {
-                Guid operationId = Guid.NewGuid();
-
-                @this.Write(
-                    SqlBeforeExecuteCommand,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = sqlCommand.Connection?.ClientConnectionId,
-                        Command = sqlCommand
-                    });
-
-                return operationId;
-            }
-            else
-                return Guid.Empty;
-        }
-
-        public static void WriteCommandAfter(this DiagnosticListener @this, Guid operationId, SqlCommand sqlCommand, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlAfterExecuteCommand))
-            {
-                @this.Write(
-                    SqlAfterExecuteCommand,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = sqlCommand.Connection?.ClientConnectionId,
-                        Command = sqlCommand,
-                        Statistics = sqlCommand.Statistics?.GetDictionary(),
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static void WriteCommandError(this DiagnosticListener @this, Guid operationId, SqlCommand sqlCommand, Exception ex, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlErrorExecuteCommand))
-            {
-                @this.Write(
-                    SqlErrorExecuteCommand,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = sqlCommand.Connection?.ClientConnectionId,
-                        Command = sqlCommand,
-                        Exception = ex,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static Guid WriteConnectionOpenBefore(this DiagnosticListener @this, SqlConnection sqlConnection, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlBeforeOpenConnection))
-            {
-                Guid operationId = Guid.NewGuid();
-
-                @this.Write(
-                    SqlBeforeOpenConnection,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        Connection = sqlConnection,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-
-                return operationId;
-            }
-            else
-                return Guid.Empty;
-        }
-
-        public static void WriteConnectionOpenAfter(this DiagnosticListener @this, Guid operationId, SqlConnection sqlConnection, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlAfterOpenConnection))
-            {
-                @this.Write(
-                    SqlAfterOpenConnection,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = sqlConnection.ClientConnectionId,
-                        Connection = sqlConnection,
-                        Statistics = sqlConnection.Statistics?.GetDictionary(),
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static void WriteConnectionOpenError(this DiagnosticListener @this, Guid operationId, SqlConnection sqlConnection, Exception ex, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlErrorOpenConnection))
-            {
-                @this.Write(
-                    SqlErrorOpenConnection,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = sqlConnection.ClientConnectionId,
-                        Connection = sqlConnection,
-                        Exception = ex,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static Guid WriteConnectionCloseBefore(this DiagnosticListener @this, SqlConnection sqlConnection, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlBeforeCloseConnection))
-            {
-                Guid operationId = Guid.NewGuid();
-
-                @this.Write(
-                    SqlBeforeCloseConnection,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = sqlConnection.ClientConnectionId,
-                        Connection = sqlConnection,
-                        Statistics = sqlConnection.Statistics?.GetDictionary(),
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-
-                return operationId;
-            }
-            else
-                return Guid.Empty;
-        }
-
-        public static void WriteConnectionCloseAfter(this DiagnosticListener @this, Guid operationId, Guid clientConnectionId, SqlConnection sqlConnection, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlAfterCloseConnection))
-            {
-                @this.Write(
-                    SqlAfterCloseConnection,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = clientConnectionId,
-                        Connection = sqlConnection,
-                        Statistics = sqlConnection.Statistics?.GetDictionary(),
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static void WriteConnectionCloseError(this DiagnosticListener @this, Guid operationId, Guid clientConnectionId, SqlConnection sqlConnection, Exception ex, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlErrorCloseConnection))
-            {
-                @this.Write(
-                    SqlErrorCloseConnection,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        ConnectionId = clientConnectionId,
-                        Connection = sqlConnection,
-                        Statistics = sqlConnection.Statistics?.GetDictionary(),
-                        Exception = ex,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static Guid WriteTransactionCommitBefore(this DiagnosticListener @this, IsolationLevel isolationLevel, SqlConnection connection, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlBeforeCommitTransaction))
-            {
-                Guid operationId = Guid.NewGuid();
-
-                @this.Write(
-                    SqlBeforeCommitTransaction,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        IsolationLevel = isolationLevel,
-                        Connection = connection,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-
-                return operationId;
-            }
-            else
-                return Guid.Empty;
-        }
-
-        public static void WriteTransactionCommitAfter(this DiagnosticListener @this, Guid operationId, IsolationLevel isolationLevel, SqlConnection connection, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlAfterCommitTransaction))
-            {
-                @this.Write(
-                    SqlAfterCommitTransaction,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        IsolationLevel = isolationLevel,
-                        Connection = connection,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static void WriteTransactionCommitError(this DiagnosticListener @this, Guid operationId, IsolationLevel isolationLevel, SqlConnection connection, Exception ex, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlErrorCommitTransaction))
-            {
-                @this.Write(
-                    SqlErrorCommitTransaction,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        IsolationLevel = isolationLevel,
-                        Connection = connection,
-                        Exception = ex,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static Guid WriteTransactionRollbackBefore(this DiagnosticListener @this, IsolationLevel isolationLevel, SqlConnection connection, string transactionName, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlBeforeRollbackTransaction))
-            {
-                Guid operationId = Guid.NewGuid();
-
-                @this.Write(
-                    SqlBeforeRollbackTransaction,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        IsolationLevel = isolationLevel,
-                        Connection = connection,
-                        TransactionName = transactionName,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-
-                return operationId;
-            }
-            else
-                return Guid.Empty;
-        }
-
-        public static void WriteTransactionRollbackAfter(this DiagnosticListener @this, Guid operationId, IsolationLevel isolationLevel, SqlConnection connection, string transactionName, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlAfterRollbackTransaction))
-            {
-                @this.Write(
-                    SqlAfterRollbackTransaction,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        IsolationLevel = isolationLevel,
-                        Connection = connection,
-                        TransactionName = transactionName,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-
-        public static void WriteTransactionRollbackError(this DiagnosticListener @this, Guid operationId, IsolationLevel isolationLevel, SqlConnection connection, string transactionName, Exception ex, [CallerMemberName] string operation = "")
-        {
-            if (@this.IsEnabled(SqlErrorRollbackTransaction))
-            {
-                @this.Write(
-                    SqlErrorRollbackTransaction,
-                    new
-                    {
-                        OperationId = operationId,
-                        Operation = operation,
-                        IsolationLevel = isolationLevel,
-                        Connection = connection,
-                        TransactionName = transactionName,
-                        Exception = ex,
-                        Timestamp = Stopwatch.GetTimestamp()
-                    });
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientFactory.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientFactory.cs
deleted file mode 100644 (file)
index c8760c6..0000000
+++ /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.Data.Common;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlClientFactory : DbProviderFactory
-    {
-        public static readonly SqlClientFactory Instance = new SqlClientFactory();
-
-        private SqlClientFactory()
-        {
-        }
-
-        public override DbCommand CreateCommand()
-        {
-            return new SqlCommand();
-        }
-
-        public override DbCommandBuilder CreateCommandBuilder()
-        {
-            return new SqlCommandBuilder();
-        }
-
-        public override DbConnection CreateConnection()
-        {
-            return new SqlConnection();
-        }
-
-        public override DbConnectionStringBuilder CreateConnectionStringBuilder()
-        {
-            return new SqlConnectionStringBuilder();
-        }
-
-        public override DbDataAdapter CreateDataAdapter()
-        {
-            return new SqlDataAdapter();
-        }
-
-        public override DbParameter CreateParameter()
-        {
-            return new SqlParameter();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientMetaDataCollectionNames.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlClientMetaDataCollectionNames.cs
deleted file mode 100644 (file)
index 3dbd6f0..0000000
+++ /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.
-
-namespace System.Data.SqlClient
-{
-
-    public static class SqlClientMetaDataCollectionNames
-    {
-        public static readonly string Columns = "Columns";
-        public static readonly string Databases = "Databases";
-        public static readonly string ForeignKeys = "ForeignKeys";
-        public static readonly string IndexColumns = "IndexColumns";
-        public static readonly string Indexes = "Indexes";
-        public static readonly string Parameters = "Parameters";
-        public static readonly string ProcedureColumns = "ProcedureColumns";
-        public static readonly string Procedures = "Procedures";
-        public static readonly string Tables = "Tables";
-        public static readonly string UserDefinedTypes = "UserDefinedTypes";
-        public static readonly string Users = "Users";
-        public static readonly string ViewColumns = "ViewColumns";
-        public static readonly string Views = "Views";
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs
deleted file mode 100644 (file)
index cdbaaa2..0000000
+++ /dev/null
@@ -1,4054 +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.Generic;
-using System.Data.Common;
-using System.Data.Sql;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.IO;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-
-using Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlCommand : DbCommand, ICloneable
-    {
-        private string _commandText;
-        private CommandType _commandType;
-        private int _commandTimeout = ADP.DefaultCommandTimeout;
-        private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
-        private bool _designTimeInvisible;
-
-        internal SqlDependency _sqlDep;
-
-        private static readonly DiagnosticListener _diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
-        private bool _parentOperationStarted = false;
-
-        // Prepare
-        // Against 7.0 Serve a prepare/unprepare requires an extra roundtrip to the server.
-        //
-        // From 8.0 and above  the preparation can be done as part of the command execution.
-
-        private enum EXECTYPE
-        {
-            UNPREPARED,         // execute unprepared commands, all server versions (results in sp_execsql call)
-            PREPAREPENDING,     // prepare and execute command, 8.0 and above only  (results in sp_prepexec call)
-            PREPARED,           // execute prepared commands, all server versions   (results in sp_exec call)
-        }
-
-        // _hiddenPrepare
-        // On 8.0 and above the Prepared state cannot be left. Once a command is prepared it will always be prepared.
-        // A change in parameters, commandtext etc (IsDirty) automatically causes a hidden prepare
-        //
-        // _inPrepare will be set immediately before the actual prepare is done.
-        // The OnReturnValue function will test this flag to determine whether the returned value is a _prepareHandle or something else.
-        //
-        // _prepareHandle - the handle of a prepared command. Apparently there can be multiple prepared commands at a time - a feature that we do not support yet.
-        private static readonly object s_cachedInvalidPrepareHandle = (object)-1;
-        private bool _inPrepare = false;
-        private object _prepareHandle = s_cachedInvalidPrepareHandle; // this is an int which is used in the object typed SqlParameter.Value field, avoid repeated boxing by storing in a box
-        private bool _hiddenPrepare = false;
-        private int _preparedConnectionCloseCount = -1;
-        private int _preparedConnectionReconnectCount = -1;
-
-        private SqlParameterCollection _parameters;
-        private SqlConnection _activeConnection;
-        private bool _dirty = false;               // true if the user changes the commandtext or number of parameters after the command is already prepared
-        private EXECTYPE _execType = EXECTYPE.UNPREPARED; // by default, assume the user is not sharing a connection so the command has not been prepared
-        private _SqlRPC[] _rpcArrayOf1 = null;                // Used for RPC executes
-
-        // cut down on object creation and cache all these
-        // cached metadata
-        private _SqlMetaDataSet _cachedMetaData;
-
-        // Last TaskCompletionSource for reconnect task - use for cancellation only
-        private TaskCompletionSource<object> _reconnectionCompletionSource = null;
-
-#if DEBUG
-        internal static int DebugForceAsyncWriteDelay { get; set; }
-#endif
-        internal bool InPrepare
-        {
-            get
-            {
-                return _inPrepare;
-            }
-        }
-
-        // Cached info for async executions
-        private sealed class CachedAsyncState
-        {
-            private int _cachedAsyncCloseCount = -1;    // value of the connection's CloseCount property when the asyncResult was set; tracks when connections are closed after an async operation
-            private TaskCompletionSource<object> _cachedAsyncResult = null;
-            private SqlConnection _cachedAsyncConnection = null;  // Used to validate that the connection hasn't changed when end the connection;
-            private SqlDataReader _cachedAsyncReader = null;
-            private RunBehavior _cachedRunBehavior = RunBehavior.ReturnImmediately;
-            private string _cachedSetOptions = null;
-            private string _cachedEndMethod = null;
-
-            internal CachedAsyncState()
-            {
-            }
-
-            internal SqlDataReader CachedAsyncReader
-            {
-                get { return _cachedAsyncReader; }
-            }
-            internal RunBehavior CachedRunBehavior
-            {
-                get { return _cachedRunBehavior; }
-            }
-            internal string CachedSetOptions
-            {
-                get { return _cachedSetOptions; }
-            }
-            internal bool PendingAsyncOperation
-            {
-                get { return (null != _cachedAsyncResult); }
-            }
-            internal string EndMethodName
-            {
-                get { return _cachedEndMethod; }
-            }
-
-            internal bool IsActiveConnectionValid(SqlConnection activeConnection)
-            {
-                return (_cachedAsyncConnection == activeConnection && _cachedAsyncCloseCount == activeConnection.CloseCount);
-            }
-
-            internal void ResetAsyncState()
-            {
-                _cachedAsyncCloseCount = -1;
-                _cachedAsyncResult = null;
-                if (_cachedAsyncConnection != null)
-                {
-                    _cachedAsyncConnection.AsyncCommandInProgress = false;
-                    _cachedAsyncConnection = null;
-                }
-                _cachedAsyncReader = null;
-                _cachedRunBehavior = RunBehavior.ReturnImmediately;
-                _cachedSetOptions = null;
-                _cachedEndMethod = null;
-            }
-
-            internal void SetActiveConnectionAndResult(TaskCompletionSource<object> completion, string endMethod, SqlConnection activeConnection)
-            {
-                Debug.Assert(activeConnection != null, "Unexpected null connection argument on SetActiveConnectionAndResult!");
-                TdsParser parser = activeConnection?.Parser;
-                if ((parser == null) || (parser.State == TdsParserState.Closed) || (parser.State == TdsParserState.Broken))
-                {
-                    throw ADP.ClosedConnectionError();
-                }
-
-                _cachedAsyncCloseCount = activeConnection.CloseCount;
-                _cachedAsyncResult = completion;
-                if (!parser.MARSOn)
-                {
-                    if (activeConnection.AsyncCommandInProgress)
-                        throw SQL.MARSUnspportedOnConnection();
-                }
-                _cachedAsyncConnection = activeConnection;
-
-                // Should only be needed for non-MARS, but set anyways.
-                _cachedAsyncConnection.AsyncCommandInProgress = true;
-                _cachedEndMethod = endMethod;
-            }
-
-            internal void SetAsyncReaderState(SqlDataReader ds, RunBehavior runBehavior, string optionSettings)
-            {
-                _cachedAsyncReader = ds;
-                _cachedRunBehavior = runBehavior;
-                _cachedSetOptions = optionSettings;
-            }
-        }
-
-        private CachedAsyncState _cachedAsyncState = null;
-
-        private CachedAsyncState cachedAsyncState
-        {
-            get
-            {
-                if (_cachedAsyncState == null)
-                {
-                    _cachedAsyncState = new CachedAsyncState();
-                }
-                return _cachedAsyncState;
-            }
-        }
-
-        // sql reader will pull this value out for each NextResult call.  It is not cumulative
-        // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
-        internal int _rowsAffected = -1; // rows affected by the command
-
-        private SqlNotificationRequest _notification;
-
-        // transaction support
-        private SqlTransaction _transaction;
-
-        private StatementCompletedEventHandler _statementCompletedEventHandler;
-
-        private TdsParserStateObject _stateObj; // this is the TDS session we're using.
-
-        // Volatile bool used to synchronize with cancel thread the state change of an executing
-        // command going from pre-processing to obtaining a stateObject.  The cancel synchronization
-        // we require in the command is only from entering an Execute* API to obtaining a
-        // stateObj.  Once a stateObj is successfully obtained, cancel synchronization is handled
-        // by the stateObject.
-        private volatile bool _pendingCancel;
-
-        private bool _batchRPCMode;
-        private List<_SqlRPC> _RPCList;
-        private _SqlRPC[] _SqlRPCBatchArray;
-        private List<SqlParameterCollection> _parameterCollectionList;
-        private int _currentlyExecutingBatch;
-
-
-        public SqlCommand() : base()
-        {
-            GC.SuppressFinalize(this);
-        }
-
-        public SqlCommand(string cmdText) : this()
-        {
-            CommandText = cmdText;
-        }
-
-        public SqlCommand(string cmdText, SqlConnection connection) : this()
-        {
-            CommandText = cmdText;
-            Connection = connection;
-        }
-
-        public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction) : this()
-        {
-            CommandText = cmdText;
-            Connection = connection;
-            Transaction = transaction;
-        }
-
-        private SqlCommand(SqlCommand from) : this()
-        {
-            CommandText = from.CommandText;
-            CommandTimeout = from.CommandTimeout;
-            CommandType = from.CommandType;
-            Connection = from.Connection;
-            DesignTimeVisible = from.DesignTimeVisible;
-            Transaction = from.Transaction;
-            UpdatedRowSource = from.UpdatedRowSource;
-
-            SqlParameterCollection parameters = Parameters;
-            foreach (object parameter in from.Parameters)
-            {
-                parameters.Add((parameter is ICloneable) ? (parameter as ICloneable).Clone() : parameter);
-            }
-        }
-
-        public new SqlConnection Connection
-        {
-            get
-            {
-                return _activeConnection;
-            }
-            set
-            {
-                // Don't allow the connection to be changed while in an async operation.
-                if (_activeConnection != value && _activeConnection != null)
-                { // If new value...
-                    if (_cachedAsyncState != null && _cachedAsyncState.PendingAsyncOperation)
-                    { // If in pending async state, throw.
-                        throw SQL.CannotModifyPropertyAsyncOperationInProgress();
-                    }
-                }
-
-                // Check to see if the currently set transaction has completed.  If so,
-                // null out our local reference.
-                if (null != _transaction && _transaction.Connection == null)
-                {
-                    _transaction = null;
-                }
-
-
-                // Command is no longer prepared on new connection, cleanup prepare status
-                if (IsPrepared)
-                {
-                    if (_activeConnection != value && _activeConnection != null)
-                    {
-                        try
-                        {
-                            // cleanup
-                            Unprepare();
-                        }
-                        catch (Exception)
-                        {
-                            // we do not really care about errors in unprepare (may be the old connection went bad)
-                        }
-                        finally
-                        {
-                            // clean prepare status (even successful Unprepare does not do that)
-                            _prepareHandle = s_cachedInvalidPrepareHandle;
-                            _execType = EXECTYPE.UNPREPARED;
-                        }
-                    }
-                }
-
-                _activeConnection = value;
-            }
-        }
-
-        protected override DbConnection DbConnection
-        {
-            get
-            {
-                return Connection;
-            }
-            set
-            {
-                Connection = (SqlConnection)value;
-            }
-        }
-
-        private SqlInternalConnectionTds InternalTdsConnection
-        {
-            get
-            {
-                return (SqlInternalConnectionTds)_activeConnection.InnerConnection;
-            }
-        }
-
-        public SqlNotificationRequest Notification
-        {
-            get
-            {
-                return _notification;
-            }
-            set
-            {
-                _sqlDep = null;
-                _notification = value;
-            }
-        }
-
-        internal SqlStatistics Statistics
-        {
-            get
-            {
-                if (null != _activeConnection)
-                {
-                    if (_activeConnection.StatisticsEnabled ||
-                        _diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand))
-                    {
-                        return _activeConnection.Statistics;
-                    }
-                }
-                return null;
-            }
-        }
-
-        public new SqlTransaction Transaction
-        {
-            get
-            {
-                // if the transaction object has been zombied, just return null
-                if ((null != _transaction) && (null == _transaction.Connection))
-                {
-                    _transaction = null;
-                }
-                return _transaction;
-            }
-            set
-            {
-                // Don't allow the transaction to be changed while in an async operation.
-                if (_transaction != value && _activeConnection != null)
-                { // If new value...
-                    if (cachedAsyncState.PendingAsyncOperation)
-                    { // If in pending async state, throw
-                        throw SQL.CannotModifyPropertyAsyncOperationInProgress();
-                    }
-                }
-
-                _transaction = value;
-            }
-        }
-
-        protected override DbTransaction DbTransaction
-        {
-            get
-            {
-                return Transaction;
-            }
-            set
-            {
-                Transaction = (SqlTransaction)value;
-            }
-        }
-
-        public override string CommandText
-        {
-            get
-            {
-                string value = _commandText;
-                return ((null != value) ? value : string.Empty);
-            }
-            set
-            {
-                if (_commandText != value)
-                {
-                    PropertyChanging();
-                    _commandText = value;
-                }
-            }
-        }
-
-        public override int CommandTimeout
-        {
-            get
-            {
-                return _commandTimeout;
-            }
-            set
-            {
-                if (value < 0)
-                {
-                    throw ADP.InvalidCommandTimeout(value);
-                }
-                if (value != _commandTimeout)
-                {
-                    PropertyChanging();
-                    _commandTimeout = value;
-                }
-            }
-        }
-
-        public void ResetCommandTimeout()
-        {
-            if (ADP.DefaultCommandTimeout != _commandTimeout)
-            {
-                PropertyChanging();
-                _commandTimeout = ADP.DefaultCommandTimeout;
-            }
-        }
-
-        public override CommandType CommandType
-        {
-            get
-            {
-                CommandType cmdType = _commandType;
-                return ((0 != cmdType) ? cmdType : CommandType.Text);
-            }
-            set
-            {
-                if (_commandType != value)
-                {
-                    switch (value)
-                    {
-                        case CommandType.Text:
-                        case CommandType.StoredProcedure:
-                            PropertyChanging();
-                            _commandType = value;
-                            break;
-                        case System.Data.CommandType.TableDirect:
-                            throw SQL.NotSupportedCommandType(value);
-                        default:
-                            throw ADP.InvalidCommandType(value);
-                    }
-                }
-            }
-        }
-
-        // @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
-        // to limit the number of components that clutter the design surface,
-        // when the DataAdapter design wizard generates the insert/update/delete commands it will
-        // set the DesignTimeVisible property to false so that cmds won't appear as individual objects
-        public override bool DesignTimeVisible
-        {
-            get
-            {
-                return !_designTimeInvisible;
-            }
-            set
-            {
-                _designTimeInvisible = !value;
-            }
-        }
-
-        public new SqlParameterCollection Parameters
-        {
-            get
-            {
-                if (null == _parameters)
-                {
-                    // delay the creation of the SqlParameterCollection
-                    // until user actually uses the Parameters property
-                    _parameters = new SqlParameterCollection();
-                }
-                return _parameters;
-            }
-        }
-
-        protected override DbParameterCollection DbParameterCollection
-        {
-            get
-            {
-                return Parameters;
-            }
-        }
-
-        public override UpdateRowSource UpdatedRowSource
-        {
-            get
-            {
-                return _updatedRowSource;
-            }
-            set
-            {
-                switch (value)
-                {
-                    case UpdateRowSource.None:
-                    case UpdateRowSource.OutputParameters:
-                    case UpdateRowSource.FirstReturnedRecord:
-                    case UpdateRowSource.Both:
-                        _updatedRowSource = value;
-                        break;
-                    default:
-                        throw ADP.InvalidUpdateRowSource(value);
-                }
-            }
-        }
-
-        public event StatementCompletedEventHandler StatementCompleted
-        {
-            add
-            {
-                _statementCompletedEventHandler += value;
-            }
-            remove
-            {
-                _statementCompletedEventHandler -= value;
-            }
-        }
-
-        internal void OnStatementCompleted(int recordCount)
-        {
-            if (0 <= recordCount)
-            {
-                StatementCompletedEventHandler handler = _statementCompletedEventHandler;
-                if (null != handler)
-                {
-                    try
-                    {
-                        handler(this, new StatementCompletedEventArgs(recordCount));
-                    }
-                    catch (Exception e)
-                    {
-                        if (!ADP.IsCatchableOrSecurityExceptionType(e))
-                        {
-                            throw;
-                        }
-                    }
-                }
-            }
-        }
-
-        private void PropertyChanging()
-        { // also called from SqlParameterCollection
-            this.IsDirty = true;
-        }
-
-        public override void Prepare()
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                // only prepare if batch with parameters
-                if (
-                    this.IsPrepared && !this.IsDirty
-                    || (this.CommandType == CommandType.StoredProcedure)
-                    || (
-                            (System.Data.CommandType.Text == this.CommandType)
-                            && (0 == GetParameterCount(_parameters))
-                        )
-                )
-                {
-                    if (null != Statistics)
-                    {
-                        Statistics.SafeIncrement(ref Statistics._prepares);
-                    }
-                    _hiddenPrepare = false;
-                }
-                else
-                {
-                    // Validate the command outside of the try\catch to avoid putting the _stateObj on error
-                    ValidateCommand(async: false);
-
-                    bool processFinallyBlock = true;
-                    try
-                    {
-                        // NOTE: The state object isn't actually needed for this, but it is still here for back-compat (since it does a bunch of checks)
-                        GetStateObject();
-
-                        // Loop through parameters ensuring that we do not have unspecified types, sizes, scales, or precisions
-                        if (null != _parameters)
-                        {
-                            int count = _parameters.Count;
-                            for (int i = 0; i < count; ++i)
-                            {
-                                _parameters[i].Prepare(this);
-                            }
-                        }
-
-                        InternalPrepare();
-                    }
-                    catch (Exception e)
-                    {
-                        processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                        throw;
-                    }
-                    finally
-                    {
-                        if (processFinallyBlock)
-                        {
-                            _hiddenPrepare = false; // The command is now officially prepared
-
-                            ReliablePutStateObject();
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private void InternalPrepare()
-        {
-            if (this.IsDirty)
-            {
-                Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters
-                //
-                // someone changed the command text or the parameter schema so we must unprepare the command
-                //
-                this.Unprepare();
-                this.IsDirty = false;
-            }
-            Debug.Assert(_execType != EXECTYPE.PREPARED, "Invalid attempt to Prepare already Prepared command!");
-            Debug.Assert(_activeConnection != null, "must have an open connection to Prepare");
-            Debug.Assert(null != _stateObj, "TdsParserStateObject should not be null");
-            Debug.Assert(null != _stateObj.Parser, "TdsParser class should not be null in Command.Execute!");
-            Debug.Assert(_stateObj.Parser == _activeConnection.Parser, "stateobject parser not same as connection parser");
-            Debug.Assert(false == _inPrepare, "Already in Prepare cycle, this.inPrepare should be false!");
-
-            // remember that the user wants to do a prepare but don't actually do an rpc
-            _execType = EXECTYPE.PREPAREPENDING;
-            // Note the current close count of the connection - this will tell us if the connection has been closed between calls to Prepare() and Execute
-            _preparedConnectionCloseCount = _activeConnection.CloseCount;
-            _preparedConnectionReconnectCount = _activeConnection.ReconnectCount;
-
-            if (null != Statistics)
-            {
-                Statistics.SafeIncrement(ref Statistics._prepares);
-            }
-        }
-
-        // SqlInternalConnectionTds needs to be able to unprepare a statement
-        internal void Unprepare()
-        {
-            Debug.Assert(true == IsPrepared, "Invalid attempt to Unprepare a non-prepared command!");
-            Debug.Assert(_activeConnection != null, "must have an open connection to UnPrepare");
-            Debug.Assert(false == _inPrepare, "_inPrepare should be false!");
-            _execType = EXECTYPE.PREPAREPENDING;
-            // Don't zero out the handle because we'll pass it in to sp_prepexec on the next prepare
-            // Unless the close count isn't the same as when we last prepared
-            if ((_activeConnection.CloseCount != _preparedConnectionCloseCount) || (_activeConnection.ReconnectCount != _preparedConnectionReconnectCount))
-            {
-                // reset our handle
-                _prepareHandle = s_cachedInvalidPrepareHandle;
-            }
-
-            _cachedMetaData = null;
-        }
-
-
-        // Cancel is supposed to be multi-thread safe.
-        // It doesn't make sense to verify the connection exists or that it is open during cancel
-        // because immediately after checkin the connection can be closed or removed via another thread.
-        //
-        public override void Cancel()
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                // If we are in reconnect phase simply cancel the waiting task
-                var reconnectCompletionSource = _reconnectionCompletionSource;
-                if (reconnectCompletionSource != null)
-                {
-                    if (reconnectCompletionSource.TrySetCanceled())
-                    {
-                        return;
-                    }
-                }
-
-                // the pending data flag means that we are awaiting a response or are in the middle of processing a response
-                // if we have no pending data, then there is nothing to cancel
-                // if we have pending data, but it is not a result of this command, then we don't cancel either.  Note that
-                // this model is implementable because we only allow one active command at any one time.  This code
-                // will have to change we allow multiple outstanding batches
-                if (null == _activeConnection)
-                {
-                    return;
-                }
-                SqlInternalConnectionTds connection = (_activeConnection.InnerConnection as SqlInternalConnectionTds);
-                if (null == connection)
-                {  // Fail with out locking
-                    return;
-                }
-
-                // The lock here is to protect against the command.cancel / connection.close race condition
-                // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
-                // the command will no longer be cancelable.  It might be desirable to be able to cancel the close operation, but this is
-                // outside of the scope of Whidbey RTM.  See (SqlConnection::Close) for other lock.
-                lock (connection)
-                {
-                    if (connection != (_activeConnection.InnerConnection as SqlInternalConnectionTds))
-                    { // make sure the connection held on the active connection is what we have stored in our temp connection variable, if not between getting "connection" and taking the lock, the connection has been closed
-                        return;
-                    }
-
-                    TdsParser parser = connection.Parser;
-                    if (null == parser)
-                    {
-                        return;
-                    }
-
-
-                    if (!_pendingCancel)
-                    { // Do nothing if already pending.
-                      // Before attempting actual cancel, set the _pendingCancel flag to false.
-                      // This denotes to other thread before obtaining stateObject from the
-                      // session pool that there is another thread wishing to cancel.
-                      // The period in question is between entering the ExecuteAPI and obtaining
-                      // a stateObject.
-                        _pendingCancel = true;
-
-                        TdsParserStateObject stateObj = _stateObj;
-                        if (null != stateObj)
-                        {
-                            stateObj.Cancel(this);
-                        }
-                        else
-                        {
-                            SqlDataReader reader = connection.FindLiveReader(this);
-                            if (reader != null)
-                            {
-                                reader.Cancel(this);
-                            }
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public new SqlParameter CreateParameter()
-        {
-            return new SqlParameter();
-        }
-
-        protected override DbParameter CreateDbParameter()
-        {
-            return CreateParameter();
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            if (disposing)
-            { // release managed objects
-                _cachedMetaData = null;
-            }
-            // release unmanaged objects
-            base.Dispose(disposing);
-        }
-
-        public override object ExecuteScalar()
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-            Guid operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            SqlStatistics statistics = null;
-
-            Exception e = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                SqlDataReader ds;
-                ds = RunExecuteReader(0, RunBehavior.ReturnImmediately, returnStream: true);
-                return CompleteExecuteScalar(ds, false);
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-
-                if (e != null)
-                {
-                    _diagnosticListener.WriteCommandError(operationId, this, e);
-                }
-                else
-                {
-                    _diagnosticListener.WriteCommandAfter(operationId, this);
-                }
-            }
-        }
-
-        private object CompleteExecuteScalar(SqlDataReader ds, bool returnSqlValue)
-        {
-            object retResult = null;
-
-            try
-            {
-                if (ds.Read())
-                {
-                    if (ds.FieldCount > 0)
-                    {
-                        if (returnSqlValue)
-                        {
-                            retResult = ds.GetSqlValue(0);
-                        }
-                        else
-                        {
-                            retResult = ds.GetValue(0);
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                // clean off the wire
-                ds.Close();
-            }
-
-            return retResult;
-        }
-
-        public override int ExecuteNonQuery()
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-            Guid operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            SqlStatistics statistics = null;
-
-            Exception e = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                InternalExecuteNonQuery(completion: null, sendToPipe: false, timeout: CommandTimeout);
-                return _rowsAffected;
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-
-                if (e != null)
-                {
-                    _diagnosticListener.WriteCommandError(operationId, this, e);
-                }
-                else
-                {
-                    _diagnosticListener.WriteCommandAfter(operationId, this);
-                }
-            }
-        }
-
-        public IAsyncResult BeginExecuteNonQuery()
-        {
-            // BeginExecuteNonQuery will track ExecutionTime for us
-            return BeginExecuteNonQuery(null, null);
-        }
-
-        public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject)
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-            ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
-                                    // back into pool when we should not.
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
-
-                try
-                { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
-                    Task execNQ = InternalExecuteNonQuery(completion, false, CommandTimeout, asyncWrite: true);
-
-                    // must finish caching information before ReadSni which can activate the callback before returning
-                    cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteNonQuery), _activeConnection);
-                    if (execNQ != null)
-                    {
-                        AsyncHelper.ContinueTaskWithState(execNQ, completion,
-                            state: Tuple.Create(this, completion),
-                            onSuccess: state =>
-                            {
-                                var parameters = (Tuple<SqlCommand, TaskCompletionSource<object>>)state;
-                                parameters.Item1.BeginExecuteNonQueryInternalReadStage(parameters.Item2);
-                            }
-                        );
-                    }
-                    else
-                    {
-                        BeginExecuteNonQueryInternalReadStage(completion);
-                    }
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableOrSecurityExceptionType(e))
-                    {
-                        // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
-                        throw;
-                    }
-
-                    // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
-                    ReliablePutStateObject();
-                    throw;
-                }
-
-                // Add callback after work is done to avoid overlapping Begin\End methods
-                if (callback != null)
-                {
-                    completion.Task.ContinueWith(
-                        (task, state) => ((AsyncCallback)state)(task),
-                        state: callback,
-                        CancellationToken.None,
-                        TaskContinuationOptions.DenyChildAttach,
-                        TaskScheduler.Default);
-                }
-
-                return completion.Task;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource<object> completion)
-        {
-            // Read SNI does not have catches for async exceptions, handle here.
-            try
-            {
-                _stateObj.ReadSni(completion);
-            }
-            catch (Exception)
-            {
-                // Similarly, if an exception occurs put the stateObj back into the pool.
-                // and reset async cache information to allow a second async execute
-                if (null != _cachedAsyncState)
-                {
-                    _cachedAsyncState.ResetAsyncState();
-                }
-                ReliablePutStateObject();
-                throw;
-            }
-        }
-
-        private void VerifyEndExecuteState(Task completionTask, string endMethod)
-        {
-            Debug.Assert(completionTask != null);
-
-            if (completionTask.IsCanceled)
-            {
-                if (_stateObj != null)
-                {
-                    _stateObj.Parser.State = TdsParserState.Broken; // We failed to respond to attention, we have to quit!
-                    _stateObj.Parser.Connection.BreakConnection();
-                    _stateObj.Parser.ThrowExceptionAndWarning(_stateObj);
-                }
-                else
-                {
-                    Debug.Assert(_reconnectionCompletionSource == null || _reconnectionCompletionSource.Task.IsCanceled, "ReconnectCompletionSource should be null or cancelled");
-                    throw SQL.CR_ReconnectionCancelled();
-                }
-            }
-            else if (completionTask.IsFaulted)
-            {
-                throw completionTask.Exception.InnerException;
-            }
-            if (cachedAsyncState.EndMethodName == null)
-            {
-                throw ADP.MethodCalledTwice(endMethod);
-            }
-            if (endMethod != cachedAsyncState.EndMethodName)
-            {
-                throw ADP.MismatchedAsyncResult(cachedAsyncState.EndMethodName, endMethod);
-            }
-            if ((_activeConnection.State != ConnectionState.Open) || (!cachedAsyncState.IsActiveConnectionValid(_activeConnection)))
-            {
-                // If the connection is not 'valid' then it was closed while we were executing
-                throw ADP.ClosedConnectionError();
-            }
-        }
-
-        private void WaitForAsyncResults(IAsyncResult asyncResult)
-        {
-            if (!asyncResult.IsCompleted)
-            {
-                asyncResult.AsyncWaitHandle.WaitOne();
-            }
-            _stateObj._networkPacketTaskSource = null;
-            _activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
-        }
-
-        private void ThrowIfReconnectionHasBeenCanceled()
-        {
-            if (_stateObj == null)
-            {
-                var reconnectionCompletionSource = _reconnectionCompletionSource;
-                if (reconnectionCompletionSource != null && reconnectionCompletionSource.Task.IsCanceled)
-                {
-                    throw SQL.CR_ReconnectionCancelled();
-                }
-            }
-        }
-
-        public int EndExecuteNonQuery(IAsyncResult asyncResult)
-        {
-            Exception asyncException = ((Task)asyncResult).Exception;
-            if (asyncException != null)
-            {
-                // Leftover exception from the Begin...InternalReadStage
-                if (cachedAsyncState != null)
-                {
-                    cachedAsyncState.ResetAsyncState();
-                }
-                ReliablePutStateObject();
-                throw asyncException.InnerException;
-            }
-            else
-            {
-                ThrowIfReconnectionHasBeenCanceled();
-                // lock on _stateObj prevents races with close/cancel.
-                lock (_stateObj)
-                {
-                    return EndExecuteNonQueryInternal(asyncResult);
-                }
-            }
-        }
-
-        private int EndExecuteNonQueryInternal(IAsyncResult asyncResult)
-        {
-            SqlStatistics statistics = null;
-
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                VerifyEndExecuteState((Task)asyncResult, nameof(EndExecuteNonQuery));
-                WaitForAsyncResults(asyncResult);
-
-                bool processFinallyBlock = true;
-                try
-                {
-                    CheckThrowSNIException();
-
-                    // only send over SQL Batch command if we are not a stored proc and have no parameters
-                    if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters)))
-                    {
-                        try
-                        {
-                            bool dataReady;
-                            Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-                            bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
-                            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-                        }
-                        finally
-                        {
-                            cachedAsyncState.ResetAsyncState();
-                        }
-                    }
-                    else
-                    { // otherwise, use a full-fledged execute that can handle params and stored procs
-                        SqlDataReader reader = CompleteAsyncExecuteReader();
-                        if (null != reader)
-                        {
-                            reader.Close();
-                        }
-                    }
-                }
-                catch (Exception e)
-                {
-                    processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                    throw;
-                }
-                finally
-                {
-                    if (processFinallyBlock)
-                    {
-                        PutStateObject();
-                    }
-                }
-
-                Debug.Assert(null == _stateObj, "non-null state object in EndExecuteNonQuery");
-                return _rowsAffected;
-            }
-            catch (Exception e)
-            {
-                if (cachedAsyncState != null)
-                {
-                    cachedAsyncState.ResetAsyncState();
-                };
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    ReliablePutStateObject();
-                };
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private Task InternalExecuteNonQuery(TaskCompletionSource<object> completion, bool sendToPipe, int timeout, bool asyncWrite = false, [CallerMemberName] string methodName = "")
-        {
-            bool async = (null != completion);
-
-            SqlStatistics statistics = Statistics;
-            _rowsAffected = -1;
-
-            // this function may throw for an invalid connection
-            // returns false for empty command text
-            ValidateCommand(async, methodName);
-
-            CheckNotificationStateAndAutoEnlist(); // Only call after validate - requires non null connection!
-
-            Task task = null;
-
-            // only send over SQL Batch command if we are not a stored proc and have no parameters and not in batch RPC mode
-            if (!BatchRPCMode && (System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters)))
-            {
-                Debug.Assert(!sendToPipe, "trying to send non-context command to pipe");
-                if (null != statistics)
-                {
-                    if (!this.IsDirty && this.IsPrepared)
-                    {
-                        statistics.SafeIncrement(ref statistics._preparedExecs);
-                    }
-                    else
-                    {
-                        statistics.SafeIncrement(ref statistics._unpreparedExecs);
-                    }
-                }
-
-                task = RunExecuteNonQueryTds(methodName, async, timeout, asyncWrite);
-            }
-            else
-            { // otherwise, use a full-fledged execute that can handle params and stored procs
-                Debug.Assert(!sendToPipe, "trying to send non-context command to pipe");
-                SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, completion, timeout, out task, asyncWrite, methodName);
-                if (null != reader)
-                {
-                    if (task != null)
-                    {
-                        task = AsyncHelper.CreateContinuationTaskWithState(task,
-                            state: reader,
-                            onSuccess: state => ((SqlDataReader)state).Close()
-                        );
-                    }
-                    else
-                    {
-                        reader.Close();
-                    }
-                }
-            }
-            Debug.Assert(async || null == _stateObj, "non-null state object in InternalExecuteNonQuery");
-            return task;
-        }
-
-        public XmlReader ExecuteXmlReader()
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-            Guid operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            SqlStatistics statistics = null;
-
-            Exception e = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                // use the reader to consume metadata
-                SqlDataReader ds;
-                ds = RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, returnStream: true);
-                return CompleteXmlReader(ds);
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-
-                if (e != null)
-                {
-                    _diagnosticListener.WriteCommandError(operationId, this, e);
-                }
-                else
-                {
-                    _diagnosticListener.WriteCommandAfter(operationId, this);
-                }
-            }
-        }
-
-
-        public IAsyncResult BeginExecuteXmlReader()
-        {
-            return BeginExecuteXmlReader(null, null);
-        }
-
-        public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject)
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-            ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
-                                    // back into pool when we should not.
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
-
-                Task writeTask;
-                try
-                { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
-                    RunExecuteReader(CommandBehavior.SequentialAccess, RunBehavior.ReturnImmediately, true, completion, CommandTimeout, out writeTask, asyncWrite: true);
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableOrSecurityExceptionType(e))
-                    {
-                        // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
-                        throw;
-                    }
-
-                    // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
-                    ReliablePutStateObject();
-                    throw;
-                }
-
-                // must finish caching information before ReadSni which can activate the callback before returning
-                cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteXmlReader), _activeConnection);
-                if (writeTask != null)
-                {
-                    AsyncHelper.ContinueTaskWithState(writeTask, completion,
-                        state: Tuple.Create(this, completion),
-                        onSuccess: state =>
-                        {
-                            var parameters = (Tuple<SqlCommand, TaskCompletionSource<object>>)state;
-                            parameters.Item1.BeginExecuteXmlReaderInternalReadStage(parameters.Item2);
-                        }
-                    );
-                }
-                else
-                {
-                    BeginExecuteXmlReaderInternalReadStage(completion);
-                }
-
-                // Add callback after work is done to avoid overlapping Begin\End methods
-                if (callback != null)
-                {
-                    completion.Task.ContinueWith(
-                        (task, state) => ((AsyncCallback)state)(task),
-                        state: callback,
-                        CancellationToken.None,
-                        TaskContinuationOptions.DenyChildAttach,
-                        TaskScheduler.Default);
-                }
-                return completion.Task;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private void BeginExecuteXmlReaderInternalReadStage(TaskCompletionSource<object> completion)
-        {
-            Debug.Assert(completion != null, "Completion source should not be null");
-            // Read SNI does not have catches for async exceptions, handle here.
-            try
-            {
-                _stateObj.ReadSni(completion);
-            }
-            catch (Exception e)
-            {
-                // Similarly, if an exception occurs put the stateObj back into the pool.
-                // and reset async cache information to allow a second async execute
-                if (null != _cachedAsyncState)
-                {
-                    _cachedAsyncState.ResetAsyncState();
-                }
-                ReliablePutStateObject();
-                completion.TrySetException(e);
-            }
-        }
-
-
-        public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult)
-        {
-            Exception asyncException = ((Task)asyncResult).Exception;
-            if (asyncException != null)
-            {
-                // Leftover exception from the Begin...InternalReadStage
-                if (cachedAsyncState != null)
-                {
-                    cachedAsyncState.ResetAsyncState();
-                }
-                ReliablePutStateObject();
-                throw asyncException.InnerException;
-            }
-            else
-            {
-                ThrowIfReconnectionHasBeenCanceled();
-                // lock on _stateObj prevents races with close/cancel.
-                lock (_stateObj)
-                {
-                    return EndExecuteXmlReaderInternal(asyncResult);
-                }
-            }
-        }
-
-        private XmlReader EndExecuteXmlReaderInternal(IAsyncResult asyncResult)
-        {
-            try
-            {
-                return CompleteXmlReader(InternalEndExecuteReader(asyncResult, nameof(EndExecuteXmlReader)), async: true);
-            }
-            catch (Exception e)
-            {
-                if (cachedAsyncState != null)
-                {
-                    cachedAsyncState.ResetAsyncState();
-                };
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    ReliablePutStateObject();
-                };
-                throw;
-            }
-        }
-
-        private XmlReader CompleteXmlReader(SqlDataReader ds, bool async = false)
-        {
-            XmlReader xr = null;
-
-            SmiExtendedMetaData[] md = ds.GetInternalSmiMetaData();
-            bool isXmlCapable = (null != md && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText
-                                                         || md[0].SqlDbType == SqlDbType.NVarChar
-                                                         || md[0].SqlDbType == SqlDbType.Xml));
-
-            if (isXmlCapable)
-            {
-                try
-                {
-                    SqlStream sqlBuf = new SqlStream(ds, true /*addByteOrderMark*/, (md[0].SqlDbType == SqlDbType.Xml) ? false : true /*process all rows*/);
-                    xr = sqlBuf.ToXmlReader(async);
-                }
-                catch (Exception e)
-                {
-                    if (ADP.IsCatchableExceptionType(e))
-                    {
-                        ds.Close();
-                    }
-                    throw;
-                }
-            }
-            if (xr == null)
-            {
-                ds.Close();
-                throw SQL.NonXmlResult();
-            }
-            return xr;
-        }
-
-
-        protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
-        {
-            return ExecuteReader(behavior);
-        }
-
-        public new SqlDataReader ExecuteReader()
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                return ExecuteReader(CommandBehavior.Default);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public new SqlDataReader ExecuteReader(CommandBehavior behavior)
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-            Guid operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            SqlStatistics statistics = null;
-
-            Exception e = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                return RunExecuteReader(behavior, RunBehavior.ReturnImmediately, returnStream: true);
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-
-                if (e != null)
-                {
-                    _diagnosticListener.WriteCommandError(operationId, this, e);
-                }
-                else
-                {
-                    _diagnosticListener.WriteCommandAfter(operationId, this);
-                }
-            }
-        }
-
-
-        public SqlDataReader EndExecuteReader(IAsyncResult asyncResult)
-        {
-            Exception asyncException = ((Task)asyncResult).Exception;
-            if (asyncException != null)
-            {
-                // Leftover exception from the Begin...InternalReadStage
-                if (cachedAsyncState != null)
-                {
-                    cachedAsyncState.ResetAsyncState();
-                }
-                ReliablePutStateObject();
-                throw asyncException.InnerException;
-            }
-            else
-            {
-                ThrowIfReconnectionHasBeenCanceled();
-                // lock on _stateObj prevents races with close/cancel.
-                lock (_stateObj)
-                {
-                    return EndExecuteReaderInternal(asyncResult);
-                }
-            }
-        }
-
-        private SqlDataReader EndExecuteReaderInternal(IAsyncResult asyncResult)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                return InternalEndExecuteReader(asyncResult, nameof(EndExecuteReader));
-            }
-            catch (Exception e)
-            {
-                if (cachedAsyncState != null)
-                {
-                    cachedAsyncState.ResetAsyncState();
-                };
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    ReliablePutStateObject();
-                };
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public IAsyncResult BeginExecuteReader()
-        {
-            return BeginExecuteReader(null, null, CommandBehavior.Default);
-        }
-
-        public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject)
-        {
-            return BeginExecuteReader(callback, stateObject, CommandBehavior.Default);
-        }
-
-        public IAsyncResult BeginExecuteReader(CommandBehavior behavior)
-        {
-            return BeginExecuteReader(null, null, behavior);
-        }
-
-        public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior)
-        {
-            // Reset _pendingCancel upon entry into any Execute - used to synchronize state
-            // between entry into Execute* API and the thread obtaining the stateObject.
-            _pendingCancel = false;
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                TaskCompletionSource<object> completion = new TaskCompletionSource<object>(stateObject);
-
-                ValidateAsyncCommand(); // Special case - done outside of try/catches to prevent putting a stateObj
-                                        // back into pool when we should not.
-
-                Task writeTask = null;
-                try
-                { // InternalExecuteNonQuery already has reliability block, but if failure will not put stateObj back into pool.
-                    RunExecuteReader(behavior, RunBehavior.ReturnImmediately, true, completion, CommandTimeout, out writeTask, asyncWrite: true);
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableOrSecurityExceptionType(e))
-                    {
-                        // If not catchable - the connection has already been caught and doomed in RunExecuteReader.
-                        throw;
-                    }
-
-                    // For async, RunExecuteReader will never put the stateObj back into the pool, so do so now.
-                    ReliablePutStateObject();
-                    throw;
-                }
-
-                // must finish caching information before ReadSni which can activate the callback before returning
-                cachedAsyncState.SetActiveConnectionAndResult(completion, nameof(EndExecuteReader), _activeConnection);
-                if (writeTask != null)
-                {
-                    AsyncHelper.ContinueTaskWithState(writeTask, completion,
-                        state: Tuple.Create(this, completion),
-                        onSuccess: state =>
-                        {
-                            var parameters = (Tuple<SqlCommand, TaskCompletionSource<object>>)state;
-                            parameters.Item1.BeginExecuteReaderInternalReadStage(parameters.Item2);
-                        }
-                    );
-                }
-                else
-                {
-                    BeginExecuteReaderInternalReadStage(completion);
-                }
-
-                // Add callback after work is done to avoid overlapping Begin\End methods
-                if (callback != null)
-                {
-                    completion.Task.ContinueWith(
-                        (task, state) => ((AsyncCallback)state)(task),
-                        state: callback,
-                        CancellationToken.None,
-                        TaskContinuationOptions.DenyChildAttach,
-                        TaskScheduler.Default);
-                }
-                return completion.Task;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private void BeginExecuteReaderInternalReadStage(TaskCompletionSource<object> completion)
-        {
-            Debug.Assert(completion != null, "CompletionSource should not be null");
-            // Read SNI does not have catches for async exceptions, handle here.
-            try
-            {
-                _stateObj.ReadSni(completion);
-            }
-            catch (Exception e)
-            {
-                // Similarly, if an exception occurs put the stateObj back into the pool.
-                // and reset async cache information to allow a second async execute
-                if (null != _cachedAsyncState)
-                {
-                    _cachedAsyncState.ResetAsyncState();
-                }
-                ReliablePutStateObject();
-                completion.TrySetException(e);
-            }
-        }
-
-        private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string endMethod)
-        {
-            VerifyEndExecuteState((Task)asyncResult, endMethod);
-            WaitForAsyncResults(asyncResult);
-
-            CheckThrowSNIException();
-
-            SqlDataReader reader = CompleteAsyncExecuteReader();
-            Debug.Assert(null == _stateObj, "non-null state object in InternalEndExecuteReader");
-            return reader;
-        }
-
-        public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
-        {
-            Guid operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            TaskCompletionSource<int> source = new TaskCompletionSource<int>();
-
-            CancellationTokenRegistration registration = default;
-            if (cancellationToken.CanBeCanceled)
-            {
-                if (cancellationToken.IsCancellationRequested)
-                {
-                    source.SetCanceled();
-                    return source.Task;
-                }
-                registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), this);
-            }
-
-            Task<int> returnedTask = source.Task;
-            try
-            {
-                RegisterForConnectionCloseNotification(ref returnedTask);
-
-                Task<int>.Factory.FromAsync(BeginExecuteNonQuery, EndExecuteNonQuery, null).ContinueWith((t) =>
-                {
-                    registration.Dispose();
-                    if (t.IsFaulted)
-                    {
-                        Exception e = t.Exception.InnerException;
-                        _diagnosticListener.WriteCommandError(operationId, this, e);
-                        source.SetException(e);
-                    }
-                    else
-                    {
-                        if (t.IsCanceled)
-                        {
-                            source.SetCanceled();
-                        }
-                        else
-                        {
-                            source.SetResult(t.Result);
-                        }
-                        _diagnosticListener.WriteCommandAfter(operationId, this);
-                    }
-                }, TaskScheduler.Default);
-            }
-            catch (Exception e)
-            {
-                _diagnosticListener.WriteCommandError(operationId, this, e);
-                source.SetException(e);
-            }
-
-            return returnedTask;
-        }
-
-        protected override Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
-        {
-            return ExecuteReaderAsync(behavior, cancellationToken).ContinueWith<DbDataReader>((result) =>
-            {
-                if (result.IsFaulted)
-                {
-                    throw result.Exception.InnerException;
-                }
-                return result.Result;
-            }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnCanceled, TaskScheduler.Default);
-        }
-
-        public new Task<SqlDataReader> ExecuteReaderAsync()
-        {
-            return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None);
-        }
-
-        public new Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior)
-        {
-            return ExecuteReaderAsync(behavior, CancellationToken.None);
-        }
-
-        public new Task<SqlDataReader> ExecuteReaderAsync(CancellationToken cancellationToken)
-        {
-            return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken);
-        }
-
-        public new Task<SqlDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
-        {
-            Guid operationId = default(Guid);
-            if (!_parentOperationStarted)
-                operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            TaskCompletionSource<SqlDataReader> source = new TaskCompletionSource<SqlDataReader>();
-
-            CancellationTokenRegistration registration = default;
-            if (cancellationToken.CanBeCanceled)
-            {
-                if (cancellationToken.IsCancellationRequested)
-                {
-                    source.SetCanceled();
-                    return source.Task;
-                }
-                registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), this);
-            }
-
-            Task<SqlDataReader> returnedTask = source.Task;
-            try
-            {
-                RegisterForConnectionCloseNotification(ref returnedTask);
-
-                Task<SqlDataReader>.Factory.FromAsync((commandBehavior, callback, stateObject) => BeginExecuteReader(callback, stateObject, commandBehavior), EndExecuteReader, behavior, null).ContinueWith((t) =>
-                {
-                    registration.Dispose();
-                    if (t.IsFaulted)
-                    {
-                        Exception e = t.Exception.InnerException;
-                        if (!_parentOperationStarted)
-                            _diagnosticListener.WriteCommandError(operationId, this, e);
-                        source.SetException(e);
-                    }
-                    else
-                    {
-                        if (t.IsCanceled)
-                        {
-                            source.SetCanceled();
-                        }
-                        else
-                        {
-                            source.SetResult(t.Result);
-                        }
-                        if (!_parentOperationStarted)
-                            _diagnosticListener.WriteCommandAfter(operationId, this);
-                    }
-                }, TaskScheduler.Default);
-            }
-            catch (Exception e)
-            {
-                if (!_parentOperationStarted)
-                    _diagnosticListener.WriteCommandError(operationId, this, e);
-
-                source.SetException(e);
-            }
-
-            return returnedTask;
-        }
-
-        public override Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
-        {
-            _parentOperationStarted = true;
-            Guid operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            return ExecuteReaderAsync(cancellationToken).ContinueWith((executeTask) =>
-            {
-                TaskCompletionSource<object> source = new TaskCompletionSource<object>();
-                if (executeTask.IsCanceled)
-                {
-                    source.SetCanceled();
-                }
-                else if (executeTask.IsFaulted)
-                {
-                    _diagnosticListener.WriteCommandError(operationId, this, executeTask.Exception.InnerException);
-                    source.SetException(executeTask.Exception.InnerException);
-                }
-                else
-                {
-                    SqlDataReader reader = executeTask.Result;
-                    reader.ReadAsync(cancellationToken).ContinueWith((readTask) =>
-                    {
-                        try
-                        {
-                            if (readTask.IsCanceled)
-                            {
-                                reader.Dispose();
-                                source.SetCanceled();
-                            }
-                            else if (readTask.IsFaulted)
-                            {
-                                reader.Dispose();
-                                _diagnosticListener.WriteCommandError(operationId, this, readTask.Exception.InnerException);
-                                source.SetException(readTask.Exception.InnerException);
-                            }
-                            else
-                            {
-                                Exception exception = null;
-                                object result = null;
-                                try
-                                {
-                                    bool more = readTask.Result;
-                                    if (more && reader.FieldCount > 0)
-                                    {
-                                        try
-                                        {
-                                            result = reader.GetValue(0);
-                                        }
-                                        catch (Exception e)
-                                        {
-                                            exception = e;
-                                        }
-                                    }
-                                }
-                                finally
-                                {
-                                    reader.Dispose();
-                                }
-                                if (exception != null)
-                                {
-                                    _diagnosticListener.WriteCommandError(operationId, this, exception);
-                                    source.SetException(exception);
-                                }
-                                else
-                                {
-                                    _diagnosticListener.WriteCommandAfter(operationId, this);
-                                    source.SetResult(result);
-                                }
-                            }
-                        }
-                        catch (Exception e)
-                        {
-                            // exception thrown by Dispose...
-                            source.SetException(e);
-                        }
-                    }, TaskScheduler.Default);
-                }
-                _parentOperationStarted = false;
-                return source.Task;
-            }, TaskScheduler.Default).Unwrap();
-        }
-
-        public Task<XmlReader> ExecuteXmlReaderAsync()
-        {
-            return ExecuteXmlReaderAsync(CancellationToken.None);
-        }
-
-        public Task<XmlReader> ExecuteXmlReaderAsync(CancellationToken cancellationToken)
-        {
-            Guid operationId = _diagnosticListener.WriteCommandBefore(this);
-
-            TaskCompletionSource<XmlReader> source = new TaskCompletionSource<XmlReader>();
-
-            CancellationTokenRegistration registration = default;
-            if (cancellationToken.CanBeCanceled)
-            {
-                if (cancellationToken.IsCancellationRequested)
-                {
-                    source.SetCanceled();
-                    return source.Task;
-                }
-                registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), this);
-            }
-
-            Task<XmlReader> returnedTask = source.Task;
-            try
-            {
-                RegisterForConnectionCloseNotification(ref returnedTask);
-
-                Task<XmlReader>.Factory.FromAsync(BeginExecuteXmlReader, EndExecuteXmlReader, null).ContinueWith((t) =>
-                {
-                    registration.Dispose();
-                    if (t.IsFaulted)
-                    {
-                        Exception e = t.Exception.InnerException;
-                        _diagnosticListener.WriteCommandError(operationId, this, e);
-                        source.SetException(e);
-                    }
-                    else
-                    {
-                        if (t.IsCanceled)
-                        {
-                            source.SetCanceled();
-                        }
-                        else
-                        {
-                            source.SetResult(t.Result);
-                        }
-                        _diagnosticListener.WriteCommandAfter(operationId, this);
-                    }
-                }, TaskScheduler.Default);
-            }
-            catch (Exception e)
-            {
-                _diagnosticListener.WriteCommandError(operationId, this, e);
-                source.SetException(e);
-            }
-
-            return returnedTask;
-        }
-
-        // If the user part is quoted, remove first and last brackets and then unquote any right square
-        // brackets in the procedure.  This is a very simple parser that performs no validation.  As
-        // with the function below, ideally we should have support from the server for this.
-        private static string UnquoteProcedurePart(string part)
-        {
-            if ((null != part) && (2 <= part.Length))
-            {
-                if ('[' == part[0] && ']' == part[part.Length - 1])
-                {
-                    part = part.Substring(1, part.Length - 2); // strip outer '[' & ']'
-                    part = part.Replace("]]", "]"); // undo quoted "]" from "]]" to "]"
-                }
-            }
-            return part;
-        }
-
-        // User value in this format: [server].[database].[schema].[sp_foo];1
-        // This function should only be passed "[sp_foo];1".
-        // This function uses a pretty simple parser that doesn't do any validation.
-        // Ideally, we would have support from the server rather than us having to do this.
-        private static string UnquoteProcedureName(string name, out object groupNumber)
-        {
-            groupNumber = null; // Out param - initialize value to no value.
-            string sproc = name;
-
-            if (null != sproc)
-            {
-                if (char.IsDigit(sproc[sproc.Length - 1]))
-                { // If last char is a digit, parse.
-                    int semicolon = sproc.LastIndexOf(';');
-                    if (semicolon != -1)
-                    { // If we found a semicolon, obtain the integer.
-                        string part = sproc.Substring(semicolon + 1);
-                        int number = 0;
-                        if (int.TryParse(part, out number))
-                        { // No checking, just fail if this doesn't work.
-                            groupNumber = number;
-                            sproc = sproc.Substring(0, semicolon);
-                        }
-                    }
-                }
-                sproc = UnquoteProcedurePart(sproc);
-            }
-            return sproc;
-        }
-
-        // Index into indirection arrays for columns of interest to DeriveParameters
-        private enum ProcParamsColIndex
-        {
-            ParameterName = 0,
-            ParameterType,
-            DataType, // obsolete in katmai, use ManagedDataType instead
-            ManagedDataType, // new in katmai
-            CharacterMaximumLength,
-            NumericPrecision,
-            NumericScale,
-            TypeCatalogName,
-            TypeSchemaName,
-            TypeName,
-            XmlSchemaCollectionCatalogName,
-            XmlSchemaCollectionSchemaName,
-            XmlSchemaCollectionName,
-            UdtTypeName, // obsolete in Katmai.  Holds the actual typename if UDT, since TypeName didn't back then.
-            DateTimeScale // new in Katmai
-        };
-
-        // Yukon- column ordinals (this array indexed by ProcParamsColIndex
-        internal static readonly string[] PreKatmaiProcParamsNames = new string[] {
-            "PARAMETER_NAME",           // ParameterName,
-            "PARAMETER_TYPE",           // ParameterType,
-            "DATA_TYPE",                // DataType
-            null,                       // ManagedDataType,     introduced in Katmai
-            "CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
-            "NUMERIC_PRECISION",        // NumericPrecision,
-            "NUMERIC_SCALE",            // NumericScale,
-            "UDT_CATALOG",              // TypeCatalogName,
-            "UDT_SCHEMA",               // TypeSchemaName,
-            "TYPE_NAME",                // TypeName,
-            "XML_CATALOGNAME",          // XmlSchemaCollectionCatalogName,
-            "XML_SCHEMANAME",           // XmlSchemaCollectionSchemaName,
-            "XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
-            "UDT_NAME",                 // UdtTypeName
-            null,                       // Scale for datetime types with scale, introduced in Katmai
-        };
-
-        // Katmai+ column ordinals (this array indexed by ProcParamsColIndex
-        internal static readonly string[] KatmaiProcParamsNames = new string[] {
-            "PARAMETER_NAME",           // ParameterName,
-            "PARAMETER_TYPE",           // ParameterType,
-            null,                       // DataType, removed from Katmai+
-            "MANAGED_DATA_TYPE",        // ManagedDataType,
-            "CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
-            "NUMERIC_PRECISION",        // NumericPrecision,
-            "NUMERIC_SCALE",            // NumericScale,
-            "TYPE_CATALOG_NAME",        // TypeCatalogName,
-            "TYPE_SCHEMA_NAME",         // TypeSchemaName,
-            "TYPE_NAME",                // TypeName,
-            "XML_CATALOGNAME",          // XmlSchemaCollectionCatalogName,
-            "XML_SCHEMANAME",           // XmlSchemaCollectionSchemaName,
-            "XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
-            null,                       // UdtTypeName, removed from Katmai+
-            "SS_DATETIME_PRECISION",    // Scale for datetime types with scale
-        };
-
-        internal void DeriveParameters()
-        {
-            switch (CommandType)
-            {
-                case CommandType.Text:
-                    throw ADP.DeriveParametersNotSupported(this);
-                case CommandType.StoredProcedure:
-                    break;
-                case CommandType.TableDirect:
-                    // CommandType.TableDirect - do nothing, parameters are not supported
-                    throw ADP.DeriveParametersNotSupported(this);
-                default:
-                    throw ADP.InvalidCommandType(CommandType);
-            }
-
-            // validate that we have a valid connection
-            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);
-            if (null == parsedSProc[3] || string.IsNullOrEmpty(parsedSProc[3]))
-            {
-                throw ADP.NoStoredProcedureExists(CommandText);
-            }
-
-            Debug.Assert(parsedSProc.Length == 4, "Invalid array length result from SqlCommandBuilder.ParseProcedureName");
-
-            SqlCommand paramsCmd = null;
-            StringBuilder cmdText = new StringBuilder();
-
-            // Build call for sp_procedure_params_rowset built of unquoted values from user:
-            // [user server, if provided].[user catalog, else current database].[sys if Yukon, else blank].[sp_procedure_params_rowset]
-
-            // Server - pass only if user provided.
-            if (!string.IsNullOrEmpty(parsedSProc[0]))
-            {
-                SqlCommandSet.BuildStoredProcedureName(cmdText, parsedSProc[0]);
-                cmdText.Append(".");
-            }
-
-            // Catalog - pass user provided, otherwise use current database.
-            if (string.IsNullOrEmpty(parsedSProc[1]))
-            {
-                parsedSProc[1] = Connection.Database;
-            }
-            SqlCommandSet.BuildStoredProcedureName(cmdText, parsedSProc[1]);
-            cmdText.Append(".");
-
-            // Schema - only if Yukon, and then only pass sys.  Also - pass managed version of sproc
-            // for Yukon, else older sproc.
-            string[] colNames;
-            bool useManagedDataType;
-            if (Connection.IsKatmaiOrNewer)
-            {
-                // Procedure - [sp_procedure_params_managed]
-                cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MGD10).Append("]");
-
-                colNames = KatmaiProcParamsNames;
-                useManagedDataType = true;
-            }
-            else
-            {
-                // Procedure - [sp_procedure_params_managed]
-                cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MANAGED).Append("]");
-
-                colNames = PreKatmaiProcParamsNames;
-                useManagedDataType = false;
-            }
-
-
-            paramsCmd = new SqlCommand(cmdText.ToString(), Connection, Transaction)
-            {
-                CommandType = CommandType.StoredProcedure
-            };
-
-            object groupNumber;
-
-            // Prepare parameters for sp_procedure_params_rowset:
-            // 1) procedure name - unquote user value
-            // 2) group number - parsed at the time we unquoted procedure name
-            // 3) procedure schema - unquote user value
-
-            paramsCmd.Parameters.Add(new SqlParameter("@procedure_name", SqlDbType.NVarChar, 255));
-            paramsCmd.Parameters[0].Value = UnquoteProcedureName(parsedSProc[3], out groupNumber); // ProcedureName is 4rd element in parsed array
-
-            if (null != groupNumber)
-            {
-                SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@group_number", SqlDbType.Int));
-                param.Value = groupNumber;
-            }
-
-            if (!string.IsNullOrEmpty(parsedSProc[2]))
-            { // SchemaName is 3rd element in parsed array
-                SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@procedure_schema", SqlDbType.NVarChar, 255));
-                param.Value = UnquoteProcedurePart(parsedSProc[2]);
-            }
-
-            SqlDataReader r = null;
-
-            List<SqlParameter> parameters = new List<SqlParameter>();
-            bool processFinallyBlock = true;
-
-            try
-            {
-                r = paramsCmd.ExecuteReader();
-
-                SqlParameter p = null;
-
-                while (r.Read())
-                {
-                    // each row corresponds to a parameter of the stored proc.  Fill in all the info
-                    p = new SqlParameter()
-                    {
-                        ParameterName = (string)r[colNames[(int)ProcParamsColIndex.ParameterName]]
-                    };
-
-                    // type
-                    if (useManagedDataType)
-                    {
-                        p.SqlDbType = (SqlDbType)(short)r[colNames[(int)ProcParamsColIndex.ManagedDataType]];
-
-                        // Yukon didn't have as accurate of information as we're getting for Katmai, so re-map a couple of
-                        //  types for backward compatability.
-                        switch (p.SqlDbType)
-                        {
-                            case SqlDbType.Image:
-                            case SqlDbType.Timestamp:
-                                p.SqlDbType = SqlDbType.VarBinary;
-                                break;
-
-                            case SqlDbType.NText:
-                                p.SqlDbType = SqlDbType.NVarChar;
-                                break;
-
-                            case SqlDbType.Text:
-                                p.SqlDbType = SqlDbType.VarChar;
-                                break;
-
-                            default:
-                                break;
-                        }
-                    }
-                    else
-                    {
-                        p.SqlDbType = MetaType.GetSqlDbTypeFromOleDbType((short)r[colNames[(int)ProcParamsColIndex.DataType]],
-                            ADP.IsNull(r[colNames[(int)ProcParamsColIndex.TypeName]]) ?
-                                string.Empty :
-                                (string)r[colNames[(int)ProcParamsColIndex.TypeName]]);
-                    }
-
-                    // size
-                    object a = r[colNames[(int)ProcParamsColIndex.CharacterMaximumLength]];
-                    if (a is int)
-                    {
-                        int size = (int)a;
-
-                        // Map MAX sizes correctly.  The Katmai server-side proc sends 0 for these instead of -1.
-                        //  Should be fixed on the Katmai side, but would likely hold up the RI, and is safer to fix here.
-                        //  If we can get the server-side fixed before shipping Katmai, we can remove this mapping.
-                        if (0 == size &&
-                                (p.SqlDbType == SqlDbType.NVarChar ||
-                                 p.SqlDbType == SqlDbType.VarBinary ||
-                                 p.SqlDbType == SqlDbType.VarChar))
-                        {
-                            size = -1;
-                        }
-                        p.Size = size;
-                    }
-
-                    // direction
-                    p.Direction = ParameterDirectionFromOleDbDirection((short)r[colNames[(int)ProcParamsColIndex.ParameterType]]);
-
-                    if (p.SqlDbType == SqlDbType.Decimal)
-                    {
-                        p.ScaleInternal = (byte)((short)r[colNames[(int)ProcParamsColIndex.NumericScale]] & 0xff);
-                        p.PrecisionInternal = (byte)((short)r[colNames[(int)ProcParamsColIndex.NumericPrecision]] & 0xff);
-                    }
-
-                    // type name for Udt
-                    if (SqlDbType.Udt == p.SqlDbType)
-                    {
-                        string udtTypeName;
-                        if (useManagedDataType)
-                        {
-                            udtTypeName = (string)r[colNames[(int)ProcParamsColIndex.TypeName]];
-                        }
-                        else
-                        {
-                            udtTypeName = (string)r[colNames[(int)ProcParamsColIndex.UdtTypeName]];
-                        }
-
-                        //read the type name
-                        p.UdtTypeName = r[colNames[(int)ProcParamsColIndex.TypeCatalogName]] + "." +
-                            r[colNames[(int)ProcParamsColIndex.TypeSchemaName]] + "." +
-                            udtTypeName;
-                    }
-
-                    // type name for Structured types (same as for Udt's except assign p.TypeName instead of p.UdtTypeName
-                    if (SqlDbType.Structured == p.SqlDbType)
-                    {
-                        Debug.Assert(_activeConnection.IsKatmaiOrNewer, "Invalid datatype token received from pre-katmai server");
-
-                        //read the type name
-                        p.TypeName = r[colNames[(int)ProcParamsColIndex.TypeCatalogName]] + "." +
-                            r[colNames[(int)ProcParamsColIndex.TypeSchemaName]] + "." +
-                            r[colNames[(int)ProcParamsColIndex.TypeName]];
-
-                        // the constructed type name above is incorrectly formatted, it should be a 2 part name not 3
-                        // for compatibility we can't change this because the bug has existed for a long time and been
-                        // worked around by users, so identify that it is present and catch it later in the execution
-                        // process once users can no longer interact with the parameter type name
-                        p.IsDerivedParameterTypeName = true;
-
-                    }
-
-                    // XmlSchema name for Xml types
-                    if (SqlDbType.Xml == p.SqlDbType)
-                    {
-                        object value;
-
-                        value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionCatalogName]];
-                        p.XmlSchemaCollectionDatabase = ADP.IsNull(value) ? string.Empty : (string)value;
-
-                        value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionSchemaName]];
-                        p.XmlSchemaCollectionOwningSchema = ADP.IsNull(value) ? string.Empty : (string)value;
-
-                        value = r[colNames[(int)ProcParamsColIndex.XmlSchemaCollectionName]];
-                        p.XmlSchemaCollectionName = ADP.IsNull(value) ? string.Empty : (string)value;
-                    }
-
-                    if (MetaType._IsVarTime(p.SqlDbType))
-                    {
-                        object value = r[colNames[(int)ProcParamsColIndex.DateTimeScale]];
-                        if (value is int)
-                        {
-                            p.ScaleInternal = (byte)(((int)value) & 0xff);
-                        }
-                    }
-
-                    parameters.Add(p);
-                }
-            }
-            catch (Exception e)
-            {
-                processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                throw;
-            }
-            finally
-            {
-                if (processFinallyBlock)
-                {
-                    r?.Close();
-
-                    // always unhook the user's connection
-                    paramsCmd.Connection = null;
-                }
-            }
-
-            if (parameters.Count == 0)
-            {
-                throw ADP.NoStoredProcedureExists(this.CommandText);
-            }
-
-            Parameters.Clear();
-
-            foreach (SqlParameter temp in parameters)
-            {
-                _parameters.Add(temp);
-            }
-        }
-
-        private ParameterDirection ParameterDirectionFromOleDbDirection(short oledbDirection)
-        {
-            Debug.Assert(oledbDirection >= 1 && oledbDirection <= 4, "invalid parameter direction from params_rowset!");
-
-            return oledbDirection switch
-            {
-                2 => ParameterDirection.InputOutput,
-                3 => ParameterDirection.Output,
-                4 => ParameterDirection.ReturnValue,
-                _ => ParameterDirection.Input,
-            };
-        }
-
-        // get cached metadata
-        internal _SqlMetaDataSet MetaData
-        {
-            get
-            {
-                return _cachedMetaData;
-            }
-        }
-
-        // Check to see if notificactions auto enlistment is turned on. Enlist if so.
-        private void CheckNotificationStateAndAutoEnlist()
-        {
-            // Auto-enlist not supported in Core
-
-            // If we have a notification with a dependency, setup the notification options at this time.
-
-            // If user passes options, then we will always have option data at the time the SqlDependency
-            // ctor is called.  But, if we are using default queue, then we do not have this data until
-            // Start().  Due to this, we always delay setting options until execute.
-
-            // There is a variance in order between Start(), SqlDependency(), and Execute.  This is the
-            // best way to solve that problem.
-            if (null != Notification)
-            {
-                if (_sqlDep != null)
-                {
-                    if (null == _sqlDep.Options)
-                    {
-                        // If null, SqlDependency was not created with options, so we need to obtain default options now.
-                        // GetDefaultOptions can and will throw under certain conditions.
-
-                        // In order to match to the appropriate start - we need 3 pieces of info:
-                        // 1) server 2) user identity (SQL Auth or Int Sec) 3) database
-
-                        SqlDependency.IdentityUserNamePair identityUserName = null;
-
-                        // Obtain identity from connection.
-                        SqlInternalConnectionTds internalConnection = _activeConnection.InnerConnection as SqlInternalConnectionTds;
-                        if (internalConnection.Identity != null)
-                        {
-                            identityUserName = new SqlDependency.IdentityUserNamePair(internalConnection.Identity, null);
-                        }
-                        else
-                        {
-                            identityUserName = new SqlDependency.IdentityUserNamePair(null, internalConnection.ConnectionOptions.UserID);
-                        }
-
-                        Notification.Options = SqlDependency.GetDefaultComposedOptions(_activeConnection.DataSource,
-                                                             InternalTdsConnection.ServerProvidedFailOverPartner,
-                                                             identityUserName, _activeConnection.Database);
-                    }
-
-                    // Set UserData on notifications, as well as adding to the appdomain dispatcher.  The value is
-                    // computed by an algorithm on the dependency - fixed and will always produce the same value
-                    // given identical commandtext + parameter values.
-                    Notification.UserData = _sqlDep.ComputeHashAndAddToDispatcher(this);
-                    // Maintain server list for SqlDependency.
-                    _sqlDep.AddToServerList(_activeConnection.DataSource);
-                }
-            }
-        }
-
-        // Tds-specific logic for ExecuteNonQuery run handling
-        private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, bool asyncWrite)
-        {
-            Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async");
-            bool processFinallyBlock = true;
-            try
-            {
-                Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout);
-
-                if (reconnectTask != null)
-                {
-                    long reconnectionStart = ADP.TimerCurrent();
-                    if (async)
-                    {
-                        TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
-                        _activeConnection.RegisterWaitingForReconnect(completion.Task);
-                        _reconnectionCompletionSource = completion;
-                        RunExecuteNonQueryTdsSetupReconnnectContinuation(methodName, async, timeout, asyncWrite, reconnectTask, reconnectionStart, completion);
-                        return completion.Task;
-                    }
-                    else
-                    {
-                        AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); });
-                        timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart);
-                    }
-                }
-
-                if (asyncWrite)
-                {
-                    _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag);
-                }
-
-                GetStateObject();
-
-                // we just send over the raw text with no annotation
-                // no parameters are sent over
-                // no data reader is returned
-                // use this overload for "batch SQL" tds token type
-                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");
-
-                NotifyDependency();
-                if (async)
-                {
-                    _activeConnection.GetOpenTdsConnection(methodName).IncrementAsyncCount();
-                }
-                else
-                {
-                    bool dataReady;
-                    Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-                    bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out dataReady);
-                    if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-                }
-            }
-            catch (Exception e)
-            {
-                processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                throw;
-            }
-            finally
-            {
-                if (processFinallyBlock && !async)
-                {
-                    // When executing Async, we need to keep the _stateObj alive...
-                    PutStateObject();
-                }
-            }
-            return null;
-        }
-
-        // This is in its own method to avoid always allocating the lambda in RunExecuteNonQueryTds, cannot use ContinueTaskWithState because of MarshalByRef and the CompareExchange
-        private void RunExecuteNonQueryTdsSetupReconnnectContinuation(string methodName, bool async, int timeout, bool asyncWrite, Task reconnectTask, long reconnectionStart, TaskCompletionSource<object> completion)
-        {
-            CancellationTokenSource timeoutCTS = new CancellationTokenSource();
-            AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token);
-            AsyncHelper.ContinueTask(reconnectTask, completion,
-                () =>
-                {
-                    if (completion.Task.IsCompleted)
-                    {
-                        return;
-                    }
-                    Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion);
-                    timeoutCTS.Cancel();
-                    Task subTask = RunExecuteNonQueryTds(methodName, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), asyncWrite);
-                    if (subTask == null)
-                    {
-                        completion.SetResult(null);
-                    }
-                    else
-                    {
-                        AsyncHelper.ContinueTaskWithState(subTask, completion,
-                            state: completion,
-                            onSuccess: (state) => ((TaskCompletionSource<object>)state).SetResult(null)
-                        );
-                    }
-                }
-            );
-        }
-
-        internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, [CallerMemberName] string method = "")
-        {
-            Task unused; // sync execution
-            SqlDataReader reader = RunExecuteReader(cmdBehavior, runBehavior, returnStream, completion: null, timeout: CommandTimeout, task: out unused, method: method);
-            Debug.Assert(unused == null, "returned task during synchronous execution");
-            return reader;
-        }
-
-        // task is created in case of pending asynchronous write, returned SqlDataReader should not be utilized until that task is complete
-        internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, TaskCompletionSource<object> completion, int timeout, out Task task, bool asyncWrite = false, [CallerMemberName] string method = "")
-        {
-            bool async = (null != completion);
-
-            task = null;
-
-            _rowsAffected = -1;
-
-            if (0 != (CommandBehavior.SingleRow & cmdBehavior))
-            {
-                // CommandBehavior.SingleRow implies CommandBehavior.SingleResult
-                cmdBehavior |= CommandBehavior.SingleResult;
-            }
-
-            // this function may throw for an invalid connection
-            // returns false for empty command text
-            ValidateCommand(async, method);
-
-            CheckNotificationStateAndAutoEnlist(); // Only call after validate - requires non null connection!
-
-            SqlStatistics statistics = Statistics;
-            if (null != statistics)
-            {
-                if ((!this.IsDirty && this.IsPrepared && !_hiddenPrepare)
-                    || (this.IsPrepared && _execType == EXECTYPE.PREPAREPENDING))
-                {
-                    statistics.SafeIncrement(ref statistics._preparedExecs);
-                }
-                else
-                {
-                    statistics.SafeIncrement(ref statistics._unpreparedExecs);
-                }
-            }
-
-
-            {
-                return RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, timeout, out task, asyncWrite && async);
-            }
-        }
-
-        private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async, int timeout, out Task task, bool asyncWrite, SqlDataReader ds = null)
-        {
-            Debug.Assert(!asyncWrite || async, "AsyncWrite should be always accompanied by Async");
-
-            if (ds == null && returnStream)
-            {
-                ds = new SqlDataReader(this, cmdBehavior);
-            }
-
-            Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout);
-
-            if (reconnectTask != null)
-            {
-                long reconnectionStart = ADP.TimerCurrent();
-                if (async)
-                {
-                    TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
-                    _activeConnection.RegisterWaitingForReconnect(completion.Task);
-                    _reconnectionCompletionSource = completion;
-                    RunExecuteReaderTdsSetupReconnectContinuation(cmdBehavior, runBehavior, returnStream, async, timeout, asyncWrite, ds, reconnectTask, reconnectionStart, completion);
-                    task = completion.Task;
-                    return ds;
-                }
-                else
-                {
-                    AsyncHelper.WaitForCompletion(reconnectTask, timeout, () => { throw SQL.CR_ReconnectTimeout(); });
-                    timeout = TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart);
-                }
-            }
-
-            // make sure we have good parameter information
-            // prepare the command
-            // execute
-            Debug.Assert(null != _activeConnection.Parser, "TdsParser class should not be null in Command.Execute!");
-
-            bool inSchema = (0 != (cmdBehavior & CommandBehavior.SchemaOnly));
-
-            // create a new RPC
-            _SqlRPC rpc = null;
-
-            task = null;
-
-            string optionSettings = null;
-            bool processFinallyBlock = true;
-            bool decrementAsyncCountOnFailure = false;
-
-            if (async)
-            {
-                _activeConnection.GetOpenTdsConnection().IncrementAsyncCount();
-                decrementAsyncCountOnFailure = true;
-            }
-
-            try
-            {
-                if (asyncWrite)
-                {
-                    _activeConnection.AddWeakReference(this, SqlReferenceCollection.CommandTag);
-                }
-
-                GetStateObject();
-                Task writeTask = null;
-
-                if (BatchRPCMode)
-                {
-                    Debug.Assert(inSchema == false, "Batch RPC does not support schema only command beahvior");
-                    Debug.Assert(!IsPrepared, "Batch RPC should not be prepared!");
-                    Debug.Assert(!IsDirty, "Batch RPC should not be marked as dirty!");
-                    Debug.Assert(_SqlRPCBatchArray != null, "RunExecuteReader rpc array not provided");
-                    writeTask = _stateObj.Parser.TdsExecuteRPC(_SqlRPCBatchArray, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite);
-                }
-                else if ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters)))
-                {
-                    // Send over SQL Batch command if we are not a stored proc and have no parameters
-                    Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!");
-                    string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior);
-                    writeTask = _stateObj.Parser.TdsExecuteSQLBatch(text, timeout, this.Notification, _stateObj, sync: !asyncWrite);
-                }
-                else if (System.Data.CommandType.Text == this.CommandType)
-                {
-                    if (this.IsDirty)
-                    {
-                        Debug.Assert(_cachedMetaData == null || !_dirty, "dirty query should not have cached metadata!"); // can have cached metadata if dirty because of parameters
-                        //
-                        // someone changed the command text or the parameter schema so we must unprepare the command
-                        //
-                        // remember that IsDirty includes test for IsPrepared!
-                        if (_execType == EXECTYPE.PREPARED)
-                        {
-                            _hiddenPrepare = true;
-                        }
-                        Unprepare();
-                        IsDirty = false;
-                    }
-
-                    if (_execType == EXECTYPE.PREPARED)
-                    {
-                        Debug.Assert(this.IsPrepared && ((int)_prepareHandle != -1), "invalid attempt to call sp_execute without a handle!");
-                        rpc = BuildExecute(inSchema);
-                    }
-                    else if (_execType == EXECTYPE.PREPAREPENDING)
-                    {
-                        rpc = BuildPrepExec(cmdBehavior);
-                        // next time through, only do an exec
-                        _execType = EXECTYPE.PREPARED;
-                        _preparedConnectionCloseCount = _activeConnection.CloseCount;
-                        _preparedConnectionReconnectCount = _activeConnection.ReconnectCount;
-                        // mark ourselves as preparing the command
-                        _inPrepare = true;
-                    }
-                    else
-                    {
-                        Debug.Assert(_execType == EXECTYPE.UNPREPARED, "Invalid execType!");
-                        BuildExecuteSql(cmdBehavior, null, _parameters, ref rpc);
-                    }
-
-                    // if shiloh, then set NOMETADATA_UNLESSCHANGED flag
-                    rpc.options = TdsEnums.RPC_NOMETADATA;
-
-                    Debug.Assert(_rpcArrayOf1[0] == rpc);
-                    writeTask = _stateObj.Parser.TdsExecuteRPC(_rpcArrayOf1, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite);
-                }
-                else
-                {
-                    Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "unknown command type!");
-
-                    BuildRPC(inSchema, _parameters, ref rpc);
-
-                    // if we need to augment the command because a user has changed the command behavior (e.g. FillSchema)
-                    // then batch sql them over.  This is inefficient (3 round trips) but the only way we can get metadata only from
-                    // a stored proc
-                    optionSettings = GetSetOptionsString(cmdBehavior);
-                    // turn set options ON
-                    if (null != optionSettings)
-                    {
-                        Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(optionSettings, timeout, this.Notification, _stateObj, sync: true);
-                        Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
-                        Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-                        bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, null, null, _stateObj, out bool dataReady);
-                        if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-                        // and turn OFF when the ds exhausts the stream on Close()
-                        optionSettings = GetResetOptionsString(cmdBehavior);
-                    }
-
-                    // execute sp
-                    Debug.Assert(_rpcArrayOf1[0] == rpc);
-                    writeTask = _stateObj.Parser.TdsExecuteRPC(_rpcArrayOf1, timeout, inSchema, this.Notification, _stateObj, CommandType.StoredProcedure == CommandType, sync: !asyncWrite);
-                }
-
-                Debug.Assert(writeTask == null || async, "Returned task in sync mode");
-
-                if (async)
-                {
-                    decrementAsyncCountOnFailure = false;
-                    if (writeTask != null)
-                    {
-                        task = RunExecuteReaderTdsSetupContinuation(runBehavior, ds, optionSettings, writeTask);
-                    }
-                    else
-                    {
-                        cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
-                    }
-                }
-                else
-                {
-                    // Always execute - even if no reader!
-                    FinishExecuteReader(ds, runBehavior, optionSettings);
-                }
-            }
-            catch (Exception e)
-            {
-                processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                if (decrementAsyncCountOnFailure)
-                {
-                    SqlInternalConnectionTds innerConnectionTds = (_activeConnection.InnerConnection as SqlInternalConnectionTds);
-                    if (null != innerConnectionTds)
-                    { // it may be closed
-                        innerConnectionTds.DecrementAsyncCount();
-                    }
-                }
-                throw;
-            }
-            finally
-            {
-                if (processFinallyBlock && !async)
-                {
-                    // When executing async, we need to keep the _stateObj alive...
-                    PutStateObject();
-                }
-            }
-
-            Debug.Assert(async || null == _stateObj, "non-null state object in RunExecuteReader");
-            return ds;
-        }
-
-        // This is in its own method to avoid always allocating the lambda in RunExecuteReaderTds
-        private Task RunExecuteReaderTdsSetupContinuation(RunBehavior runBehavior, SqlDataReader ds, string optionSettings, Task writeTask)
-        {
-            Task task = AsyncHelper.CreateContinuationTask(writeTask,
-                onSuccess: () =>
-                {
-                    _activeConnection.GetOpenTdsConnection(); // it will throw if connection is closed
-                    cachedAsyncState.SetAsyncReaderState(ds, runBehavior, optionSettings);
-                },
-                onFailure: (exc) =>
-                {
-                    _activeConnection.GetOpenTdsConnection().DecrementAsyncCount();
-                }
-            );
-            return task;
-        }
-
-        // This is in its own method to avoid always allocating the lambda in RunExecuteReaderTds
-        private void RunExecuteReaderTdsSetupReconnectContinuation(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, bool async, int timeout, bool asyncWrite, SqlDataReader ds, Task reconnectTask, long reconnectionStart, TaskCompletionSource<object> completion)
-        {
-            CancellationTokenSource timeoutCTS = new CancellationTokenSource();
-            AsyncHelper.SetTimeoutException(completion, timeout, SQL.CR_ReconnectTimeout, timeoutCTS.Token);
-            AsyncHelper.ContinueTask(reconnectTask, completion,
-                () =>
-                {
-                    if (completion.Task.IsCompleted)
-                    {
-                        return;
-                    }
-                    Interlocked.CompareExchange(ref _reconnectionCompletionSource, null, completion);
-                    timeoutCTS.Cancel();
-                    Task subTask;
-                    RunExecuteReaderTds(cmdBehavior, runBehavior, returnStream, async, TdsParserStaticMethods.GetRemainingTimeout(timeout, reconnectionStart), out subTask, asyncWrite, ds);
-                    if (subTask == null)
-                    {
-                        completion.SetResult(null);
-                    }
-                    else
-                    {
-                        AsyncHelper.ContinueTaskWithState(subTask, completion,
-                            state: completion,
-                            onSuccess: (state) => ((TaskCompletionSource<object>)state).SetResult(null)
-                        );
-                    }
-                }
-            );
-        }
-
-        private SqlDataReader CompleteAsyncExecuteReader()
-        {
-            SqlDataReader ds = cachedAsyncState.CachedAsyncReader; // should not be null
-            bool processFinallyBlock = true;
-            try
-            {
-                FinishExecuteReader(ds, cachedAsyncState.CachedRunBehavior, cachedAsyncState.CachedSetOptions);
-            }
-            catch (Exception e)
-            {
-                processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                throw;
-            }
-            finally
-            {
-                if (processFinallyBlock)
-                {
-                    cachedAsyncState.ResetAsyncState();
-                    PutStateObject();
-                }
-            }
-
-            return ds;
-        }
-
-        private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, string resetOptionsString)
-        {
-            // always wrap with a try { FinishExecuteReader(...) } finally { PutStateObject(); }
-
-            NotifyDependency();
-
-            if (runBehavior == RunBehavior.UntilDone)
-            {
-                try
-                {
-                    bool dataReady;
-                    Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-                    bool result = _stateObj.Parser.TryRun(RunBehavior.UntilDone, this, ds, null, _stateObj, out dataReady);
-                    if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-                }
-                catch (Exception e)
-                {
-                    if (ADP.IsCatchableExceptionType(e))
-                    {
-                        if (_inPrepare)
-                        {
-                            // The flag is expected to be reset by OnReturnValue.  We should receive
-                            // the handle unless command execution failed.  If fail, move back to pending
-                            // state.
-                            _inPrepare = false;                  // reset the flag
-                            IsDirty = true;                      // mark command as dirty so it will be prepared next time we're coming through
-                            _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending
-                        }
-
-                        if (null != ds)
-                        {
-                            try
-                            {
-                                ds.Close();
-                            }
-                            catch (Exception exClose)
-                            {
-                                Debug.WriteLine("Received this exception from SqlDataReader.Close() while in another catch block: " + exClose.ToString());
-                            }
-                        }
-                    }
-                    throw;
-                }
-            }
-
-            // bind the parser to the reader if we get this far
-            if (ds != null)
-            {
-                ds.Bind(_stateObj);
-                _stateObj = null;   // the reader now owns this...
-                ds.ResetOptionsString = resetOptionsString;
-                // bind this reader to this connection now
-                _activeConnection.AddWeakReference(ds, SqlReferenceCollection.DataReaderTag);
-
-                // force this command to start reading data off the wire.
-                // this will cause an error to be reported at Execute() time instead of Read() time
-                // if the command is not set.
-                try
-                {
-                    _cachedMetaData = ds.MetaData;
-                    ds.IsInitialized = true;
-                }
-                catch (Exception e)
-                {
-                    if (ADP.IsCatchableExceptionType(e))
-                    {
-                        if (_inPrepare)
-                        {
-                            // The flag is expected to be reset by OnReturnValue.  We should receive
-                            // the handle unless command execution failed.  If fail, move back to pending
-                            // state.
-                            _inPrepare = false;                  // reset the flag
-                            IsDirty = true;                      // mark command as dirty so it will be prepared next time we're coming through
-                            _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending
-                        }
-
-                        try
-                        {
-                            ds.Close();
-                        }
-                        catch (Exception exClose)
-                        {
-                            Debug.WriteLine("Received this exception from SqlDataReader.Close() while in another catch block: " + exClose.ToString());
-                        }
-                    }
-
-                    throw;
-                }
-            }
-        }
-
-
-        private void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask)
-        {
-            SqlConnection connection = _activeConnection;
-            if (connection == null)
-            {
-                // No connection
-                throw ADP.ClosedConnectionError();
-            }
-
-            connection.RegisterForConnectionCloseNotification<T>(ref outerTask, this, SqlReferenceCollection.CommandTag);
-        }
-
-        // validates that a command has commandText and a non-busy open connection
-        // throws exception for error case, returns false if the commandText is empty
-        private void ValidateCommand(bool async, [CallerMemberName] string method = "")
-        {
-            if (null == _activeConnection)
-            {
-                throw ADP.ConnectionRequired(method);
-            }
-
-            // Ensure that the connection is open and that the Parser is in the correct state
-            SqlInternalConnectionTds tdsConnection = _activeConnection.InnerConnection as SqlInternalConnectionTds;
-            if (tdsConnection != null)
-            {
-                var parser = tdsConnection.Parser;
-                if ((parser == null) || (parser.State == TdsParserState.Closed))
-                {
-                    throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
-                }
-                else if (parser.State != TdsParserState.OpenLoggedIn)
-                {
-                    throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
-                }
-            }
-            else if (_activeConnection.State == ConnectionState.Closed)
-            {
-                throw ADP.OpenConnectionRequired(method, ConnectionState.Closed);
-            }
-            else if (_activeConnection.State == ConnectionState.Broken)
-            {
-                throw ADP.OpenConnectionRequired(method, ConnectionState.Broken);
-            }
-
-            ValidateAsyncCommand();
-
-            // close any non MARS dead readers, if applicable, and then throw if still busy.
-            // Throw if we have a live reader on this command
-            _activeConnection.ValidateConnectionForExecute(method, this);
-            // Check to see if the currently set transaction has completed.  If so,
-            // null out our local reference.
-            if (null != _transaction && _transaction.Connection == null)
-                _transaction = null;
-
-            // throw if the connection is in a transaction but there is no
-            // locally assigned transaction object
-            if (_activeConnection.HasLocalTransactionFromAPI && (null == _transaction))
-                throw ADP.TransactionRequired(method);
-
-            // if we have a transaction, check to ensure that the active
-            // connection property matches the connection associated with
-            // the transaction
-            if (null != _transaction && _activeConnection != _transaction.Connection)
-                throw ADP.TransactionConnectionMismatch();
-
-            if (string.IsNullOrEmpty(this.CommandText))
-                throw ADP.CommandTextRequired(method);
-        }
-
-        private void ValidateAsyncCommand()
-        {
-            if (_cachedAsyncState != null && _cachedAsyncState.PendingAsyncOperation)
-            { // Enforce only one pending async execute at a time.
-                if (_cachedAsyncState.IsActiveConnectionValid(_activeConnection))
-                {
-                    throw SQL.PendingBeginXXXExists();
-                }
-                else
-                {
-                    _stateObj = null; // Session was re-claimed by session pool upon connection close.
-                    _cachedAsyncState.ResetAsyncState();
-                }
-            }
-        }
-
-        private void GetStateObject(TdsParser parser = null)
-        {
-            Debug.Assert(null == _stateObj, "StateObject not null on GetStateObject");
-            Debug.Assert(null != _activeConnection, "no active connection?");
-
-            if (_pendingCancel)
-            {
-                _pendingCancel = false; // Not really needed, but we'll reset anyways.
-
-                // If a pendingCancel exists on the object, we must have had a Cancel() call
-                // between the point that we entered an Execute* API and the point in Execute* that
-                // we proceeded to call this function and obtain a stateObject.  In that case,
-                // we now throw a cancelled error.
-                throw SQL.OperationCancelled();
-            }
-
-            if (parser == null)
-            {
-                parser = _activeConnection.Parser;
-                if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed))
-                {
-                    // Connection's parser is null as well, therefore we must be closed
-                    throw ADP.ClosedConnectionError();
-                }
-            }
-
-            TdsParserStateObject stateObj = parser.GetSession(this);
-            stateObj.StartSession(this);
-
-            _stateObj = stateObj;
-
-            if (_pendingCancel)
-            {
-                _pendingCancel = false; // Not really needed, but we'll reset anyways.
-
-                // If a pendingCancel exists on the object, we must have had a Cancel() call
-                // between the point that we entered this function and the point where we obtained
-                // and actually assigned the stateObject to the local member.  It is possible
-                // that the flag is set as well as a call to stateObj.Cancel - though that would
-                // be a no-op.  So - throw.
-                throw SQL.OperationCancelled();
-            }
-        }
-
-        private void ReliablePutStateObject()
-        {
-            PutStateObject();
-        }
-
-        private void PutStateObject()
-        {
-            TdsParserStateObject stateObj = _stateObj;
-            _stateObj = null;
-
-            if (null != stateObj)
-            {
-                stateObj.CloseSession();
-            }
-        }
-        internal void OnDoneProc()
-        { // called per rpc batch complete
-            if (BatchRPCMode)
-            {
-                // track the records affected for the just completed rpc batch
-                // _rowsAffected is cumulative for ExecuteNonQuery across all rpc batches
-                _SqlRPCBatchArray[_currentlyExecutingBatch].cumulativeRecordsAffected = _rowsAffected;
-
-                _SqlRPCBatchArray[_currentlyExecutingBatch].recordsAffected =
-                    (((0 < _currentlyExecutingBatch) && (0 <= _rowsAffected))
-                        ? (_rowsAffected - Math.Max(_SqlRPCBatchArray[_currentlyExecutingBatch - 1].cumulativeRecordsAffected, 0))
-                        : _rowsAffected);
-
-                // track the error collection (not available from TdsParser after ExecuteNonQuery)
-                // and the which errors are associated with the just completed rpc batch
-                _SqlRPCBatchArray[_currentlyExecutingBatch].errorsIndexStart =
-                    ((0 < _currentlyExecutingBatch)
-                        ? _SqlRPCBatchArray[_currentlyExecutingBatch - 1].errorsIndexEnd
-                        : 0);
-                _SqlRPCBatchArray[_currentlyExecutingBatch].errorsIndexEnd = _stateObj.ErrorCount;
-                _SqlRPCBatchArray[_currentlyExecutingBatch].errors = _stateObj._errors;
-
-                // track the warning collection (not available from TdsParser after ExecuteNonQuery)
-                // and the which warnings are associated with the just completed rpc batch
-                _SqlRPCBatchArray[_currentlyExecutingBatch].warningsIndexStart =
-                    ((0 < _currentlyExecutingBatch)
-                        ? _SqlRPCBatchArray[_currentlyExecutingBatch - 1].warningsIndexEnd
-                        : 0);
-                _SqlRPCBatchArray[_currentlyExecutingBatch].warningsIndexEnd = _stateObj.WarningCount;
-                _SqlRPCBatchArray[_currentlyExecutingBatch].warnings = _stateObj._warnings;
-
-                _currentlyExecutingBatch++;
-                Debug.Assert(_parameterCollectionList.Count >= _currentlyExecutingBatch, "OnDoneProc: Too many DONEPROC events");
-            }
-        }
-        internal void OnReturnStatus(int status)
-        {
-            if (_inPrepare)
-                return;
-
-            SqlParameterCollection parameters = _parameters;
-            if (BatchRPCMode)
-            {
-                if (_parameterCollectionList.Count > _currentlyExecutingBatch)
-                {
-                    parameters = _parameterCollectionList[_currentlyExecutingBatch];
-                }
-                else
-                {
-                    Debug.Fail("OnReturnStatus: SqlCommand got too many DONEPROC events");
-                    parameters = null;
-                }
-            }
-            // see if a return value is bound
-            int count = GetParameterCount(parameters);
-            for (int i = 0; i < count; i++)
-            {
-                SqlParameter parameter = parameters[i];
-                if (parameter.Direction == ParameterDirection.ReturnValue)
-                {
-                    object v = parameter.Value;
-
-                    // if the user bound a sqlint32 (the only valid one for status, use it)
-                    if ((null != v) && (v.GetType() == typeof(SqlInt32)))
-                    {
-                        parameter.Value = new SqlInt32(status); // value type
-                    }
-                    else
-                    {
-                        parameter.Value = status;
-
-                    }
-
-                    break;
-                }
-            }
-        }
-
-        //
-        // Move the return value to the corresponding output parameter.
-        // Return parameters are sent in the order in which they were defined in the procedure.
-        // If named, match the parameter name, otherwise fill in based on ordinal position.
-        // If the parameter is not bound, then ignore the return value.
-        //
-        internal void OnReturnValue(SqlReturnValue rec, TdsParserStateObject stateObj)
-        {
-            if (_inPrepare)
-            {
-                if (!rec.value.IsNull)
-                {
-                    _prepareHandle = rec.value.Int32;
-                }
-                _inPrepare = false;
-                return;
-            }
-
-            SqlParameterCollection parameters = GetCurrentParameterCollection();
-            int count = GetParameterCount(parameters);
-
-            SqlParameter thisParam = GetParameterForOutputValueExtraction(parameters, rec.parameter, count);
-
-            if (null != thisParam)
-            {
-                // copy over data
-
-                // if the value user has supplied a SqlType class, then just copy over the SqlType, otherwise convert
-                // to the com type
-                object val = thisParam.Value;
-
-                //set the UDT value as typed object rather than bytes
-                if (SqlDbType.Udt == thisParam.SqlDbType)
-                {
-                    object data = null;
-                    try
-                    {
-                        Connection.CheckGetExtendedUDTInfo(rec, true);
-
-                        //extract the byte array from the param value
-                        if (rec.value.IsNull)
-                        {
-                            data = DBNull.Value;
-                        }
-                        else
-                        {
-                            data = rec.value.ByteArray; //should work for both sql and non-sql values
-                        }
-
-                        //call the connection to instantiate the UDT object
-                        thisParam.Value = Connection.GetUdtValue(data, rec, false);
-                    }
-                    catch (FileNotFoundException e)
-                    {
-                        // Assign Assembly.Load failure in case where assembly not on client.
-                        // This allows execution to complete and failure on SqlParameter.Value.
-                        thisParam.SetUdtLoadError(e);
-                    }
-                    catch (FileLoadException e)
-                    {
-                        // Assign Assembly.Load failure in case where assembly cannot be loaded on client.
-                        // This allows execution to complete and failure on SqlParameter.Value.
-                        thisParam.SetUdtLoadError(e);
-                    }
-
-                    return;
-                }
-                else
-                {
-                    thisParam.SetSqlBuffer(rec.value);
-                }
-
-                MetaType mt = MetaType.GetMetaTypeFromSqlDbType(rec.type, false);
-
-                if (rec.type == SqlDbType.Decimal)
-                {
-                    thisParam.ScaleInternal = rec.scale;
-                    thisParam.PrecisionInternal = rec.precision;
-                }
-                else if (mt.IsVarTime)
-                {
-                    thisParam.ScaleInternal = rec.scale;
-                }
-                else if (rec.type == SqlDbType.Xml)
-                {
-                    SqlCachedBuffer cachedBuffer = (thisParam.Value as SqlCachedBuffer);
-                    if (null != cachedBuffer)
-                    {
-                        thisParam.Value = cachedBuffer.ToString();
-                    }
-                }
-
-                if (rec.collation != null)
-                {
-                    Debug.Assert(mt.IsCharType, "Invalid collation structure for non-char type");
-                    thisParam.Collation = rec.collation;
-                }
-            }
-
-            return;
-        }
-
-        private SqlParameterCollection GetCurrentParameterCollection()
-        {
-            if (BatchRPCMode)
-            {
-                if (_parameterCollectionList.Count > _currentlyExecutingBatch)
-                {
-                    return _parameterCollectionList[_currentlyExecutingBatch];
-                }
-                else
-                {
-                    Debug.Fail("OnReturnValue: SqlCommand got too many DONEPROC events");
-                    return null;
-                }
-            }
-            else
-            {
-                return _parameters;
-            }
-        }
-
-        private SqlParameter GetParameterForOutputValueExtraction(SqlParameterCollection parameters,
-                        string paramName, int paramCount)
-        {
-            SqlParameter thisParam = null;
-            bool foundParam = false;
-
-            if (null == paramName)
-            {
-                // rec.parameter should only be null for a return value from a function
-                for (int i = 0; i < paramCount; i++)
-                {
-                    thisParam = parameters[i];
-                    // searching for ReturnValue
-                    if (thisParam.Direction == ParameterDirection.ReturnValue)
-                    {
-                        foundParam = true;
-                        break; // found it
-                    }
-                }
-            }
-            else
-            {
-                for (int i = 0; i < paramCount; i++)
-                {
-                    thisParam = parameters[i];
-                    // searching for Output or InputOutput or ReturnValue with matching name
-                    if (thisParam.Direction != ParameterDirection.Input && thisParam.Direction != ParameterDirection.ReturnValue && paramName == thisParam.ParameterNameFixed)
-                    {
-                        foundParam = true;
-                        break; // found it
-                    }
-                }
-            }
-            if (foundParam)
-                return thisParam;
-            else
-                return null;
-        }
-
-        private void GetRPCObject(int systemParamCount, int userParamCount, ref _SqlRPC rpc)
-        {
-            // Designed to minimize necessary allocations
-            if (rpc == null)
-            {
-                if (_rpcArrayOf1 == null)
-                {
-                    _rpcArrayOf1 = new _SqlRPC[1];
-                    _rpcArrayOf1[0] = new _SqlRPC();
-                }
-                rpc = _rpcArrayOf1[0];
-            }
-
-            rpc.options = 0;
-            rpc.systemParamCount = systemParamCount;
-
-            int currentCount = rpc.systemParams?.Length ?? 0;
-            // Make sure there is enough space in the parameters and paramoptions arrays
-            if (currentCount < systemParamCount)
-            {
-                Array.Resize(ref rpc.systemParams, systemParamCount);
-                Array.Resize(ref rpc.systemParamOptions, systemParamCount);
-                for (int index = currentCount; index < systemParamCount; index++)
-                {
-                    rpc.systemParams[index] = new SqlParameter();
-                }
-            }
-            for (int ii = 0; ii < systemParamCount; ii++)
-            {
-                rpc.systemParamOptions[ii] = 0;
-            }
-            if ((rpc.userParamMap?.Length ?? 0) < userParamCount)
-            {
-                Array.Resize(ref rpc.userParamMap, userParamCount);
-            }
-        }
-
-        private void SetUpRPCParameters(_SqlRPC rpc, bool inSchema, SqlParameterCollection parameters)
-        {
-            int paramCount = GetParameterCount(parameters);
-            int userParamCount = 0;
-
-            for (int index = 0; index < paramCount; index++)
-            {
-                SqlParameter parameter = parameters[index];
-                parameter.Validate(index, CommandType.StoredProcedure == CommandType);
-
-                // func will change type to that with a 4 byte length if the type has a two
-                // byte length and a parameter length > than that expressible in 2 bytes
-                if ((!parameter.ValidateTypeLengths().IsPlp) && (parameter.Direction != ParameterDirection.Output))
-                {
-                    parameter.FixStreamDataForNonPLP();
-                }
-
-                if (ShouldSendParameter(parameter))
-                {
-                    byte options = 0;
-
-                    // set output bit
-                    if (parameter.Direction == ParameterDirection.InputOutput ||
-                        parameter.Direction == ParameterDirection.Output)
-                        options = TdsEnums.RPC_PARAM_BYREF;
-
-                    // set default value bit
-                    if (parameter.Direction != ParameterDirection.Output)
-                    {
-                        // detect incorrectly derived type names unchanged by the caller and fix them
-                        if (parameter.IsDerivedParameterTypeName)
-                        {
-                            string[] parts = MultipartIdentifier.ParseMultipartIdentifier(parameter.TypeName, "[\"", "]\"", SR.SQL_TDSParserTableName, false);
-                            if (parts != null && parts.Length == 4) // will always return int[4] right justified
-                            {
-                                if (
-                                    parts[3] != null && // name must not be null
-                                    parts[2] != null && // schema must not be null
-                                    parts[1] != null // server should not be null or we don't need to remove it
-                                )
-                                {
-                                    parameter.TypeName = QuoteIdentifier(parts.AsSpan(2, 2));
-                                }
-                            }
-                        }
-
-                        // remember that null == Convert.IsEmpty, DBNull.Value is a database null!
-
-                        // Don't assume a default value exists for parameters in the case when
-                        // the user is simply requesting schema.
-                        // TVPs use DEFAULT and do not allow NULL, even for schema only.
-                        if (null == parameter.Value && (!inSchema || SqlDbType.Structured == parameter.SqlDbType))
-                        {
-                            options |= TdsEnums.RPC_PARAM_DEFAULT;
-                        }
-                    }
-
-                    rpc.userParamMap[userParamCount] = ((((long)options) << 32) | (long)index);
-                    userParamCount += 1;
-                    // Must set parameter option bit for LOB_COOKIE if unfilled LazyMat blob
-
-                }
-            }
-            rpc.userParamCount = userParamCount;
-            rpc.userParams = parameters;
-        }
-
-        private _SqlRPC BuildPrepExec(CommandBehavior behavior)
-        {
-            Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid use of sp_prepexec for stored proc invocation!");
-            SqlParameter sqlParam;
-            const int systemParameterCount = 3;
-
-            int userParameterCount = CountSendableParameters(_parameters);
-
-            _SqlRPC rpc = null;
-            GetRPCObject(systemParameterCount, userParameterCount, ref rpc);
-
-            rpc.ProcID = TdsEnums.RPC_PROCID_PREPEXEC;
-            rpc.rpcName = TdsEnums.SP_PREPEXEC;
-
-            //@handle
-            sqlParam = rpc.systemParams[0];
-            sqlParam.SqlDbType = SqlDbType.Int;
-            sqlParam.Value = _prepareHandle;
-            sqlParam.Size = 4;
-            sqlParam.Direction = ParameterDirection.InputOutput;
-            rpc.systemParamOptions[0] = TdsEnums.RPC_PARAM_BYREF;
-
-            //@batch_params
-            string paramList = BuildParamList(_stateObj.Parser, _parameters);
-            sqlParam = rpc.systemParams[1];
-            sqlParam.SqlDbType = ((paramList.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText;
-            sqlParam.Size = paramList.Length;
-            sqlParam.Value = paramList;
-
-            //@batch_text
-            string text = GetCommandText(behavior);
-            sqlParam = rpc.systemParams[2];
-            sqlParam.SqlDbType = ((text.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText;
-            sqlParam.Size = text.Length;
-            sqlParam.Value = text;
-
-            SetUpRPCParameters(rpc, false, _parameters);
-
-            return rpc;
-        }
-
-
-        //
-        // returns true if the parameter is not a return value
-        // and it's value is not DBNull (for a nullable parameter)
-        //
-        private static bool ShouldSendParameter(SqlParameter p)
-        {
-            switch (p.Direction)
-            {
-                case ParameterDirection.ReturnValue:
-                    // return value parameters are never sent
-                    return false;
-                case ParameterDirection.Output:
-                case ParameterDirection.InputOutput:
-                case ParameterDirection.Input:
-                    // InputOutput/Output parameters are aways sent
-                    return true;
-                default:
-                    Debug.Fail("Invalid ParameterDirection!");
-                    return false;
-            }
-        }
-
-        private int CountSendableParameters(SqlParameterCollection parameters)
-        {
-            int cParams = 0;
-
-            if (parameters != null)
-            {
-                int count = parameters.Count;
-                for (int i = 0; i < count; i++)
-                {
-                    if (ShouldSendParameter(parameters[i]))
-                        cParams++;
-                }
-            }
-            return cParams;
-        }
-
-        // Returns total number of parameters
-        private int GetParameterCount(SqlParameterCollection parameters)
-        {
-            return ((null != parameters) ? parameters.Count : 0);
-        }
-
-        //
-        // build the RPC record header for this stored proc and add parameters
-        //
-        private void BuildRPC(bool inSchema, SqlParameterCollection parameters, ref _SqlRPC rpc)
-        {
-            Debug.Assert(this.CommandType == System.Data.CommandType.StoredProcedure, "Command must be a stored proc to execute an RPC");
-            int userParameterCount = CountSendableParameters(parameters);
-            GetRPCObject(0, userParameterCount, ref rpc);
-
-            rpc.ProcID = 0;
-            rpc.rpcName = this.CommandText; // just get the raw command text
-
-            SetUpRPCParameters(rpc, inSchema, parameters);
-        }
-
-        //
-        // build the RPC record header for sp_unprepare
-        //
-        // prototype for sp_unprepare is:
-        // sp_unprepare(@handle)
-
-        // build the RPC record header for sp_execute
-        //
-        // prototype for sp_execute is:
-        // sp_execute(@handle int,param1value,param2value...)
-
-        private _SqlRPC BuildExecute(bool inSchema)
-        {
-            Debug.Assert((int)_prepareHandle != -1, "Invalid call to sp_execute without a valid handle!");
-            const int systemParameterCount = 1;
-
-            int userParameterCount = CountSendableParameters(_parameters);
-
-            _SqlRPC rpc = null;
-            GetRPCObject(systemParameterCount, userParameterCount, ref rpc);
-
-            rpc.ProcID = TdsEnums.RPC_PROCID_EXECUTE;
-            rpc.rpcName = TdsEnums.SP_EXECUTE;
-
-            //@handle
-            SqlParameter sqlParam = rpc.systemParams[0];
-            sqlParam.SqlDbType = SqlDbType.Int;
-            sqlParam.Value = _prepareHandle;
-            sqlParam.Direction = ParameterDirection.Input;
-
-            SetUpRPCParameters(rpc, inSchema, _parameters);
-            return rpc;
-        }
-
-        //
-        // build the RPC record header for sp_executesql and add the parameters
-        //
-        // prototype for sp_executesql is:
-        // sp_executesql(@batch_text nvarchar(4000),@batch_params nvarchar(4000), param1,.. paramN)
-        private void BuildExecuteSql(CommandBehavior behavior, string commandText, SqlParameterCollection parameters, ref _SqlRPC rpc)
-        {
-
-            Debug.Assert((int)_prepareHandle == -1, "This command has an existing handle, use sp_execute!");
-            Debug.Assert(CommandType.Text == this.CommandType, "invalid use of sp_executesql for stored proc invocation!");
-            int systemParamCount;
-            SqlParameter sqlParam;
-
-            int userParamCount = CountSendableParameters(parameters);
-            if (userParamCount > 0)
-            {
-                systemParamCount = 2;
-            }
-            else
-            {
-                systemParamCount = 1;
-            }
-
-            GetRPCObject(systemParamCount, userParamCount, ref rpc);
-
-            rpc.ProcID = TdsEnums.RPC_PROCID_EXECUTESQL;
-            rpc.rpcName = TdsEnums.SP_EXECUTESQL;
-
-            // @sql
-            if (commandText == null)
-            {
-                commandText = GetCommandText(behavior);
-            }
-            sqlParam = rpc.systemParams[0];
-            sqlParam.SqlDbType = ((commandText.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText;
-            sqlParam.Size = commandText.Length;
-            sqlParam.Value = commandText;
-            sqlParam.Direction = ParameterDirection.Input;
-
-            if (userParamCount > 0)
-            {
-                string paramList = BuildParamList(_stateObj.Parser, BatchRPCMode ? parameters : _parameters);
-                sqlParam = rpc.systemParams[1];
-                sqlParam.SqlDbType = ((paramList.Length << 1) <= TdsEnums.TYPE_SIZE_LIMIT) ? SqlDbType.NVarChar : SqlDbType.NText;
-                sqlParam.Size = paramList.Length;
-                sqlParam.Value = paramList;
-
-                bool inSchema = (0 != (behavior & CommandBehavior.SchemaOnly));
-                SetUpRPCParameters(rpc, inSchema, parameters);
-            }
-        }
-
-        // paramList parameter for sp_executesql, sp_prepare, and sp_prepexec
-        internal string BuildParamList(TdsParser parser, SqlParameterCollection parameters)
-        {
-            StringBuilder paramList = new StringBuilder();
-            bool fAddSeperator = false;
-
-            int count = 0;
-
-            count = parameters.Count;
-            for (int i = 0; i < count; i++)
-            {
-                SqlParameter sqlParam = parameters[i];
-                sqlParam.Validate(i, CommandType.StoredProcedure == CommandType);
-                // skip ReturnValue parameters; we never send them to the server
-                if (!ShouldSendParameter(sqlParam))
-                    continue;
-
-                // add our separator for the ith parameter
-                if (fAddSeperator)
-                    paramList.Append(',');
-
-                paramList.Append(sqlParam.ParameterNameFixed);
-
-                MetaType mt = sqlParam.InternalMetaType;
-
-                //for UDTs, get the actual type name. Get only the typename, omit catalog and schema names.
-                //in TSQL you should only specify the unqualified type name
-
-                // paragraph above doesn't seem to be correct. Server won't find the type
-                // if we don't provide a fully qualified name
-                paramList.Append(" ");
-                if (mt.SqlDbType == SqlDbType.Udt)
-                {
-                    string fullTypeName = sqlParam.UdtTypeName;
-                    if (string.IsNullOrEmpty(fullTypeName))
-                        throw SQL.MustSetUdtTypeNameForUdtParams();
-
-                    paramList.Append(ParseAndQuoteIdentifier(fullTypeName, true /* is UdtTypeName */));
-                }
-                else if (mt.SqlDbType == SqlDbType.Structured)
-                {
-                    string typeName = sqlParam.TypeName;
-                    if (string.IsNullOrEmpty(typeName))
-                    {
-                        throw SQL.MustSetTypeNameForParam(mt.TypeName, sqlParam.ParameterNameFixed);
-                    }
-                    paramList.Append(ParseAndQuoteIdentifier(typeName, false /* is not UdtTypeName*/));
-
-                    // TVPs currently are the only Structured type and must be read only, so add that keyword
-                    paramList.Append(" READONLY");
-                }
-                else
-                {
-                    // func will change type to that with a 4 byte length if the type has a two
-                    // byte length and a parameter length > than that expressible in 2 bytes
-                    mt = sqlParam.ValidateTypeLengths();
-                    if ((!mt.IsPlp) && (sqlParam.Direction != ParameterDirection.Output))
-                    {
-                        sqlParam.FixStreamDataForNonPLP();
-                    }
-                    paramList.Append(mt.TypeName);
-                }
-
-                fAddSeperator = true;
-
-                if (mt.SqlDbType == SqlDbType.Decimal)
-                {
-                    byte precision = sqlParam.GetActualPrecision();
-                    byte scale = sqlParam.GetActualScale();
-
-                    paramList.Append('(');
-
-                    if (0 == precision)
-                    {
-                        precision = TdsEnums.DEFAULT_NUMERIC_PRECISION;
-                    }
-
-                    paramList.Append(precision);
-                    paramList.Append(',');
-                    paramList.Append(scale);
-                    paramList.Append(')');
-                }
-                else if (mt.IsVarTime)
-                {
-                    byte scale = sqlParam.GetActualScale();
-
-                    paramList.Append('(');
-                    paramList.Append(scale);
-                    paramList.Append(')');
-                }
-                else if (!mt.IsFixed && !mt.IsLong && mt.SqlDbType != SqlDbType.Timestamp && mt.SqlDbType != SqlDbType.Udt && SqlDbType.Structured != mt.SqlDbType)
-                {
-                    int size = sqlParam.Size;
-
-                    paramList.Append('(');
-
-                    // if using non unicode types, obtain the actual byte length from the parser, with it's associated code page
-                    if (mt.IsAnsiType)
-                    {
-                        object val = sqlParam.GetCoercedValue();
-                        string s = null;
-
-                        // deal with the sql types
-                        if ((null != val) && (DBNull.Value != val))
-                        {
-                            s = (val as string);
-                            if (null == s)
-                            {
-                                SqlString sval = val is SqlString ? (SqlString)val : SqlString.Null;
-                                if (!sval.IsNull)
-                                {
-                                    s = sval.Value;
-                                }
-                            }
-                        }
-
-                        if (null != s)
-                        {
-                            int actualBytes = parser.GetEncodingCharLength(s, sqlParam.GetActualSize(), sqlParam.Offset, null);
-                            // if actual number of bytes is greater than the user given number of chars, use actual bytes
-                            if (actualBytes > size)
-                                size = actualBytes;
-                        }
-                    }
-
-                    // If the user specifies a 0-sized parameter for a variable len field
-                    // pass over max size (8000 bytes or 4000 characters for wide types)
-                    if (0 == size)
-                        size = mt.IsSizeInCharacters ? (TdsEnums.MAXSIZE >> 1) : TdsEnums.MAXSIZE;
-
-                    paramList.Append(size);
-                    paramList.Append(')');
-                }
-                else if (mt.IsPlp && (mt.SqlDbType != SqlDbType.Xml) && (mt.SqlDbType != SqlDbType.Udt))
-                {
-                    paramList.Append("(max) ");
-                }
-
-                // set the output bit for Output or InputOutput parameters
-                if (sqlParam.Direction != ParameterDirection.Input)
-                    paramList.Append(" " + TdsEnums.PARAM_OUTPUT);
-            }
-
-            return paramList.ToString();
-        }
-
-        // Adds quotes to each part of a SQL identifier that may be multi-part, while leaving
-        //  the result as a single composite name.
-        private static string ParseAndQuoteIdentifier(string identifier, bool isUdtTypeName)
-        {
-            string[] strings = SqlParameter.ParseTypeName(identifier, isUdtTypeName);
-            return QuoteIdentifier(strings);
-        }
-
-        private static string QuoteIdentifier(ReadOnlySpan<string> strings)
-        {
-            StringBuilder bld = new StringBuilder();
-
-            // Stitching back together is a little tricky. Assume we want to build a full multi-part name
-            //  with all parts except trimming separators for leading empty names (null or empty strings,
-            //  but not whitespace). Separators in the middle should be added, even if the name part is
-            //  null/empty, to maintain proper location of the parts.
-            for (int i = 0; i < strings.Length; i++)
-            {
-                if (0 < bld.Length)
-                {
-                    bld.Append('.');
-                }
-                if (null != strings[i] && 0 != strings[i].Length)
-                {
-                    ADP.AppendQuotedString(bld, "[", "]", strings[i]);
-                }
-            }
-
-            return bld.ToString();
-        }
-
-        // returns set option text to turn on format only and key info on and off
-        //  When we are executing as a text command, then we never need
-        // to turn off the options since they command text is executed in the scope of sp_executesql.
-        // For a stored proc command, however, we must send over batch sql and then turn off
-        // the set options after we read the data.  See the code in Command.Execute()
-        private string GetSetOptionsString(CommandBehavior behavior)
-        {
-            string s = null;
-
-            if ((System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly)) ||
-               (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo)))
-            {
-                // SET FMTONLY ON will cause the server to ignore other SET OPTIONS, so turn
-                // it off before we ask for browse mode metadata
-                s = TdsEnums.FMTONLY_OFF;
-
-                if (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))
-                {
-                    s = s + TdsEnums.BROWSE_ON;
-                }
-
-                if (System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly))
-                {
-                    s = s + TdsEnums.FMTONLY_ON;
-                }
-            }
-
-            return s;
-        }
-
-        private string GetResetOptionsString(CommandBehavior behavior)
-        {
-            string s = null;
-
-            // SET FMTONLY ON OFF
-            if (System.Data.CommandBehavior.SchemaOnly == (behavior & CommandBehavior.SchemaOnly))
-            {
-                s = s + TdsEnums.FMTONLY_OFF;
-            }
-
-            // SET NO_BROWSETABLE OFF
-            if (System.Data.CommandBehavior.KeyInfo == (behavior & CommandBehavior.KeyInfo))
-            {
-                s = s + TdsEnums.BROWSE_OFF;
-            }
-
-            return s;
-        }
-
-        private string GetCommandText(CommandBehavior behavior)
-        {
-            // build the batch string we send over, since we execute within a stored proc (sp_executesql), the SET options never need to be
-            // turned off since they are scoped to the sproc
-            Debug.Assert(System.Data.CommandType.Text == this.CommandType, "invalid call to GetCommandText for stored proc!");
-            return GetSetOptionsString(behavior) + this.CommandText;
-        }
-
-        internal void CheckThrowSNIException()
-        {
-            var stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                stateObj.CheckThrowSNIException();
-            }
-        }
-
-        // We're being notified that the underlying connection has closed
-        internal void OnConnectionClosed()
-        {
-            var stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                stateObj.OnConnectionClosed();
-            }
-        }
-
-        internal TdsParserStateObject StateObject
-        {
-            get
-            {
-                return _stateObj;
-            }
-        }
-
-        private bool IsPrepared
-        {
-            get { return (_execType != EXECTYPE.UNPREPARED); }
-        }
-
-        private bool IsUserPrepared
-        {
-            get { return IsPrepared && !_hiddenPrepare && !IsDirty; }
-        }
-
-        internal bool IsDirty
-        {
-            get
-            {
-                // only dirty if prepared
-                var activeConnection = _activeConnection;
-                return (IsPrepared &&
-                    (_dirty ||
-                    ((_parameters != null) && (_parameters.IsDirty)) ||
-                    ((activeConnection != null) && ((activeConnection.CloseCount != _preparedConnectionCloseCount) || (activeConnection.ReconnectCount != _preparedConnectionReconnectCount)))));
-            }
-            set
-            {
-                // only mark the command as dirty if it is already prepared
-                // but always clear the value if it we are clearing the dirty flag
-                _dirty = value ? IsPrepared : false;
-                if (null != _parameters)
-                {
-                    _parameters.IsDirty = _dirty;
-                }
-                _cachedMetaData = null;
-            }
-        }
-
-        internal int InternalRecordsAffected
-        {
-            get
-            {
-                return _rowsAffected;
-            }
-            set
-            {
-                if (-1 == _rowsAffected)
-                {
-                    _rowsAffected = value;
-                }
-                else if (0 < value)
-                {
-                    _rowsAffected += value;
-                }
-            }
-        }
-
-        internal void ClearBatchCommand()
-        {
-            List<_SqlRPC> rpcList = _RPCList;
-            if (null != rpcList)
-            {
-                rpcList.Clear();
-            }
-            if (null != _parameterCollectionList)
-            {
-                _parameterCollectionList.Clear();
-            }
-
-            _SqlRPCBatchArray = null;
-            _currentlyExecutingBatch = 0;
-        }
-
-        internal bool BatchRPCMode
-        {
-            get
-            {
-                return _batchRPCMode;
-            }
-            set
-            {
-                _batchRPCMode = value;
-
-                if (_batchRPCMode == false)
-                {
-                    ClearBatchCommand();
-                }
-                else
-                {
-                    if (_RPCList == null)
-                    {
-                        _RPCList = new List<_SqlRPC>();
-                    }
-                    if (_parameterCollectionList == null)
-                    {
-                        _parameterCollectionList = new List<SqlParameterCollection>();
-                    }
-                }
-            }
-        }
-
-        internal void AddBatchCommand(string commandText, SqlParameterCollection parameters, CommandType cmdType)
-        {
-            Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
-            Debug.Assert(_RPCList != null);
-            Debug.Assert(_parameterCollectionList != null);
-
-            _SqlRPC rpc = new _SqlRPC();
-
-            CommandText = commandText;
-            CommandType = cmdType;
-
-            GetStateObject();
-            if (cmdType == CommandType.StoredProcedure)
-            {
-                BuildRPC(false, parameters, ref rpc);
-            }
-            else
-            {
-                // All batch sql statements must be executed inside sp_executesql, including those without parameters
-                BuildExecuteSql(CommandBehavior.Default, commandText, parameters, ref rpc);
-            }
-
-            _RPCList.Add(rpc);
-            // Always add a parameters collection per RPC, even if there are no parameters.
-            _parameterCollectionList.Add(parameters);
-
-            ReliablePutStateObject();
-        }
-
-        internal int ExecuteBatchRPCCommand()
-        {
-
-            Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
-            Debug.Assert(_RPCList != null, "No batch commands specified");
-
-            _SqlRPCBatchArray = _RPCList.ToArray();
-            _currentlyExecutingBatch = 0;
-            return ExecuteNonQuery();       // Check permissions, execute, return output params
-        }
-
-        internal int? GetRecordsAffected(int commandIndex)
-        {
-            Debug.Assert(BatchRPCMode, "Command is not in batch RPC Mode");
-            Debug.Assert(_SqlRPCBatchArray != null, "batch command have been cleared");
-            return _SqlRPCBatchArray[commandIndex].recordsAffected;
-        }
-
-        internal SqlException GetErrors(int commandIndex)
-        {
-            SqlException result = null;
-            int length = (_SqlRPCBatchArray[commandIndex].errorsIndexEnd - _SqlRPCBatchArray[commandIndex].errorsIndexStart);
-            if (0 < length)
-            {
-                SqlErrorCollection errors = new SqlErrorCollection();
-                for (int i = _SqlRPCBatchArray[commandIndex].errorsIndexStart; i < _SqlRPCBatchArray[commandIndex].errorsIndexEnd; ++i)
-                {
-                    errors.Add(_SqlRPCBatchArray[commandIndex].errors[i]);
-                }
-                for (int i = _SqlRPCBatchArray[commandIndex].warningsIndexStart; i < _SqlRPCBatchArray[commandIndex].warningsIndexEnd; ++i)
-                {
-                    errors.Add(_SqlRPCBatchArray[commandIndex].warnings[i]);
-                }
-                result = SqlException.CreateException(errors, Connection.ServerVersion, Connection.ClientConnectionId);
-            }
-            return result;
-        }
-
-
-#if DEBUG
-        internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait)
-        {
-            var stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
-            }
-            else
-            {
-                var tempCachedAsyncState = cachedAsyncState;
-                if (tempCachedAsyncState != null)
-                {
-                    var reader = tempCachedAsyncState.CachedAsyncReader;
-                    if (reader != null)
-                    {
-                        reader.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
-                    }
-                }
-            }
-        }
-
-        internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait)
-        {
-            var stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
-            }
-            else
-            {
-                var tempCachedAsyncState = _cachedAsyncState;
-                if (tempCachedAsyncState != null)
-                {
-                    var reader = tempCachedAsyncState.CachedAsyncReader;
-                    if (reader != null)
-                    {
-                        reader.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
-                    }
-                }
-            }
-        }
-#endif
-
-        internal void CancelIgnoreFailure()
-        {
-            // This method is used to route CancellationTokens to the Cancel method.
-            // Cancellation is a suggestion, and exceptions should be ignored
-            // rather than allowed to be unhandled, as there is no way to route
-            // them to the caller.  It would be expected that the error will be
-            // observed anyway from the regular method.  An example is canceling
-            // an operation on a closed connection.
-            try
-            {
-                Cancel();
-            }
-            catch (Exception)
-            {
-            }
-        }
-
-        private void NotifyDependency()
-        {
-            if (_sqlDep != null)
-            {
-                _sqlDep.StartTimer(Notification);
-            }
-        }
-
-        object ICloneable.Clone() => Clone();
-
-        public SqlCommand Clone() => new SqlCommand(this);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommandBuilder.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommandBuilder.cs
deleted file mode 100644 (file)
index a3a3859..0000000
+++ /dev/null
@@ -1,281 +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.Data.Common;
-using System.Data.Sql;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.CompilerServices;
-using System.Threading;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlCommandBuilder : DbCommandBuilder
-    {
-        public SqlCommandBuilder() : base()
-        {
-            GC.SuppressFinalize(this);
-            base.QuotePrefix = "["; // initialize base with defaults
-            base.QuoteSuffix = "]";
-        }
-
-        public SqlCommandBuilder(SqlDataAdapter adapter) : this()
-        {
-            DataAdapter = adapter;
-        }
-
-        /// <devnote>SqlServer only supports CatalogLocation.Start</devnote>
-        public override CatalogLocation CatalogLocation
-        {
-            get
-            {
-                return CatalogLocation.Start;
-            }
-            set
-            {
-                if (CatalogLocation.Start != value)
-                {
-                    throw ADP.SingleValuedProperty(nameof(CatalogLocation), nameof(CatalogLocation.Start));
-                }
-            }
-        }
-
-        /// <devnote>SqlServer only supports '.'</devnote>
-        public override string CatalogSeparator
-        {
-            get
-            {
-                return ".";
-            }
-            set
-            {
-                if ("." != value)
-                {
-                    throw ADP.SingleValuedProperty(nameof(CatalogSeparator), ".");
-                }
-            }
-        }
-
-        public new SqlDataAdapter DataAdapter
-        {
-            get
-            {
-                return (SqlDataAdapter)base.DataAdapter;
-            }
-            set
-            {
-                base.DataAdapter = value;
-            }
-        }
-
-        /// <devnote>SqlServer only supports '.'</devnote>
-        public override string QuotePrefix
-        {
-            get
-            {
-                return base.QuotePrefix;
-            }
-            set
-            {
-                if (("[" != value) && ("\"" != value))
-                {
-                    throw ADP.DoubleValuedProperty(nameof(QuotePrefix), "[", "\"");
-                }
-                base.QuotePrefix = value;
-            }
-        }
-
-        public override string QuoteSuffix
-        {
-            get
-            {
-                return base.QuoteSuffix;
-            }
-            set
-            {
-                if (("]" != value) && ("\"" != value))
-                {
-                    throw ADP.DoubleValuedProperty(nameof(QuoteSuffix), "]", "\"");
-                }
-                base.QuoteSuffix = value;
-            }
-        }
-
-        public override string SchemaSeparator
-        {
-            get
-            {
-                return ".";
-            }
-            set
-            {
-                if ("." != value)
-                {
-                    throw ADP.SingleValuedProperty(nameof(SchemaSeparator), ".");
-                }
-            }
-        }
-
-        private void SqlRowUpdatingHandler(object sender, SqlRowUpdatingEventArgs ruevent)
-        {
-            base.RowUpdatingHandler(ruevent);
-        }
-
-        public new SqlCommand GetInsertCommand()
-            => (SqlCommand)base.GetInsertCommand();
-
-        public new SqlCommand GetInsertCommand(bool useColumnsForParameterNames)
-            => (SqlCommand)base.GetInsertCommand(useColumnsForParameterNames);
-
-        public new SqlCommand GetUpdateCommand()
-            => (SqlCommand)base.GetUpdateCommand();
-
-        public new SqlCommand GetUpdateCommand(bool useColumnsForParameterNames)
-            => (SqlCommand)base.GetUpdateCommand(useColumnsForParameterNames);
-
-        public new SqlCommand GetDeleteCommand()
-            => (SqlCommand)base.GetDeleteCommand();
-
-        public new SqlCommand GetDeleteCommand(bool useColumnsForParameterNames)
-            => (SqlCommand)base.GetDeleteCommand(useColumnsForParameterNames);
-
-        protected override void ApplyParameterInfo(DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause)
-        {
-            SqlParameter p = (SqlParameter)parameter;
-            object valueType = datarow[SchemaTableColumn.ProviderType];
-            p.SqlDbType = (SqlDbType)valueType;
-            p.Offset = 0;
-
-            if ((p.SqlDbType == SqlDbType.Udt) && !p.SourceColumnNullMapping)
-            {
-                p.UdtTypeName = datarow["DataTypeName"] as string;
-            }
-            else
-            {
-                p.UdtTypeName = string.Empty;
-            }
-
-            object bvalue = datarow[SchemaTableColumn.NumericPrecision];
-            if (DBNull.Value != bvalue)
-            {
-                byte bval = (byte)(short)bvalue;
-                p.PrecisionInternal = ((0xff != bval) ? bval : (byte)0);
-            }
-
-            bvalue = datarow[SchemaTableColumn.NumericScale];
-            if (DBNull.Value != bvalue)
-            {
-                byte bval = (byte)(short)bvalue;
-                p.ScaleInternal = ((0xff != bval) ? bval : (byte)0);
-            }
-        }
-
-        protected override string GetParameterName(int parameterOrdinal)
-            => ("@p" + parameterOrdinal.ToString(CultureInfo.InvariantCulture));
-
-        protected override string GetParameterName(string parameterName)
-            => ("@" + parameterName);
-
-        protected override string GetParameterPlaceholder(int parameterOrdinal)
-            => ("@p" + parameterOrdinal.ToString(CultureInfo.InvariantCulture));
-
-        private void ConsistentQuoteDelimiters(string quotePrefix, string quoteSuffix)
-        {
-            Debug.Assert(quotePrefix == "\"" || quotePrefix == "[");
-            if ((("\"" == quotePrefix) && ("\"" != quoteSuffix)) ||
-                (("[" == quotePrefix) && ("]" != quoteSuffix)))
-            {
-                throw ADP.InvalidPrefixSuffix();
-            }
-        }
-
-        public static void DeriveParameters(SqlCommand command)
-        {
-            if (null == command)
-            {
-                throw ADP.ArgumentNull(nameof(command));
-            }
-
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try
-            {
-                command.DeriveParameters();
-            }
-            catch (OutOfMemoryException e)
-            {
-                command?.Connection?.Abort(e);
-                throw;
-            }
-            catch (StackOverflowException e)
-            {
-                command?.Connection?.Abort(e);
-                throw;
-            }
-            catch (ThreadAbortException e)
-            {
-                command?.Connection?.Abort(e);
-                throw;
-            }
-        }
-
-        protected override DataTable GetSchemaTable(DbCommand srcCommand)
-        {
-            SqlCommand sqlCommand = srcCommand as SqlCommand;
-            SqlNotificationRequest notificationRequest = sqlCommand.Notification;
-
-            sqlCommand.Notification = null;
-
-            try
-            {
-                using (SqlDataReader dataReader = sqlCommand.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo))
-                {
-                    return dataReader.GetSchemaTable();
-                }
-            }
-            finally
-            {
-                sqlCommand.Notification = notificationRequest;
-            }
-
-        }
-
-        protected override DbCommand InitializeCommand(DbCommand command)
-            => (SqlCommand)base.InitializeCommand(command);
-
-        public override string QuoteIdentifier(string unquotedIdentifier)
-        {
-            ADP.CheckArgumentNull(unquotedIdentifier, nameof(unquotedIdentifier));
-            string quoteSuffixLocal = QuoteSuffix;
-            string quotePrefixLocal = QuotePrefix;
-            ConsistentQuoteDelimiters(quotePrefixLocal, quoteSuffixLocal);
-            return ADP.BuildQuotedString(quotePrefixLocal, quoteSuffixLocal, unquotedIdentifier);
-        }
-
-        protected override void SetRowUpdatingHandler(DbDataAdapter adapter)
-        {
-            Debug.Assert(adapter is SqlDataAdapter, "Adapter is not a SqlDataAdapter.");
-            if (adapter == base.DataAdapter)
-            { // removal case
-                ((SqlDataAdapter)adapter).RowUpdating -= SqlRowUpdatingHandler;
-            }
-            else
-            { // adding case
-                ((SqlDataAdapter)adapter).RowUpdating += SqlRowUpdatingHandler;
-            }
-        }
-
-        public override string UnquoteIdentifier(string quotedIdentifier)
-        {
-            ADP.CheckArgumentNull(quotedIdentifier, nameof(quotedIdentifier));
-            string unquotedIdentifier;
-            string quoteSuffixLocal = QuoteSuffix;
-            string quotePrefixLocal = QuotePrefix;
-            ConsistentQuoteDelimiters(quotePrefixLocal, quoteSuffixLocal);
-            // ignoring the return value becasue an unquoted source string is OK here
-            ADP.RemoveStringQuotes(quotePrefixLocal, quoteSuffixLocal, quotedIdentifier, out unquotedIdentifier);
-            return unquotedIdentifier;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommandSet.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommandSet.cs
deleted file mode 100644 (file)
index b823208..0000000
+++ /dev/null
@@ -1,299 +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.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Text;
-using System.Text.RegularExpressions;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlCommandSet
-    {
-        private const string SqlIdentifierPattern = "^@[\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}_@#][\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}\\p{Nd}\uff3f_@#\\$]*$";
-        private static readonly Regex s_sqlIdentifierParser = new Regex(SqlIdentifierPattern, RegexOptions.ExplicitCapture | RegexOptions.Singleline);
-
-        private List<LocalCommand> _commandList = new List<LocalCommand>();
-
-        private SqlCommand _batchCommand;
-
-        private sealed class LocalCommand
-        {
-            internal readonly string CommandText;
-            internal readonly SqlParameterCollection Parameters;
-            internal readonly int ReturnParameterIndex;
-            internal readonly CommandType CmdType;
-
-            internal LocalCommand(string commandText, SqlParameterCollection parameters, int returnParameterIndex, CommandType cmdType)
-            {
-                Debug.Assert(0 <= commandText.Length, "no text");
-                CommandText = commandText;
-                Parameters = parameters;
-                ReturnParameterIndex = returnParameterIndex;
-                CmdType = cmdType;
-            }
-        }
-
-        internal SqlCommandSet() : base()
-        {
-            _batchCommand = new SqlCommand();
-        }
-
-        private SqlCommand BatchCommand
-        {
-            get
-            {
-                SqlCommand command = _batchCommand;
-                if (null == command)
-                {
-                    throw ADP.ObjectDisposed(this);
-                }
-                return command;
-            }
-        }
-
-        internal int CommandCount => CommandList.Count;
-
-        private List<LocalCommand> CommandList
-        {
-            get
-            {
-                List<LocalCommand> commandList = _commandList;
-                if (null == commandList)
-                {
-                    throw ADP.ObjectDisposed(this);
-                }
-                return commandList;
-            }
-        }
-
-        internal int CommandTimeout
-        {
-            set
-            {
-                BatchCommand.CommandTimeout = value;
-            }
-        }
-
-        internal SqlConnection Connection
-        {
-            get
-            {
-                return BatchCommand.Connection;
-            }
-            set
-            {
-                BatchCommand.Connection = value;
-            }
-        }
-
-        internal SqlTransaction Transaction
-        {
-            set
-            {
-                BatchCommand.Transaction = value;
-            }
-        }
-
-        internal void Append(SqlCommand command)
-        {
-            ADP.CheckArgumentNull(command, nameof(command));
-
-            string cmdText = command.CommandText;
-            if (string.IsNullOrEmpty(cmdText))
-            {
-                throw ADP.CommandTextRequired(nameof(Append));
-            }
-
-            CommandType commandType = command.CommandType;
-            switch (commandType)
-            {
-                case CommandType.Text:
-                case CommandType.StoredProcedure:
-                    break;
-                case CommandType.TableDirect:
-                    throw SQL.NotSupportedCommandType(commandType);
-                default:
-                    throw ADP.InvalidCommandType(commandType);
-            }
-
-            SqlParameterCollection parameters = null;
-
-            SqlParameterCollection collection = command.Parameters;
-            if (0 < collection.Count)
-            {
-                parameters = new SqlParameterCollection();
-
-                // clone parameters so they aren't destroyed
-                for (int i = 0; i < collection.Count; ++i)
-                {
-                    SqlParameter p = new SqlParameter();
-                    collection[i].CopyTo(p);
-                    parameters.Add(p);
-
-                    // SQL Injection awareness
-                    if (!s_sqlIdentifierParser.IsMatch(p.ParameterName))
-                    {
-                        throw ADP.BadParameterName(p.ParameterName);
-                    }
-                }
-
-                foreach (SqlParameter p in parameters)
-                {
-                    // deep clone the parameter value if byte[] or char[]
-                    object obj = p.Value;
-                    byte[] byteValues = (obj as byte[]);
-                    if (null != byteValues)
-                    {
-                        int offset = p.Offset;
-                        int size = p.Size;
-                        int countOfBytes = byteValues.Length - offset;
-                        if ((0 != size) && (size < countOfBytes))
-                        {
-                            countOfBytes = size;
-                        }
-                        byte[] copy = new byte[Math.Max(countOfBytes, 0)];
-                        Buffer.BlockCopy(byteValues, offset, copy, 0, copy.Length);
-                        p.Offset = 0;
-                        p.Value = copy;
-                    }
-                    else
-                    {
-                        char[] charValues = (obj as char[]);
-                        if (null != charValues)
-                        {
-                            int offset = p.Offset;
-                            int size = p.Size;
-                            int countOfChars = charValues.Length - offset;
-                            if ((0 != size) && (size < countOfChars))
-                            {
-                                countOfChars = size;
-                            }
-                            char[] copy = new char[Math.Max(countOfChars, 0)];
-                            Buffer.BlockCopy(charValues, offset, copy, 0, copy.Length * 2);
-                            p.Offset = 0;
-                            p.Value = copy;
-                        }
-                        else
-                        {
-                            ICloneable cloneable = (obj as ICloneable);
-                            if (null != cloneable)
-                            {
-                                p.Value = cloneable.Clone();
-                            }
-                        }
-                    }
-                }
-            }
-
-            int returnParameterIndex = -1;
-            if (null != parameters)
-            {
-                for (int i = 0; i < parameters.Count; ++i)
-                {
-                    if (ParameterDirection.ReturnValue == parameters[i].Direction)
-                    {
-                        returnParameterIndex = i;
-                        break;
-                    }
-                }
-            }
-            LocalCommand cmd = new LocalCommand(cmdText, parameters, returnParameterIndex, command.CommandType);
-            CommandList.Add(cmd);
-        }
-
-        internal static void BuildStoredProcedureName(StringBuilder builder, string part)
-        {
-            if ((null != part) && (0 < part.Length))
-            {
-                if ('[' == part[0])
-                {
-                    int count = 0;
-                    foreach (char c in part)
-                    {
-                        if (']' == c)
-                        {
-                            count++;
-                        }
-                    }
-                    if (1 == (count % 2))
-                    {
-                        builder.Append(part);
-                        return;
-                    }
-                }
-
-                // the part is not escaped, escape it now
-                SqlServerEscapeHelper.EscapeIdentifier(builder, part);
-            }
-        }
-
-        internal void Clear()
-        {
-            DbCommand batchCommand = BatchCommand;
-            if (null != batchCommand)
-            {
-                batchCommand.Parameters.Clear();
-                batchCommand.CommandText = null;
-            }
-            List<LocalCommand> commandList = _commandList;
-            if (null != commandList)
-            {
-                commandList.Clear();
-            }
-        }
-
-        internal void Dispose()
-        {
-            SqlCommand command = _batchCommand;
-            _commandList = null;
-            _batchCommand = null;
-
-            if (null != command)
-            {
-                command.Dispose();
-            }
-        }
-
-        internal int ExecuteNonQuery()
-        {
-            ValidateCommandBehavior(nameof(ExecuteNonQuery), CommandBehavior.Default);
-
-            BatchCommand.BatchRPCMode = true;
-            BatchCommand.ClearBatchCommand();
-            BatchCommand.Parameters.Clear();
-            for (int ii = 0; ii < _commandList.Count; ii++)
-            {
-                LocalCommand cmd = _commandList[ii];
-                BatchCommand.AddBatchCommand(cmd.CommandText, cmd.Parameters, cmd.CmdType);
-            }
-
-            return BatchCommand.ExecuteBatchRPCCommand();
-        }
-
-        internal SqlParameter GetParameter(int commandIndex, int parameterIndex)
-            => CommandList[commandIndex].Parameters[parameterIndex];
-
-        internal bool GetBatchedAffected(int commandIdentifier, out int recordsAffected, out Exception error)
-        {
-            error = BatchCommand.GetErrors(commandIdentifier);
-            int? affected = BatchCommand.GetRecordsAffected(commandIdentifier);
-            recordsAffected = affected.GetValueOrDefault();
-            return affected.HasValue;
-        }
-
-        internal int GetParameterCount(int commandIndex)
-            => CommandList[commandIndex].Parameters.Count;
-
-        private void ValidateCommandBehavior(string method, CommandBehavior behavior)
-        {
-            if (0 != (behavior & ~(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection)))
-            {
-                ADP.ValidateCommandBehavior(behavior);
-                throw ADP.NotSupportedCommandBehavior(behavior & ~(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection), method);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs
deleted file mode 100644 (file)
index f67ef15..0000000
+++ /dev/null
@@ -1,1708 +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.Data.Common;
-using System.Data.ProviderBase;
-using System.Diagnostics;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Diagnostics.CodeAnalysis;
-using System.Transactions;
-using Microsoft.SqlServer.Server;
-using System.Reflection;
-using System.IO;
-using System.Globalization;
-using System.Security;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlConnection : DbConnection, ICloneable
-    {
-        private bool _AsyncCommandInProgress;
-
-        // SQLStatistics support
-        internal SqlStatistics _statistics;
-        private bool _collectstats;
-
-        private bool _fireInfoMessageEventOnUserErrors; // False by default
-
-        // root task associated with current async invocation
-        private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;
-
-        private SqlCredential _credential;
-        private string _connectionString;
-        private int _connectRetryCount;
-        private string _accessToken; // Access Token to be used for token based authententication
-
-        // connection resiliency
-        private readonly object _reconnectLock = new object();
-        internal Task _currentReconnectionTask;
-        private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections
-        private Guid _originalConnectionId = Guid.Empty;
-        private CancellationTokenSource _reconnectionCancellationSource;
-        internal SessionData _recoverySessionData;
-        internal bool _suppressStateChangeForReconnection;
-        private int _reconnectCount;
-
-        // diagnostics listener
-        private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
-
-        // Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not
-        // The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened
-        // using SqlConnection.Open() method.
-        internal bool _applyTransientFaultHandling = false;
-
-        public SqlConnection(string connectionString) : this()
-        {
-            ConnectionString = connectionString;    // setting connection string first so that ConnectionOption is available
-            CacheConnectionStringProperties();
-        }
-
-        public SqlConnection(string connectionString, SqlCredential credential) : this()
-        {
-            ConnectionString = connectionString;
-            if (credential != null)
-            {
-                // The following checks are necessary as setting Credential property will call CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential
-                //  CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential it will throw InvalidOperationException rather than Arguemtn exception
-                //  Need to call setter on Credential property rather than setting _credential directly as pool groups need to be checked
-                SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
-                if (UsesClearUserIdOrPassword(connectionOptions))
-                {
-                    throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
-                }
-
-                if (UsesIntegratedSecurity(connectionOptions))
-                {
-                    throw ADP.InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity();
-                }
-                Credential = credential;
-            }
-            // 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)
-        {
-            GC.SuppressFinalize(this);
-            CopyFrom(connection);
-            _connectionString = connection._connectionString;
-            if (connection._credential != null)
-            {
-                SecureString password = connection._credential.Password.Copy();
-                password.MakeReadOnly();
-                _credential = new SqlCredential(connection._credential.UserId, password);
-            }
-
-            _accessToken = connection._accessToken;
-            CacheConnectionStringProperties();
-        }
-
-        // This method will be called once connection string is set or changed.
-        private void CacheConnectionStringProperties()
-        {
-            SqlConnectionString connString = ConnectionOptions as SqlConnectionString;
-            if (connString != null)
-            {
-                _connectRetryCount = connString.ConnectRetryCount;
-            }
-        }
-
-        //
-        // PUBLIC PROPERTIES
-        //
-
-        // used to start/stop collection of statistics data and do verify the current state
-        //
-        // devnote: start/stop should not performed using a property since it requires execution of code
-        //
-        // start statistics
-        //  set the internal flag (_statisticsEnabled) to true.
-        //  Create a new SqlStatistics object if not already there.
-        //  connect the parser to the object.
-        //  if there is no parser at this time we need to connect it after creation.
-        //
-
-        public bool StatisticsEnabled
-        {
-            get
-            {
-                return (_collectstats);
-            }
-            set
-            {
-                {
-                    if (value)
-                    {
-                        // start
-                        if (ConnectionState.Open == State)
-                        {
-                            if (null == _statistics)
-                            {
-                                _statistics = new SqlStatistics();
-                                ADP.TimerCurrent(out _statistics._openTimestamp);
-                            }
-                            // set statistics on the parser
-                            // update timestamp;
-                            Debug.Assert(Parser != null, "Where's the parser?");
-                            Parser.Statistics = _statistics;
-                        }
-                    }
-                    else
-                    {
-                        // stop
-                        if (null != _statistics)
-                        {
-                            if (ConnectionState.Open == State)
-                            {
-                                // remove statistics from parser
-                                // update timestamp;
-                                TdsParser parser = Parser;
-                                Debug.Assert(parser != null, "Where's the parser?");
-                                parser.Statistics = null;
-                                ADP.TimerCurrent(out _statistics._closeTimestamp);
-                            }
-                        }
-                    }
-                    _collectstats = value;
-                }
-            }
-        }
-
-        internal bool AsyncCommandInProgress
-        {
-            get => _AsyncCommandInProgress;
-            set => _AsyncCommandInProgress = value;
-        }
-
-        // Does this connection use Integrated Security?
-        private bool UsesIntegratedSecurity(SqlConnectionString opt)
-        {
-            return opt != null ? opt.IntegratedSecurity : false;
-        }
-
-        // Does this connection use old style of clear userID or Password in connection string?
-        private bool UsesClearUserIdOrPassword(SqlConnectionString opt)
-        {
-            bool result = false;
-            if (null != opt)
-            {
-                result = (!string.IsNullOrEmpty(opt.UserID) || !string.IsNullOrEmpty(opt.Password));
-            }
-            return result;
-        }
-
-        internal SqlConnectionString.TransactionBindingEnum TransactionBinding
-        {
-            get => ((SqlConnectionString)ConnectionOptions).TransactionBinding;
-        }
-
-        internal SqlConnectionString.TypeSystem TypeSystem
-        {
-            get => ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
-        }
-
-        internal Version TypeSystemAssemblyVersion
-        {
-            get => ((SqlConnectionString)ConnectionOptions).TypeSystemAssemblyVersion;
-        }
-
-        internal int ConnectRetryInterval
-        {
-            get => ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
-        }
-
-        public override string ConnectionString
-        {
-            get
-            {
-                return ConnectionString_Get();
-            }
-            set
-            {
-                if (_credential != null || _accessToken != null)
-                {
-                    SqlConnectionString connectionOptions = new SqlConnectionString(value);
-                    if (_credential != null)
-                    {
-                        CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(connectionOptions);
-                    }
-                    else
-                    {
-                        CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(connectionOptions);
-                    }
-                }
-                ConnectionString_Set(new SqlConnectionPoolKey(value, _credential, _accessToken));
-                _connectionString = value;  // Change _connectionString value only after value is validated
-                CacheConnectionStringProperties();
-            }
-        }
-
-        public override int ConnectionTimeout
-        {
-            get
-            {
-                SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
-                return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
-            }
-        }
-
-        // AccessToken: To be used for token based authentication
-        public string AccessToken
-        {
-            get
-            {
-                // When a connection is connecting or is ever opened, make AccessToken available only if "Persist Security Info" is set to true
-                // otherwise, return null
-                SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
-                return InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo ? null : _accessToken;
-            }
-            set
-            {
-                // If a connection is connecting or is ever opened, AccessToken cannot be set
-                if (!InnerConnection.AllowSetConnectionString)
-                {
-                    throw ADP.OpenConnectionPropertySet("AccessToken", InnerConnection.State);
-                }
-
-                if (value != null)
-                {
-                    // Check if the usage of AccessToken has any conflict with the keys used in connection string and credential
-                    CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken((SqlConnectionString)ConnectionOptions);
-                }
-
-                // Need to call ConnectionString_Set to do proper pool group check
-                ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, credential: _credential, accessToken: value));
-                _accessToken = value;
-            }
-        }
-
-        public override string Database
-        {
-            // if the connection is open, we need to ask the inner connection what it's
-            // current catalog is because it may have gotten changed, otherwise we can
-            // just return what the connection string had.
-            get
-            {
-                SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
-                string result;
-
-                if (null != innerConnection)
-                {
-                    result = innerConnection.CurrentDatabase;
-                }
-                else
-                {
-                    SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
-                    result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog);
-                }
-                return result;
-            }
-        }
-
-        public override string DataSource
-        {
-            get
-            {
-                SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
-                string result;
-
-                if (null != innerConnection)
-                {
-                    result = innerConnection.CurrentDataSource;
-                }
-                else
-                {
-                    SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
-                    result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source);
-                }
-                return result;
-            }
-        }
-
-        public int PacketSize
-        {
-            // if the connection is open, we need to ask the inner connection what it's
-            // current packet size is because it may have gotten changed, otherwise we
-            // can just return what the connection string had.
-            get
-            {
-                SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
-                int result;
-
-                if (null != innerConnection)
-                {
-                    result = innerConnection.PacketSize;
-                }
-                else
-                {
-                    SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
-                    result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size);
-                }
-                return result;
-            }
-        }
-
-        public Guid ClientConnectionId
-        {
-            get
-            {
-                SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
-
-                if (null != innerConnection)
-                {
-                    return innerConnection.ClientConnectionId;
-                }
-                else
-                {
-                    Task reconnectTask = _currentReconnectionTask;
-                    if (reconnectTask != null && !reconnectTask.IsCompleted)
-                    {
-                        return _originalConnectionId;
-                    }
-                    return Guid.Empty;
-                }
-            }
-        }
-
-        public override string ServerVersion
-        {
-            get => GetOpenTdsConnection().ServerVersion;
-        }
-
-        public override ConnectionState State
-        {
-            get
-            {
-                Task reconnectTask = _currentReconnectionTask;
-                if (reconnectTask != null && !reconnectTask.IsCompleted)
-                {
-                    return ConnectionState.Open;
-                }
-                return InnerConnection.State;
-            }
-        }
-
-
-        internal SqlStatistics Statistics
-        {
-            get => _statistics;
-        }
-
-        public string WorkstationId
-        {
-            get
-            {
-                // If not supplied by the user, the default value is the MachineName
-                // Note: In Longhorn you'll be able to rename a machine without
-                // rebooting.  Therefore, don't cache this machine name.
-                SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
-                string result = constr?.WorkstationId ?? Environment.MachineName;
-                return result;
-            }
-        }
-
-        public SqlCredential Credential
-        {
-            get
-            {
-                SqlCredential result = _credential;
-
-                // When a connection is connecting or is ever opened, make credential available only if "Persist Security Info" is set to true
-                //  otherwise, return null
-                SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
-                if (InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo)
-                {
-                    result = null;
-                }
-
-                return result;
-            }
-
-            set
-            {
-                // If a connection is connecting or is ever opened, user id/password cannot be set
-                if (!InnerConnection.AllowSetConnectionString)
-                {
-                    throw ADP.OpenConnectionPropertySet(nameof(Credential), InnerConnection.State);
-                }
-
-                // check if the usage of credential has any conflict with the keys used in connection string
-                if (value != null)
-                {
-                    CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential((SqlConnectionString)ConnectionOptions);
-                    if (_accessToken != null)
-                    {
-                        throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
-                    }
-                }
-
-                _credential = value;
-
-                // Need to call ConnectionString_Set to do proper pool group check
-                ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, accessToken: _accessToken));
-            }
-        }
-
-        // CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential: check if the usage of credential has any conflict
-        //  with the keys used in connection string
-        //  If there is any conflict, it throws InvalidOperationException
-        //  This is used in the setter of ConnectionString and Credential properties.
-        private void CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(SqlConnectionString connectionOptions)
-        {
-            if (UsesClearUserIdOrPassword(connectionOptions))
-            {
-                throw ADP.InvalidMixedUsageOfSecureAndClearCredential();
-            }
-
-            if (UsesIntegratedSecurity(connectionOptions))
-            {
-                throw ADP.InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity();
-            }
-        }
-
-        // CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken: check if the usage of AccessToken has any conflict
-        //  with the keys used in connection string and credential
-        //  If there is any conflict, it throws InvalidOperationException
-        //  This is to be used setter of ConnectionString and AccessToken properties
-        private void CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(SqlConnectionString connectionOptions)
-        {
-            if (UsesClearUserIdOrPassword(connectionOptions))
-            {
-                throw ADP.InvalidMixedUsageOfAccessTokenAndUserIDPassword();
-            }
-
-            if (UsesIntegratedSecurity(connectionOptions))
-            {
-                throw ADP.InvalidMixedUsageOfAccessTokenAndIntegratedSecurity();
-            }
-
-            // Check if the usage of AccessToken has the conflict with credential
-            if (_credential != null)
-            {
-                throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
-            }
-        }
-
-        protected override DbProviderFactory DbProviderFactory
-        {
-            get => SqlClientFactory.Instance;
-        }
-
-        // SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
-
-        //
-        // PUBLIC EVENTS
-        //
-
-        public event SqlInfoMessageEventHandler InfoMessage;
-
-        public bool FireInfoMessageEventOnUserErrors
-        {
-            get => _fireInfoMessageEventOnUserErrors;
-            set => _fireInfoMessageEventOnUserErrors = value;
-        }
-
-        // Approx. number of times that the internal connection has been reconnected
-        internal int ReconnectCount
-        {
-            get => _reconnectCount;
-        }
-
-        internal bool ForceNewConnection { get; set; }
-
-        protected override void OnStateChange(StateChangeEventArgs stateChange)
-        {
-            if (!_suppressStateChangeForReconnection)
-            {
-                base.OnStateChange(stateChange);
-            }
-        }
-
-        //
-        // PUBLIC METHODS
-        //
-
-        public new SqlTransaction BeginTransaction()
-        {
-            // this is just a delegate. The actual method tracks executiontime
-            return BeginTransaction(IsolationLevel.Unspecified, null);
-        }
-
-        public new SqlTransaction BeginTransaction(IsolationLevel iso)
-        {
-            // this is just a delegate. The actual method tracks executiontime
-            return BeginTransaction(iso, null);
-        }
-
-        public SqlTransaction BeginTransaction(string transactionName)
-        {
-            // Use transaction names only on the outermost pair of nested
-            // BEGIN...COMMIT or BEGIN...ROLLBACK statements.  Transaction names
-            // are ignored for nested BEGIN's.  The only way to rollback a nested
-            // transaction is to have a save point from a SAVE TRANSACTION call.
-            return BeginTransaction(IsolationLevel.Unspecified, transactionName);
-        }
-
-        [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
-        protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
-        {
-            DbTransaction transaction = BeginTransaction(isolationLevel);
-
-            //   InnerConnection doesn't maintain a ref on the outer connection (this) and
-            //   subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction
-            //   is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
-            //   until the completion of BeginTransaction with KeepAlive
-            GC.KeepAlive(this);
-
-            return transaction;
-        }
-
-        public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName)
-        {
-            WaitForPendingReconnection();
-            SqlStatistics statistics = null;
-
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                SqlTransaction transaction;
-                bool isFirstAttempt = true;
-                do
-                {
-                    transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice
-                    Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt");
-                    isFirstAttempt = false;
-                } while (transaction.InternalTransaction.ConnectionHasBeenRestored);
-
-
-                //  The GetOpenConnection line above doesn't keep a ref on the outer connection (this),
-                //  and it could be collected before the inner connection can hook it to the transaction, resulting in
-                //  a transaction with a null connection property.  Use GC.KeepAlive to ensure this doesn't happen.
-                GC.KeepAlive(this);
-
-                return transaction;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public override void ChangeDatabase(string database)
-        {
-            SqlStatistics statistics = null;
-            RepairInnerConnection();
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                InnerConnection.ChangeDatabase(database);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public static void ClearAllPools()
-        {
-            SqlConnectionFactory.SingletonInstance.ClearAllPools();
-        }
-
-        public static void ClearPool(SqlConnection connection)
-        {
-            ADP.CheckArgumentNull(connection, nameof(connection));
-
-            DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
-            if (null != connectionOptions)
-            {
-                SqlConnectionFactory.SingletonInstance.ClearPool(connection);
-            }
-        }
-
-
-        private void CloseInnerConnection()
-        {
-            // CloseConnection() now handles the lock
-
-            // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
-            // the command will no longer be cancelable.  It might be desirable to be able to cancel the close operation, but this is
-            // outside of the scope of Whidbey RTM.  See (SqlCommand::Cancel) for other lock.
-            InnerConnection.CloseConnection(this, ConnectionFactory);
-        }
-
-        public override void Close()
-        {
-            ConnectionState previousState = State;
-            Guid operationId = default(Guid);
-            Guid clientConnectionId = default(Guid);
-
-            // during the call to Dispose() there is a redundant call to
-            // Close(). because of this, the second time Close() is invoked the
-            // connection is already in a closed state. this doesn't seem to be a
-            // problem except for logging, as we'll get duplicate Before/After/Error
-            // log entries
-            if (previousState != ConnectionState.Closed)
-            {
-                operationId = s_diagnosticListener.WriteConnectionCloseBefore(this);
-                // we want to cache the ClientConnectionId for After/Error logging, as when the connection
-                // is closed then we will lose this identifier
-                //
-                // note: caching this is only for diagnostics logging purposes
-                clientConnectionId = ClientConnectionId;
-            }
-
-            SqlStatistics statistics = null;
-
-            Exception e = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                Task reconnectTask = _currentReconnectionTask;
-                if (reconnectTask != null && !reconnectTask.IsCompleted)
-                {
-                    CancellationTokenSource cts = _reconnectionCancellationSource;
-                    if (cts != null)
-                    {
-                        cts.Cancel();
-                    }
-                    AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
-                    if (State != ConnectionState.Open)
-                    {// if we cancelled before the connection was opened
-                        OnStateChange(DbConnectionInternal.StateChangeClosed);
-                    }
-                }
-                CancelOpenAndWait();
-                CloseInnerConnection();
-                GC.SuppressFinalize(this);
-
-                if (null != Statistics)
-                {
-                    ADP.TimerCurrent(out _statistics._closeTimestamp);
-                }
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-
-                // we only want to log this if the previous state of the
-                // connection is open, as that's the valid use-case
-                if (previousState != ConnectionState.Closed)
-                {
-                    if (e != null)
-                    {
-                        s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e);
-                    }
-                    else
-                    {
-                        s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this);
-                    }
-                }
-            }
-        }
-
-        public new SqlCommand CreateCommand()
-        {
-            return new SqlCommand(null, this);
-        }
-
-        private void DisposeMe(bool disposing)
-        {
-            _credential = null;
-            _accessToken = null;
-
-            if (!disposing)
-            {
-                // For non-pooled connections we need to make sure that if the SqlConnection was not closed,
-                // then we release the GCHandle on the stateObject to allow it to be GCed
-                // For pooled connections, we will rely on the pool reclaiming the connection
-                var innerConnection = (InnerConnection as SqlInternalConnectionTds);
-                if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling))
-                {
-                    var parser = innerConnection.Parser;
-                    if ((parser != null) && (parser._physicalStateObj != null))
-                    {
-                        parser._physicalStateObj.DecrementPendingCallbacks(release: false);
-                    }
-                }
-            }
-        }
-
-
-        public override void Open()
-        {
-            Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
-
-            PrepareStatisticsForNewConnection();
-
-            SqlStatistics statistics = null;
-
-            Exception e = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                if (!TryOpen(null))
-                {
-                    throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
-                }
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-
-                if (e != null)
-                {
-                    s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
-                }
-                else
-                {
-                    s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
-                }
-            }
-        }
-
-        internal void RegisterWaitingForReconnect(Task waitingTask)
-        {
-            if (((SqlConnectionString)ConnectionOptions).MARS)
-            {
-                return;
-            }
-            Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null);
-            if (_asyncWaitingForReconnection != waitingTask)
-            { // somebody else managed to register
-                throw SQL.MARSUnspportedOnConnection();
-            }
-        }
-
-        private async Task ReconnectAsync(int timeout)
-        {
-            try
-            {
-                long commandTimeoutExpiration = 0;
-                if (timeout > 0)
-                {
-                    commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout);
-                }
-                CancellationTokenSource cts = new CancellationTokenSource();
-                _reconnectionCancellationSource = cts;
-                CancellationToken ctoken = cts.Token;
-                int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string
-                for (int attempt = 0; attempt < retryCount; attempt++)
-                {
-                    if (ctoken.IsCancellationRequested)
-                    {
-                        return;
-                    }
-                    try
-                    {
-                        try
-                        {
-                            ForceNewConnection = true;
-                            await OpenAsync(ctoken).ConfigureAwait(false);
-                            // On success, increment the reconnect count - we don't really care if it rolls over since it is approx.
-                            _reconnectCount = unchecked(_reconnectCount + 1);
-#if DEBUG
-                            Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !");
-#endif
-                        }
-                        finally
-                        {
-                            ForceNewConnection = false;
-                        }
-                        return;
-                    }
-                    catch (SqlException e)
-                    {
-                        if (attempt == retryCount - 1)
-                        {
-                            throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
-                        }
-                        if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval))
-                        {
-                            throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId);
-                        }
-                    }
-                    await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false);
-                }
-            }
-            finally
-            {
-                _recoverySessionData = null;
-                _suppressStateChangeForReconnection = false;
-            }
-            Debug.Fail("Should not reach this point");
-        }
-
-        internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
-        {
-            Task runningReconnect = _currentReconnectionTask;
-            // This loop in the end will return not completed reconnect task or null
-            while (runningReconnect != null && runningReconnect.IsCompleted)
-            {
-                // clean current reconnect task (if it is the same one we checked
-                Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect);
-                // make sure nobody started new task (if which case we did not clean it)
-                runningReconnect = _currentReconnectionTask;
-            }
-            if (runningReconnect == null)
-            {
-                if (_connectRetryCount > 0)
-                {
-                    SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();
-                    if (tdsConn._sessionRecoveryAcknowledged)
-                    {
-                        TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;
-                        if (!stateObj.ValidateSNIConnection())
-                        {
-                            if (tdsConn.Parser._sessionPool != null)
-                            {
-                                if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0)
-                                {
-                                    // >1 MARS session
-                                    if (beforeDisconnect != null)
-                                    {
-                                        beforeDisconnect();
-                                    }
-                                    OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
-                                }
-                            }
-                            SessionData cData = tdsConn.CurrentSessionData;
-                            cData.AssertUnrecoverableStateCountIsCorrect();
-                            if (cData._unrecoverableStatesCount == 0)
-                            {
-                                bool callDisconnect = false;
-                                lock (_reconnectLock)
-                                {
-                                    tdsConn.CheckEnlistedTransactionBinding();
-                                    runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
-                                    if (runningReconnect == null)
-                                    {
-                                        if (cData._unrecoverableStatesCount == 0)
-                                        { // could change since the first check, but now is stable since connection is know to be broken
-                                            _originalConnectionId = ClientConnectionId;
-                                            _recoverySessionData = cData;
-                                            if (beforeDisconnect != null)
-                                            {
-                                                beforeDisconnect();
-                                            }
-                                            try
-                                            {
-                                                _suppressStateChangeForReconnection = true;
-                                                tdsConn.DoomThisConnection();
-                                            }
-                                            catch (SqlException)
-                                            {
-                                            }
-                                            // use Task.Factory.StartNew with state overload instead of Task.Run to avoid anonymous closure context capture in method scope and avoid the unneeded allocation
-                                            runningReconnect = Task.Factory.StartNew(state => ReconnectAsync((int)state), timeout, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();
-                                            // if current reconnect is not null, somebody already started reconnection task - some kind of race condition
-                                            Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");
-                                            _currentReconnectionTask = runningReconnect;
-                                        }
-                                    }
-                                    else
-                                    {
-                                        callDisconnect = true;
-                                    }
-                                }
-                                if (callDisconnect && beforeDisconnect != null)
-                                {
-                                    beforeDisconnect();
-                                }
-                            }
-                            else
-                            {
-                                if (beforeDisconnect != null)
-                                {
-                                    beforeDisconnect();
-                                }
-                                OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
-                            }
-                        } // ValidateSNIConnection
-                    } // sessionRecoverySupported
-                } // connectRetryCount>0
-            }
-            else
-            { // runningReconnect = null
-                if (beforeDisconnect != null)
-                {
-                    beforeDisconnect();
-                }
-            }
-            return runningReconnect;
-        }
-
-        // this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request
-        partial void RepairInnerConnection()
-        {
-            WaitForPendingReconnection();
-            if (_connectRetryCount == 0)
-            {
-                return;
-            }
-            SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds;
-            if (tdsConn != null)
-            {
-                tdsConn.ValidateConnectionForExecute(null);
-                tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this);
-            }
-        }
-
-        private void WaitForPendingReconnection()
-        {
-            Task reconnectTask = _currentReconnectionTask;
-            if (reconnectTask != null && !reconnectTask.IsCompleted)
-            {
-                AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false);
-            }
-        }
-
-        private void CancelOpenAndWait()
-        {
-            // copy from member to avoid changes by background thread
-            var completion = _currentCompletion;
-            if (completion != null)
-            {
-                completion.Item1.TrySetCanceled();
-                ((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne();
-            }
-            Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source");
-        }
-
-        public override Task OpenAsync(CancellationToken cancellationToken)
-        {
-            Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this);
-
-            PrepareStatisticsForNewConnection();
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                System.Transactions.Transaction transaction = ADP.GetCurrentTransaction();
-                TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(transaction);
-                TaskCompletionSource<object> result = new TaskCompletionSource<object>();
-
-                if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) ||
-                    s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection))
-                {
-                    result.Task.ContinueWith((t) =>
-                    {
-                        if (t.Exception != null)
-                        {
-                            s_diagnosticListener.WriteConnectionOpenError(operationId, this, t.Exception);
-                        }
-                        else
-                        {
-                            s_diagnosticListener.WriteConnectionOpenAfter(operationId, this);
-                        }
-                    }, TaskScheduler.Default);
-                }
-
-                if (cancellationToken.IsCancellationRequested)
-                {
-                    result.SetCanceled();
-                    return result.Task;
-                }
-
-
-                bool completed;
-
-                try
-                {
-                    completed = TryOpen(completion);
-                }
-                catch (Exception e)
-                {
-                    s_diagnosticListener.WriteConnectionOpenError(operationId, this, e);
-                    result.SetException(e);
-                    return result.Task;
-                }
-
-                if (completed)
-                {
-                    result.SetResult(null);
-                }
-                else
-                {
-                    CancellationTokenRegistration registration = default;
-                    if (cancellationToken.CanBeCanceled)
-                    {
-                        registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion);
-                    }
-                    OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration);
-                    _currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task);
-                    completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default);
-                    return result.Task;
-                }
-
-                return result.Task;
-            }
-            catch (Exception ex)
-            {
-                s_diagnosticListener.WriteConnectionOpenError(operationId, this, ex);
-                throw;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public override DataTable GetSchema()
-        {
-            return GetSchema(DbMetaDataCollectionNames.MetaDataCollections, null);
-        }
-
-        public override DataTable GetSchema(string collectionName)
-        {
-            return GetSchema(collectionName, null);
-        }
-
-        public override DataTable GetSchema(string collectionName, string[] restrictionValues)
-        {
-            return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues);
-        }
-
-        private class OpenAsyncRetry
-        {
-            private readonly SqlConnection _parent;
-            private readonly TaskCompletionSource<DbConnectionInternal> _retry;
-            private readonly TaskCompletionSource<object> _result;
-            private readonly CancellationTokenRegistration _registration;
-
-            public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration)
-            {
-                _parent = parent;
-                _retry = retry;
-                _result = result;
-                _registration = registration;
-            }
-
-            internal void Retry(Task<DbConnectionInternal> retryTask)
-            {
-                _registration.Dispose();
-                try
-                {
-                    SqlStatistics statistics = null;
-                    try
-                    {
-                        statistics = SqlStatistics.StartTimer(_parent.Statistics);
-
-                        if (retryTask.IsFaulted)
-                        {
-                            _parent.CloseInnerConnection();
-                            _parent._currentCompletion = null;
-                            _result.SetException(retryTask.Exception.InnerException);
-                        }
-                        else if (retryTask.IsCanceled)
-                        {
-                            _parent.CloseInnerConnection();
-                            _parent._currentCompletion = null;
-                            _result.SetCanceled();
-                        }
-                        else
-                        {
-                            bool result;
-                            // protect continuation from races with close and cancel
-                            lock (_parent.InnerConnection)
-                            {
-                                result = _parent.TryOpen(_retry);
-                            }
-                            if (result)
-                            {
-                                _parent._currentCompletion = null;
-                                _result.SetResult(null);
-                            }
-                            else
-                            {
-                                _parent.CloseInnerConnection();
-                                _parent._currentCompletion = null;
-                                _result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending)));
-                            }
-                        }
-                    }
-                    finally
-                    {
-                        SqlStatistics.StopTimer(statistics);
-                    }
-                }
-                catch (Exception e)
-                {
-                    _parent.CloseInnerConnection();
-                    _parent._currentCompletion = null;
-                    _result.SetException(e);
-                }
-            }
-        }
-
-        private void PrepareStatisticsForNewConnection()
-        {
-            if (StatisticsEnabled ||
-                s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) ||
-                s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection))
-            {
-                if (null == _statistics)
-                {
-                    _statistics = new SqlStatistics();
-                }
-                else
-                {
-                    _statistics.ContinueOnNewConnection();
-                }
-            }
-        }
-
-        private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry)
-        {
-            SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
-
-            _applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0);
-
-            if (ForceNewConnection)
-            {
-                if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions))
-                {
-                    return false;
-                }
-            }
-            else
-            {
-                if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions))
-                {
-                    return false;
-                }
-            }
-            // does not require GC.KeepAlive(this) because of ReRegisterForFinalize below.
-
-            var tdsInnerConnection = (SqlInternalConnectionTds)InnerConnection;
-
-            Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");
-
-            if (!tdsInnerConnection.ConnectionOptions.Pooling)
-            {
-                // For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles
-                GC.ReRegisterForFinalize(this);
-            }
-
-            // The _statistics can change with StatisticsEnabled. Copying to a local variable before checking for a null value.
-            SqlStatistics statistics = _statistics;
-            if (StatisticsEnabled ||
-                (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) && statistics != null))
-            {
-                ADP.TimerCurrent(out _statistics._openTimestamp);
-                tdsInnerConnection.Parser.Statistics = _statistics;
-            }
-            else
-            {
-                tdsInnerConnection.Parser.Statistics = null;
-                _statistics = null; // in case of previous Open/Close/reset_CollectStats sequence
-            }
-
-            return true;
-        }
-
-
-        //
-        // INTERNAL PROPERTIES
-        //
-
-        internal bool HasLocalTransaction
-        {
-            get
-            {
-                return GetOpenTdsConnection().HasLocalTransaction;
-            }
-        }
-
-        internal bool HasLocalTransactionFromAPI
-        {
-            get
-            {
-                Task reconnectTask = _currentReconnectionTask;
-                if (reconnectTask != null && !reconnectTask.IsCompleted)
-                {
-                    return false; //we will not go into reconnection if we are inside the transaction
-                }
-                return GetOpenTdsConnection().HasLocalTransactionFromAPI;
-            }
-        }
-
-
-        internal bool IsKatmaiOrNewer
-        {
-            get
-            {
-                if (_currentReconnectionTask != null)
-                { // holds true even if task is completed
-                    return true; // if CR is enabled, connection, if established, will be Katmai+
-                }
-                return GetOpenTdsConnection().IsKatmaiOrNewer;
-            }
-        }
-
-        internal TdsParser Parser
-        {
-            get
-            {
-                SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection();
-                return tdsConnection.Parser;
-            }
-        }
-
-
-        //
-        // INTERNAL METHODS
-        //
-
-        internal void ValidateConnectionForExecute(string method, SqlCommand command)
-        {
-            Task asyncWaitingForReconnection = _asyncWaitingForReconnection;
-            if (asyncWaitingForReconnection != null)
-            {
-                if (!asyncWaitingForReconnection.IsCompleted)
-                {
-                    throw SQL.MARSUnspportedOnConnection();
-                }
-                else
-                {
-                    Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection);
-                }
-            }
-            if (_currentReconnectionTask != null)
-            {
-                Task currentReconnectionTask = _currentReconnectionTask;
-                if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted)
-                {
-                    return; // execution will wait for this task later
-                }
-            }
-            SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method);
-            innerConnection.ValidateConnectionForExecute(command);
-        }
-
-        // Surround name in brackets and then escape any end bracket to protect against SQL Injection.
-        // NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well
-        // as native OleDb and Odbc.
-        internal static string FixupDatabaseTransactionName(string name)
-        {
-            if (!string.IsNullOrEmpty(name))
-            {
-                return SqlServerEscapeHelper.EscapeIdentifier(name);
-            }
-            else
-            {
-                return name;
-            }
-        }
-
-        // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
-        // The close action also supports being run asynchronously
-        internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
-        {
-            Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!");
-
-
-            if (breakConnection && (ConnectionState.Open == State))
-            {
-                if (wrapCloseInAction != null)
-                {
-                    int capturedCloseCount = _closeCount;
-
-                    Action closeAction = () =>
-                    {
-                        if (capturedCloseCount == _closeCount)
-                        {
-                            Close();
-                        }
-                    };
-
-                    wrapCloseInAction(closeAction);
-                }
-                else
-                {
-                    Close();
-                }
-            }
-
-            if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
-            {
-                // It is an error, and should be thrown.  Class of TdsEnums.MIN_ERROR_CLASS or above is an error,
-                // below TdsEnums.MIN_ERROR_CLASS denotes an info message.
-                throw exception;
-            }
-            else
-            {
-                // If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler
-                this.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
-            }
-        }
-
-        //
-        // PRIVATE METHODS
-        //
-
-
-        internal SqlInternalConnectionTds GetOpenTdsConnection()
-        {
-            SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
-            if (null == innerConnection)
-            {
-                throw ADP.ClosedConnectionError();
-            }
-            return innerConnection;
-        }
-
-        internal SqlInternalConnectionTds GetOpenTdsConnection(string method)
-        {
-            SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
-            if (null == innerConnection)
-            {
-                throw ADP.OpenConnectionRequired(method, InnerConnection.State);
-            }
-            return innerConnection;
-        }
-
-        internal void OnInfoMessage(SqlInfoMessageEventArgs imevent)
-        {
-            bool notified;
-            OnInfoMessage(imevent, out notified);
-        }
-
-        internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified)
-        {
-            SqlInfoMessageEventHandler handler = InfoMessage;
-            if (null != handler)
-            {
-                notified = true;
-                try
-                {
-                    handler(this, imevent);
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableOrSecurityExceptionType(e))
-                    {
-                        throw;
-                    }
-                }
-            }
-            else
-            {
-                notified = false;
-            }
-        }
-
-
-        public static void ChangePassword(string connectionString, string newPassword)
-        {
-            if (string.IsNullOrEmpty(connectionString))
-            {
-                throw SQL.ChangePasswordArgumentMissing(nameof(newPassword));
-            }
-            if (string.IsNullOrEmpty(newPassword))
-            {
-                throw SQL.ChangePasswordArgumentMissing(nameof(newPassword));
-            }
-            if (TdsEnums.MAXLEN_NEWPASSWORD < newPassword.Length)
-            {
-                throw ADP.InvalidArgumentLength(nameof(newPassword), TdsEnums.MAXLEN_NEWPASSWORD);
-            }
-
-            SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential: null, accessToken: null);
-
-            SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
-            if (connectionOptions.IntegratedSecurity)
-            {
-                throw SQL.ChangePasswordConflictsWithSSPI();
-            }
-            if (!string.IsNullOrEmpty(connectionOptions.AttachDBFilename))
-            {
-                throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
-            }
-
-            ChangePassword(connectionString, connectionOptions, null, newPassword, null);
-        }
-
-        public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword)
-        {
-            if (string.IsNullOrEmpty(connectionString))
-            {
-                throw SQL.ChangePasswordArgumentMissing(nameof(connectionString));
-            }
-
-            // check credential; not necessary to check the length of password in credential as the check is done by SqlCredential class
-            if (credential == null)
-            {
-                throw SQL.ChangePasswordArgumentMissing(nameof(credential));
-            }
-
-            if (newSecurePassword == null || newSecurePassword.Length == 0)
-            {
-                throw SQL.ChangePasswordArgumentMissing(nameof(newSecurePassword));
-            }
-
-            if (!newSecurePassword.IsReadOnly())
-            {
-                throw ADP.MustBeReadOnly(nameof(newSecurePassword));
-            }
-
-            if (TdsEnums.MAXLEN_NEWPASSWORD < newSecurePassword.Length)
-            {
-                throw ADP.InvalidArgumentLength(nameof(newSecurePassword), TdsEnums.MAXLEN_NEWPASSWORD);
-            }
-
-            SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null);
-
-            SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
-
-            // Check for connection string values incompatible with SqlCredential
-            if (!string.IsNullOrEmpty(connectionOptions.UserID) || !string.IsNullOrEmpty(connectionOptions.Password))
-            {
-                throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
-            }
-
-            if (connectionOptions.IntegratedSecurity)
-            {
-                throw SQL.ChangePasswordConflictsWithSSPI();
-            }
-
-            if (!string.IsNullOrEmpty(connectionOptions.AttachDBFilename))
-            {
-                throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
-            }
-
-            ChangePassword(connectionString, connectionOptions, credential, null, newSecurePassword);
-        }
-
-        private static void ChangePassword(string connectionString, SqlConnectionString connectionOptions, SqlCredential credential, string newPassword, SecureString newSecurePassword)
-        {
-            // note: This is the only case where we directly construct the internal connection, passing in the new password.
-            // Normally we would simply create a regular connection and open it, but there is no other way to pass the
-            // new password down to the constructor. This would have an unwanted impact on the connection pool.
-            SqlInternalConnectionTds con = null;
-            try
-            {
-                con = new SqlInternalConnectionTds(null, connectionOptions, credential, null, newPassword, newSecurePassword, false);
-            }
-            finally
-            {
-                if (con != null)
-                    con.Dispose();
-            }
-            SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null);
-
-            SqlConnectionFactory.SingletonInstance.ClearPool(key);
-        }
-
-        //
-        // SQL DEBUGGING SUPPORT
-        //
-
-        // this only happens once per connection
-        // SxS: using named file mapping APIs
-
-        internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag)
-        {
-            // Connection exists,  schedule removal, will be added to ref collection after calling ValidateAndReconnect
-            outerTask = outerTask.ContinueWith(task =>
-            {
-                RemoveWeakReference(value);
-                return task;
-            }, TaskScheduler.Default).Unwrap();
-        }
-
-
-        public void ResetStatistics()
-        {
-            if (null != Statistics)
-            {
-                Statistics.Reset();
-                if (ConnectionState.Open == State)
-                {
-                    // update timestamp;
-                    ADP.TimerCurrent(out _statistics._openTimestamp);
-                }
-            }
-        }
-
-        public IDictionary RetrieveStatistics()
-        {
-            if (null != Statistics)
-            {
-                UpdateStatistics();
-                return Statistics.GetDictionary();
-            }
-            else
-            {
-                return new SqlStatistics().GetDictionary();
-            }
-        }
-
-        private void UpdateStatistics()
-        {
-            if (ConnectionState.Open == State)
-            {
-                // update timestamp
-                ADP.TimerCurrent(out _statistics._closeTimestamp);
-            }
-            // delegate the rest of the work to the SqlStatistics class
-            Statistics.UpdateStatistics();
-        }
-
-        object ICloneable.Clone() => new SqlConnection(this);
-
-        private void CopyFrom(SqlConnection connection)
-        {
-            ADP.CheckArgumentNull(connection, nameof(connection));
-            _userConnectionOptions = connection.UserConnectionOptions;
-            _poolGroup = connection.PoolGroup;
-
-            if (DbConnectionClosedNeverOpened.SingletonInstance == connection._innerConnection)
-            {
-                _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
-            }
-            else
-            {
-                _innerConnection = DbConnectionClosedPreviouslyOpened.SingletonInstance;
-            }
-        }
-
-        // UDT SUPPORT
-        private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError)
-        {
-            Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !");
-            if (string.Equals(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase))
-            {
-                asmRef.Version = TypeSystemAssemblyVersion;
-            }
-            try
-            {
-                return Assembly.Load(asmRef);
-            }
-            catch (Exception e)
-            {
-                if (throwOnError || !ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-                else
-                {
-                    return null;
-                };
-            }
-        }
-
-        internal void CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, bool fThrow)
-        {
-            if (metaData.udt?.Type == null)
-            { // If null, we have not obtained extended info.
-                Debug.Assert(!string.IsNullOrEmpty(metaData.udt?.AssemblyQualifiedName), "Unexpected state on GetUDTInfo");
-                // Parameter throwOnError determines whether exception from Assembly.Load is thrown.
-                metaData.udt.Type =
-                    Type.GetType(typeName: metaData.udt.AssemblyQualifiedName, assemblyResolver: asmRef => ResolveTypeAssembly(asmRef, fThrow), typeResolver: null, throwOnError: fThrow);
-
-                if (fThrow && metaData.udt.Type == null)
-                {
-                    throw SQL.UDTUnexpectedResult(metaData.udt.AssemblyQualifiedName);
-                }
-            }
-        }
-
-        internal object GetUdtValue(object value, SqlMetaDataPriv metaData, bool returnDBNull)
-        {
-            if (returnDBNull && ADP.IsNull(value))
-            {
-                return DBNull.Value;
-            }
-
-            object o = null;
-
-            // Since the serializer doesn't handle nulls...
-            if (ADP.IsNull(value))
-            {
-                Type t = metaData.udt?.Type;
-                Debug.Assert(t != null, "Unexpected null of udtType on GetUdtValue!");
-                o = t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, Array.Empty<object>(), CultureInfo.InvariantCulture);
-                Debug.Assert(o != null);
-                return o;
-            }
-            else
-            {
-
-                MemoryStream stm = new MemoryStream((byte[])value);
-
-                o = SerializationHelperSql9.Deserialize(stm, metaData.udt?.Type);
-
-                Debug.Assert(o != null, "object could NOT be created");
-                return o;
-            }
-        }
-
-        internal byte[] GetBytes(object o)
-        {
-            Format format = Format.Native;
-            return GetBytes(o, out format, out int maxSize);
-        }
-
-        internal byte[] GetBytes(object o, out Format format, out int maxSize)
-        {
-            SqlUdtInfo attr = GetInfoFromType(o.GetType());
-            maxSize = attr.MaxByteSize;
-            format = attr.SerializationFormat;
-
-            if (maxSize < -1 || maxSize >= ushort.MaxValue)
-            {
-                throw new InvalidOperationException(o.GetType() + ": invalid Size");
-            }
-
-            byte[] retval;
-
-            using (MemoryStream stm = new MemoryStream(maxSize < 0 ? 0 : maxSize))
-            {
-                SerializationHelperSql9.Serialize(stm, o);
-                retval = stm.ToArray();
-            }
-            return retval;
-        }
-
-        private SqlUdtInfo GetInfoFromType(Type t)
-        {
-            Debug.Assert(t != null, "Type object cant be NULL");
-            Type orig = t;
-            do
-            {
-                SqlUdtInfo attr = SqlUdtInfo.TryGetFromType(t);
-                if (attr != null)
-                {
-                    return attr;
-                }
-                else
-                {
-                    t = t.BaseType;
-                }
-            }
-            while (t != null);
-
-            throw SQL.UDTInvalidSqlType(orig.AssemblyQualifiedName);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs
deleted file mode 100644 (file)
index 56701b2..0000000
+++ /dev/null
@@ -1,284 +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.Specialized;
-using System.Configuration;
-using System.Data.Common;
-using System.Data.ProviderBase;
-using System.Diagnostics;
-using System.IO;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlConnectionFactory : DbConnectionFactory
-    {
-        private SqlConnectionFactory() : base() { }
-
-        public static readonly SqlConnectionFactory SingletonInstance = new SqlConnectionFactory();
-
-        public override DbProviderFactory ProviderFactory
-        {
-            get
-            {
-                return SqlClientFactory.Instance;
-            }
-        }
-
-        protected override DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
-        {
-            return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection, userOptions: null);
-        }
-
-        protected override DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
-        {
-            SqlConnectionString opt = (SqlConnectionString)options;
-            SqlConnectionPoolKey key = (SqlConnectionPoolKey)poolKey;
-            SqlInternalConnection result = null;
-            SessionData recoverySessionData = null;
-
-            SqlConnection sqlOwningConnection = (SqlConnection)owningConnection;
-            bool applyTransientFaultHandling = sqlOwningConnection != null ? sqlOwningConnection._applyTransientFaultHandling : false;
-
-            SqlConnectionString userOpt = null;
-            if (userOptions != null)
-            {
-                userOpt = (SqlConnectionString)userOptions;
-            }
-            else if (sqlOwningConnection != null)
-            {
-                userOpt = (SqlConnectionString)(sqlOwningConnection.UserConnectionOptions);
-            }
-
-            if (sqlOwningConnection != null)
-            {
-                recoverySessionData = sqlOwningConnection._recoverySessionData;
-            }
-
-            bool redirectedUserInstance = false;
-            DbConnectionPoolIdentity identity = null;
-
-            // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security.
-            // Used by notifications.
-            if (opt.IntegratedSecurity)
-            {
-                if (pool != null)
-                {
-                    identity = pool.Identity;
-                }
-                else
-                {
-                    identity = DbConnectionPoolIdentity.GetCurrent();
-                }
-            }
-
-            // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES
-            // If "user instance=true" is in the connection string, we're using SSE user instances
-            if (opt.UserInstance)
-            {
-                // opt.DataSource is used to create the SSE connection
-                redirectedUserInstance = true;
-                string instanceName;
-
-                if ((null == pool) ||
-                     (null != pool && pool.Count <= 0))
-                { // Non-pooled or pooled and no connections in the pool.
-                    SqlInternalConnectionTds sseConnection = null;
-                    try
-                    {
-                        // We throw an exception in case of a failure
-                        // NOTE: Cloning connection option opt to set 'UserInstance=True' and 'Enlist=False'
-                        //       This first connection is established to SqlExpress to get the instance name
-                        //       of the UserInstance.
-                        SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, userInstance: true, setEnlistValue: false);
-                        sseConnection = new SqlInternalConnectionTds(identity, sseopt, key.Credential, null, "", null, false, applyTransientFaultHandling: applyTransientFaultHandling);
-                        // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance.
-                        instanceName = sseConnection.InstanceName;
-
-                        if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal))
-                        {
-                            throw SQL.NonLocalSSEInstance();
-                        }
-
-                        if (null != pool)
-                        { // Pooled connection - cache result
-                            SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
-                            // No lock since we are already in creation mutex
-                            providerInfo.InstanceName = instanceName;
-                        }
-                    }
-                    finally
-                    {
-                        if (null != sseConnection)
-                        {
-                            sseConnection.Dispose();
-                        }
-                    }
-                }
-                else
-                { // Cached info from pool.
-                    SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
-                    // No lock since we are already in creation mutex
-                    instanceName = providerInfo.InstanceName;
-                }
-
-                // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was
-                //       retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'.
-                // options immutable - stored in global hash - don't modify
-                opt = new SqlConnectionString(opt, instanceName, userInstance: false, setEnlistValue: null);
-                poolGroupProviderInfo = null; // null so we do not pass to constructor below...
-            }
-            result = new SqlInternalConnectionTds(identity, opt, key.Credential, poolGroupProviderInfo, "", null, redirectedUserInstance, userOpt, recoverySessionData, applyTransientFaultHandling: applyTransientFaultHandling, key.AccessToken);
-            return result;
-        }
-
-        protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous)
-        {
-            Debug.Assert(!string.IsNullOrEmpty(connectionString), "empty connectionString");
-            SqlConnectionString result = new SqlConnectionString(connectionString);
-            return result;
-        }
-
-        internal override DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions)
-        {
-            DbConnectionPoolProviderInfo providerInfo = null;
-
-            if (((SqlConnectionString)connectionOptions).UserInstance)
-            {
-                providerInfo = new SqlConnectionPoolProviderInfo();
-            }
-
-            return providerInfo;
-        }
-
-        protected override DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions connectionOptions)
-        {
-            SqlConnectionString opt = (SqlConnectionString)connectionOptions;
-
-            DbConnectionPoolGroupOptions poolingOptions = null;
-
-            if (opt.Pooling)
-            {    // never pool context connections.
-                int connectionTimeout = opt.ConnectTimeout;
-
-                if ((0 < connectionTimeout) && (connectionTimeout < int.MaxValue / 1000))
-                    connectionTimeout *= 1000;
-                else if (connectionTimeout >= int.MaxValue / 1000)
-                    connectionTimeout = int.MaxValue;
-
-                poolingOptions = new DbConnectionPoolGroupOptions(
-                                                    opt.IntegratedSecurity,
-                                                    opt.MinPoolSize,
-                                                    opt.MaxPoolSize,
-                                                    connectionTimeout,
-                                                    opt.LoadBalanceTimeout,
-                                                    opt.Enlist);
-            }
-            return poolingOptions;
-        }
-
-
-        internal override DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
-        {
-            return new SqlConnectionPoolGroupProviderInfo((SqlConnectionString)connectionOptions);
-        }
-
-
-        internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key)
-        {
-            SqlConnectionString connectionOptions = (SqlConnectionString)SingletonInstance.FindConnectionOptions(key);
-            if (null == connectionOptions)
-            {
-                connectionOptions = new SqlConnectionString(key.ConnectionString);
-            }
-            if (connectionOptions.IsEmpty)
-            {
-                throw ADP.NoConnectionString();
-            }
-            return connectionOptions;
-        }
-
-
-        internal override DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection)
-        {
-            SqlConnection c = (connection as SqlConnection);
-            if (null != c)
-            {
-                return c.PoolGroup;
-            }
-            return null;
-        }
-
-        internal override DbConnectionInternal GetInnerConnection(DbConnection connection)
-        {
-            SqlConnection c = (connection as SqlConnection);
-            if (null != c)
-            {
-                return c.InnerConnection;
-            }
-            return null;
-        }
-
-
-        internal override void PermissionDemand(DbConnection outerConnection)
-        {
-            SqlConnection c = (outerConnection as SqlConnection);
-            if (null != c)
-            {
-                c.PermissionDemand();
-            }
-        }
-
-        internal override void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup)
-        {
-            SqlConnection c = (outerConnection as SqlConnection);
-            if (null != c)
-            {
-                c.PoolGroup = poolGroup;
-            }
-        }
-
-        internal override void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to)
-        {
-            SqlConnection c = (owningObject as SqlConnection);
-            if (null != c)
-            {
-                c.SetInnerConnectionEvent(to);
-            }
-        }
-
-        internal override bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from)
-        {
-            SqlConnection c = (owningObject as SqlConnection);
-            if (null != c)
-            {
-                return c.SetInnerConnectionFrom(to, from);
-            }
-            return false;
-        }
-
-        internal override void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to)
-        {
-            SqlConnection c = (owningObject as SqlConnection);
-            if (null != c)
-            {
-                c.SetInnerConnectionTo(to);
-            }
-        }
-
-        protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory)
-        {
-            Debug.Assert(internalConnection != null, "internalConnection may not be null.");
-
-            Stream xmlStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.SqlClient.SqlMetaData.xml");
-            cacheMetaDataFactory = true;
-
-            Debug.Assert(xmlStream != null, nameof(xmlStream) + " may not be null.");
-
-            return new SqlMetaDataFactory(xmlStream,
-                                          internalConnection.ServerVersion,
-                                          internalConnection.ServerVersion);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs
deleted file mode 100644 (file)
index e34017e..0000000
+++ /dev/null
@@ -1,264 +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.
-
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-// In the .NET Framework version of the framework, this file is generated from ProviderBase\DbConnectionHelper.cs
-// #line 1 "e:\\fxdata\\src\\ndp\\fx\\src\\data\\system\\data\\providerbase\\dbconnectionhelper.cs"
-
-using System.Data.Common;
-using System.Data.ProviderBase;
-using System.Diagnostics;
-using System.Threading;
-using System.Transactions;
-
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlConnection : DbConnection
-    {
-        private static readonly DbConnectionFactory s_connectionFactory = SqlConnectionFactory.SingletonInstance;
-
-        private DbConnectionOptions _userConnectionOptions;
-        private DbConnectionPoolGroup _poolGroup;
-        private DbConnectionInternal _innerConnection;
-        private int _closeCount;
-
-
-        public SqlConnection() : base()
-        {
-            GC.SuppressFinalize(this);
-            _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
-        }
-
-        internal int CloseCount
-        {
-            get
-            {
-                return _closeCount;
-            }
-        }
-
-        internal DbConnectionFactory ConnectionFactory
-        {
-            get
-            {
-                return s_connectionFactory;
-            }
-        }
-
-        internal DbConnectionOptions ConnectionOptions
-        {
-            get
-            {
-                System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
-                return ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
-            }
-        }
-
-        private string ConnectionString_Get()
-        {
-            bool hidePassword = InnerConnection.ShouldHidePassword;
-            DbConnectionOptions connectionOptions = UserConnectionOptions;
-            return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : "");
-        }
-
-        private void ConnectionString_Set(DbConnectionPoolKey key)
-        {
-            DbConnectionOptions connectionOptions = null;
-            System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions);
-            DbConnectionInternal connectionInternal = InnerConnection;
-            bool flag = connectionInternal.AllowSetConnectionString;
-            if (flag)
-            {
-                flag = SetInnerConnectionFrom(DbConnectionClosedBusy.SingletonInstance, connectionInternal);
-                if (flag)
-                {
-                    _userConnectionOptions = connectionOptions;
-                    _poolGroup = poolGroup;
-                    _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
-                }
-            }
-            if (!flag)
-            {
-                throw ADP.OpenConnectionPropertySet(nameof(ConnectionString), connectionInternal.State);
-            }
-        }
-
-        internal DbConnectionInternal InnerConnection
-        {
-            get
-            {
-                return _innerConnection;
-            }
-        }
-
-        internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup
-        {
-            get
-            {
-                return _poolGroup;
-            }
-            set
-            {
-                Debug.Assert(null != value, "null poolGroup");
-                _poolGroup = value;
-            }
-        }
-
-
-        internal DbConnectionOptions UserConnectionOptions
-        {
-            get
-            {
-                return _userConnectionOptions;
-            }
-        }
-
-
-        internal void Abort(Exception e)
-        {
-            DbConnectionInternal innerConnection = _innerConnection;
-            if (ConnectionState.Open == innerConnection.State)
-            {
-                Interlocked.CompareExchange(ref _innerConnection, DbConnectionClosedPreviouslyOpened.SingletonInstance, innerConnection);
-                innerConnection.DoomThisConnection();
-            }
-        }
-
-        internal void AddWeakReference(object value, int tag)
-        {
-            InnerConnection.AddWeakReference(value, tag);
-        }
-
-        protected override DbCommand CreateDbCommand()
-        {
-            DbCommand command = null;
-            DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory;
-            command = providerFactory.CreateCommand();
-            command.Connection = this;
-            return command;
-        }
-
-
-        protected override void Dispose(bool disposing)
-        {
-            if (disposing)
-            {
-                _userConnectionOptions = null;
-                _poolGroup = null;
-                Close();
-            }
-            DisposeMe(disposing);
-            base.Dispose(disposing);
-        }
-
-        partial void RepairInnerConnection();
-
-        public override void EnlistTransaction(Transaction transaction)
-        {
-            // If we're currently enlisted in a transaction and we were called
-            // on the EnlistTransaction method (Whidbey) we're not allowed to
-            // enlist in a different transaction.
-
-            DbConnectionInternal innerConnection = InnerConnection;
-
-            // NOTE: since transaction enlistment involves round trips to the
-            // server, we don't want to lock here, we'll handle the race conditions
-            // elsewhere.
-            Transaction enlistedTransaction = innerConnection.EnlistedTransaction;
-            if (enlistedTransaction != null)
-            {
-                // Allow calling enlist if already enlisted (no-op)
-                if (enlistedTransaction.Equals(transaction))
-                {
-                    return;
-                }
-
-                // Allow enlisting in a different transaction if the enlisted transaction has completed.
-                if (enlistedTransaction.TransactionInformation.Status == TransactionStatus.Active)
-                {
-                    throw ADP.TransactionPresent();
-                }
-            }
-            RepairInnerConnection();
-            InnerConnection.EnlistTransaction(transaction);
-
-            // NOTE: If this outer connection were to be GC'd while we're
-            // enlisting, the pooler would attempt to reclaim the inner connection
-            // while we're attempting to enlist; not sure how likely that is but
-            // we should consider a GC.KeepAlive(this) here.
-            GC.KeepAlive(this);
-        }
-
-        internal void NotifyWeakReference(int message)
-        {
-            InnerConnection.NotifyWeakReference(message);
-        }
-
-        internal void PermissionDemand()
-        {
-            Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting");
-            System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
-            DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
-            if ((null == connectionOptions) || connectionOptions.IsEmpty)
-            {
-                throw ADP.NoConnectionString();
-            }
-            DbConnectionOptions userConnectionOptions = UserConnectionOptions;
-            Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions");
-        }
-
-        internal void RemoveWeakReference(object value)
-        {
-            InnerConnection.RemoveWeakReference(value);
-        }
-
-        internal void SetInnerConnectionEvent(DbConnectionInternal to)
-        {
-            Debug.Assert(null != _innerConnection, "null InnerConnection");
-            Debug.Assert(null != to, "to null InnerConnection");
-
-            ConnectionState originalState = _innerConnection.State & ConnectionState.Open;
-            ConnectionState currentState = to.State & ConnectionState.Open;
-            if ((originalState != currentState) && (ConnectionState.Closed == currentState))
-            {
-                unchecked { _closeCount++; }
-            }
-
-            _innerConnection = to;
-            if (ConnectionState.Closed == originalState && ConnectionState.Open == currentState)
-            {
-                OnStateChange(DbConnectionInternal.StateChangeOpen);
-            }
-            else if (ConnectionState.Open == originalState && ConnectionState.Closed == currentState)
-            {
-                OnStateChange(DbConnectionInternal.StateChangeClosed);
-            }
-            else
-            {
-                Debug.Fail("unexpected state switch");
-                if (originalState != currentState)
-                {
-                    OnStateChange(new StateChangeEventArgs(originalState, currentState));
-                }
-            }
-        }
-
-        internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from)
-        {
-            Debug.Assert(null != _innerConnection, "null InnerConnection");
-            Debug.Assert(null != from, "from null InnerConnection");
-            Debug.Assert(null != to, "to null InnerConnection");
-            bool result = (from == Interlocked.CompareExchange<DbConnectionInternal>(ref _innerConnection, to, from));
-            return result;
-        }
-
-        internal void SetInnerConnectionTo(DbConnectionInternal to)
-        {
-            Debug.Assert(null != _innerConnection, "null InnerConnection");
-            Debug.Assert(null != to, "to null InnerConnection");
-            _innerConnection = to;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs
deleted file mode 100644 (file)
index b9eba3d..0000000
+++ /dev/null
@@ -1,94 +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.Data.Common;
-using System.Data.ProviderBase;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlConnectionPoolGroupProviderInfo : DbConnectionPoolGroupProviderInfo
-    {
-        private string _alias;
-        private string _failoverPartner;
-        private bool _useFailoverPartner;
-
-        internal SqlConnectionPoolGroupProviderInfo(SqlConnectionString connectionOptions)
-        {
-            // This is for the case where the user specified the failover partner
-            // in the connection string and we have not yet connected to get the
-            // env change.
-            _failoverPartner = connectionOptions.FailoverPartner;
-
-            if (string.IsNullOrEmpty(_failoverPartner))
-            {
-                _failoverPartner = null;
-            }
-        }
-
-        internal string FailoverPartner
-        {
-            get
-            {
-                return _failoverPartner;
-            }
-        }
-
-        internal bool UseFailoverPartner
-        {
-            get
-            {
-                return _useFailoverPartner;
-            }
-        }
-
-        internal void AliasCheck(string server)
-        {
-            if (_alias != server)
-            {
-                lock (this)
-                {
-                    if (null == _alias)
-                    {
-                        _alias = server;
-                    }
-                    else if (_alias != server)
-                    {
-                        base.PoolGroup.Clear();
-                        _alias = server;
-                    }
-                }
-            }
-        }
-
-
-        internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFailoverPartner, SqlConnectionString userConnectionOptions, string actualFailoverPartner)
-        {
-            if (UseFailoverPartner != actualUseFailoverPartner)
-            {
-                base.PoolGroup.Clear();
-                _useFailoverPartner = actualUseFailoverPartner;
-            }
-            // Only construct a new permission set when we're connecting to the
-            // primary data source, not the failover partner.
-            if (!_useFailoverPartner && _failoverPartner != actualFailoverPartner)
-            {
-                // NOTE: we optimistically generate the permission set to keep
-                //       lock short, but we only do this when we get a new
-                //       failover partner.
-
-                lock (this)
-                {
-                    if (_failoverPartner != actualFailoverPartner)
-                    {
-                        _failoverPartner = actualFailoverPartner;
-                    }
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolKey.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolKey.cs
deleted file mode 100644 (file)
index 65c8440..0000000
+++ /dev/null
@@ -1,97 +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.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    // SqlConnectionPoolKey: Implementation of a key to connection pool groups for specifically to be used for SqlConnection
-    //  Connection string and SqlCredential are used as a key
-    internal class SqlConnectionPoolKey : DbConnectionPoolKey
-    {
-        private int _hashValue;
-        private readonly SqlCredential _credential;
-        private readonly string _accessToken;
-
-        internal SqlConnectionPoolKey(string connectionString, SqlCredential credential, string accessToken) : base(connectionString)
-        {
-            Debug.Assert(_credential == null || _accessToken == null, "Credential and AccessToken can't have the value at the same time.");
-            _credential = credential;
-            _accessToken = accessToken;
-            CalculateHashCode();
-        }
-
-        private SqlConnectionPoolKey(SqlConnectionPoolKey key) : base(key)
-        {
-            _credential = key.Credential;
-            _accessToken = key.AccessToken;
-            CalculateHashCode();
-        }
-
-        public override object Clone()
-        {
-            return new SqlConnectionPoolKey(this);
-        }
-
-        internal override string ConnectionString
-        {
-            get
-            {
-                return base.ConnectionString;
-            }
-
-            set
-            {
-                base.ConnectionString = value;
-                CalculateHashCode();
-            }
-        }
-
-        internal SqlCredential Credential => _credential;
-
-        internal string AccessToken
-        {
-            get
-            {
-                return _accessToken;
-            }
-        }
-
-        public override bool Equals(object obj)
-        {
-            SqlConnectionPoolKey key = obj as SqlConnectionPoolKey;
-            return (key != null && _credential == key._credential && ConnectionString == key.ConnectionString && object.ReferenceEquals(_accessToken, key._accessToken));
-        }
-
-        public override int GetHashCode()
-        {
-            return _hashValue;
-        }
-
-        private void CalculateHashCode()
-        {
-            _hashValue = base.GetHashCode();
-
-            if (_credential != null)
-            {
-                unchecked
-                {
-                    _hashValue = _hashValue * 17 + _credential.GetHashCode();
-                }
-            }
-            else if (_accessToken != null)
-            {
-                unchecked
-                {
-                    _hashValue = _hashValue * 17 + _accessToken.GetHashCode();
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolProviderInfo.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionPoolProviderInfo.cs
deleted file mode 100644 (file)
index 0dfa316..0000000
+++ /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.Data.ProviderBase;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlConnectionPoolProviderInfo : DbConnectionPoolProviderInfo
-    {
-        private string _instanceName;
-
-        internal string InstanceName
-        {
-            get
-            {
-                return _instanceName;
-            }
-            set
-            {
-                _instanceName = value;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.NetCoreApp.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.NetCoreApp.cs
deleted file mode 100644 (file)
index bde3cef..0000000
+++ /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.Data.Common;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class SqlConnectionString : DbConnectionOptions
-    {
-        internal static partial class DEFAULT
-        {
-            internal const PoolBlockingPeriod PoolBlockingPeriod = DbConnectionStringDefaults.PoolBlockingPeriod;
-        }
-
-        private readonly PoolBlockingPeriod _poolBlockingPeriod;
-
-        internal PoolBlockingPeriod PoolBlockingPeriod { get { return _poolBlockingPeriod; } }
-
-        internal System.Data.SqlClient.PoolBlockingPeriod ConvertValueToPoolBlockingPeriod()
-        {
-            string value;
-            if (!TryGetParsetableValue(KEY.PoolBlockingPeriod, out value))
-            {
-                return DEFAULT.PoolBlockingPeriod;
-            }
-
-            try
-            {
-                return DbConnectionStringBuilderUtil.ConvertToPoolBlockingPeriod(KEY.PoolBlockingPeriod, value);
-            }
-            catch (Exception e) when (e is FormatException || e is OverflowException)
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.PoolBlockingPeriod, e);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs
deleted file mode 100644 (file)
index b7bd4a1..0000000
+++ /dev/null
@@ -1,628 +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.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Threading;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class SqlConnectionString : DbConnectionOptions
-    {
-        // instances of this class are intended to be immutable, i.e readonly
-        // used by pooling classes so it is much easier to verify correctness
-        // when not worried about the class being modified during execution
-
-        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 Connect_Timeout = ADP.DefaultConnectionTimeout;
-            internal const string Current_Language = "";
-            internal const string Data_Source = "";
-            internal const bool Encrypt = false;
-            internal const bool Enlist = true;
-            internal const string FailoverPartner = "";
-            internal const string Initial_Catalog = "";
-            internal const bool Integrated_Security = false;
-            internal const int Load_Balance_Timeout = 0; // default of 0 means don't use
-            internal const bool MARS = false;
-            internal const int Max_Pool_Size = 100;
-            internal const int Min_Pool_Size = 0;
-            internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
-            internal const int Packet_Size = 8000;
-            internal const string Password = "";
-            internal const bool Persist_Security_Info = false;
-            internal const bool Pooling = true;
-            internal const bool TrustServerCertificate = false;
-            internal const string Type_System_Version = "";
-            internal const string User_ID = "";
-            internal const bool User_Instance = false;
-            internal const bool Replication = false;
-            internal const int Connect_Retry_Count = 1;
-            internal const int Connect_Retry_Interval = 10;
-        }
-
-        // SqlConnection ConnectionString Options
-        // keys must be lowercase!
-        internal static class KEY
-        {
-            internal const string ApplicationIntent = "applicationintent";
-            internal const string Application_Name = "application name";
-            internal const string AsynchronousProcessing = "asynchronous processing";
-            internal const string AttachDBFilename = "attachdbfilename";
-#if NETCOREAPP
-            internal const string PoolBlockingPeriod = "poolblockingperiod";
-#endif
-            internal const string Connect_Timeout = "connect timeout";
-            internal const string Connection_Reset = "connection reset";
-            internal const string Context_Connection = "context connection";
-            internal const string Current_Language = "current language";
-            internal const string Data_Source = "data source";
-            internal const string Encrypt = "encrypt";
-            internal const string Enlist = "enlist";
-            internal const string FailoverPartner = "failover partner";
-            internal const string Initial_Catalog = "initial catalog";
-            internal const string Integrated_Security = "integrated security";
-            internal const string Load_Balance_Timeout = "load balance timeout";
-            internal const string MARS = "multipleactiveresultsets";
-            internal const string Max_Pool_Size = "max pool size";
-            internal const string Min_Pool_Size = "min pool size";
-            internal const string MultiSubnetFailover = "multisubnetfailover";
-            internal const string Network_Library = "network library";
-            internal const string Packet_Size = "packet size";
-            internal const string Password = "password";
-            internal const string Persist_Security_Info = "persist security info";
-            internal const string Pooling = "pooling";
-            internal const string TransactionBinding = "transaction binding";
-            internal const string TrustServerCertificate = "trustservercertificate";
-            internal const string Type_System_Version = "type system version";
-            internal const string User_ID = "user id";
-            internal const string User_Instance = "user instance";
-            internal const string Workstation_Id = "workstation id";
-            internal const string Replication = "replication";
-            internal const string Connect_Retry_Count = "connectretrycount";
-            internal const string Connect_Retry_Interval = "connectretryinterval";
-        }
-
-        // Constant for the number of duplicate options in the connection string
-
-        private static class SYNONYM
-        {
-            // application name
-            internal const string APP = "app";
-            internal const string Async = "async";
-            // attachDBFilename
-            internal const string EXTENDED_PROPERTIES = "extended properties";
-            internal const string INITIAL_FILE_NAME = "initial file name";
-            // connect timeout
-            internal const string CONNECTION_TIMEOUT = "connection timeout";
-            internal const string TIMEOUT = "timeout";
-            // current language
-            internal const string LANGUAGE = "language";
-            // data source
-            internal const string ADDR = "addr";
-            internal const string ADDRESS = "address";
-            internal const string SERVER = "server";
-            internal const string NETWORK_ADDRESS = "network address";
-            // initial catalog
-            internal const string DATABASE = "database";
-            // integrated security
-            internal const string TRUSTED_CONNECTION = "trusted_connection";
-            // load balance timeout
-            internal const string Connection_Lifetime = "connection lifetime";
-            // network library
-            internal const string NET = "net";
-            internal const string NETWORK = "network";
-            // password
-            internal const string Pwd = "pwd";
-            // persist security info
-            internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
-            // user id
-            internal const string UID = "uid";
-            internal const string User = "user";
-            // workstation id
-            internal const string WSID = "wsid";
-            // make sure to update SynonymCount value below when adding or removing synonyms
-        }
-
-        internal const int SynonymCount = 18;
-        internal const int DeprecatedSynonymCount = 3;
-
-
-        internal enum TypeSystem
-        {
-            Latest = 2008,
-            SQLServer2000 = 2000,
-            SQLServer2005 = 2005,
-            SQLServer2008 = 2008,
-            SQLServer2012 = 2012,
-        }
-
-        internal static class TYPESYSTEMVERSION
-        {
-            internal const string Latest = "Latest";
-            internal const string SQL_Server_2000 = "SQL Server 2000";
-            internal const string SQL_Server_2005 = "SQL Server 2005";
-            internal const string SQL_Server_2008 = "SQL Server 2008";
-            internal const string SQL_Server_2012 = "SQL Server 2012";
-        }
-
-        internal enum TransactionBindingEnum
-        {
-            ImplicitUnbind,
-            ExplicitUnbind
-        }
-
-        internal static class TRANSACTIONBINDING
-        {
-            internal const string ImplicitUnbind = "Implicit Unbind";
-            internal const string ExplicitUnbind = "Explicit Unbind";
-        }
-
-        private static Dictionary<string, string> s_sqlClientSynonyms;
-
-        private readonly bool _integratedSecurity;
-
-        private readonly bool _encrypt;
-        private readonly bool _trustServerCertificate;
-        private readonly bool _enlist;
-        private readonly bool _mars;
-        private readonly bool _persistSecurityInfo;
-        private readonly bool _pooling;
-        private readonly bool _replication;
-        private readonly bool _userInstance;
-        private readonly bool _multiSubnetFailover;
-
-        private readonly int _connectTimeout;
-        private readonly int _loadBalanceTimeout;
-        private readonly int _maxPoolSize;
-        private readonly int _minPoolSize;
-        private readonly int _packetSize;
-        private readonly int _connectRetryCount;
-        private readonly int _connectRetryInterval;
-
-        private readonly ApplicationIntent _applicationIntent;
-        private readonly string _applicationName;
-        private readonly string _attachDBFileName;
-        private readonly string _currentLanguage;
-        private readonly string _dataSource;
-        private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB
-        private readonly string _failoverPartner;
-        private readonly string _initialCatalog;
-        private readonly string _password;
-        private readonly string _userID;
-
-        private readonly string _workstationId;
-
-        private readonly TransactionBindingEnum _transactionBinding;
-
-        private readonly TypeSystem _typeSystemVersion;
-        private readonly Version _typeSystemAssemblyVersion;
-        private static readonly Version constTypeSystemAsmVersion10 = new Version("10.0.0.0");
-        private static readonly Version constTypeSystemAsmVersion11 = new Version("11.0.0.0");
-
-        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
-        {
-            ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
-            ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
-            ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);
-
-            // Network Library has its own special error message
-            if (ContainsKey(KEY.Network_Library))
-            {
-                throw SQL.NetworkLibraryKeywordNotSupported();
-            }
-
-            _integratedSecurity = ConvertValueToIntegratedSecurity();
-#if NETCOREAPP
-            _poolBlockingPeriod = ConvertValueToPoolBlockingPeriod();
-#endif
-            _encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
-            _enlist = ConvertValueToBoolean(KEY.Enlist, DEFAULT.Enlist);
-            _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
-            _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
-            _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
-            _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
-            _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
-            _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);
-
-            _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);
-            _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
-            _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
-            _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
-            _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);
-
-            _applicationIntent = ConvertValueToApplicationIntent();
-            _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
-            _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
-            _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
-            _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
-            _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
-            _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
-            _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
-            _password = ConvertValueToString(KEY.Password, DEFAULT.Password);
-            _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);
-
-            // Temporary string - this value is stored internally as an enum.
-            string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);
-            string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null);
-
-            _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
-            _workstationId = ConvertValueToString(KEY.Workstation_Id, null);
-
-
-
-            if (_loadBalanceTimeout < 0)
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
-            }
-
-            if (_connectTimeout < 0)
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
-            }
-
-            if (_maxPoolSize < 1)
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
-            }
-
-            if (_minPoolSize < 0)
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
-            }
-            if (_maxPoolSize < _minPoolSize)
-            {
-                throw ADP.InvalidMinMaxPoolSizeValues();
-            }
-
-            if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
-            {
-                throw SQL.InvalidPacketSizeValue();
-            }
-
-
-            ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
-            ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
-            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
-            ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
-            ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
-            ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
-            ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
-            if (null != _workstationId)
-            {
-                ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
-            }
-
-            if (!string.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
-            {
-                // fail-over partner is set
-
-                if (_multiSubnetFailover)
-                {
-                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
-                }
-
-                if (string.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
-                {
-                    throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
-                }
-            }
-
-            // string.Contains(char) is .NetCore2.1+ specific
-            if (0 <= _attachDBFileName.IndexOf('|'))
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
-            }
-            else
-            {
-                ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
-            }
-
-            _typeSystemAssemblyVersion = constTypeSystemAsmVersion10;
-
-            if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner))
-            {
-                throw SQL.UserInstanceFailoverNotCompatible();
-            }
-
-            if (string.IsNullOrEmpty(typeSystemVersionString))
-            {
-                typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
-            }
-
-            if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
-            {
-                _typeSystemVersion = TypeSystem.Latest;
-            }
-            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
-            {
-                _typeSystemVersion = TypeSystem.SQLServer2000;
-            }
-            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
-            {
-                _typeSystemVersion = TypeSystem.SQLServer2005;
-            }
-            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
-            {
-                _typeSystemVersion = TypeSystem.SQLServer2008;
-            }
-            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
-            {
-                _typeSystemVersion = TypeSystem.SQLServer2012;
-                _typeSystemAssemblyVersion = constTypeSystemAsmVersion11;
-            }
-            else
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
-            }
-
-            if (string.IsNullOrEmpty(transactionBindingString))
-            {
-                transactionBindingString = DbConnectionStringDefaults.TransactionBinding;
-            }
-
-            if (transactionBindingString.Equals(TRANSACTIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase))
-            {
-                _transactionBinding = TransactionBindingEnum.ImplicitUnbind;
-            }
-            else if (transactionBindingString.Equals(TRANSACTIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase))
-            {
-                _transactionBinding = TransactionBindingEnum.ExplicitUnbind;
-            }
-            else
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding);
-            }
-
-            if (_applicationIntent == ApplicationIntent.ReadOnly && !string.IsNullOrEmpty(_failoverPartner))
-                throw SQL.ROR_FailoverNotSupportedConnString();
-
-            if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
-            {
-                throw ADP.InvalidConnectRetryCountValue();
-            }
-
-            if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
-            {
-                throw ADP.InvalidConnectRetryIntervalValue();
-            }
-        }
-
-        // This c-tor is used to create SSE and user instance connection strings when user instance is set to true
-        // BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message
-        internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool? setEnlistValue) : base(connectionOptions)
-        {
-            _integratedSecurity = connectionOptions._integratedSecurity;
-            _encrypt = connectionOptions._encrypt;
-
-            if (setEnlistValue.HasValue)
-            {
-                _enlist = setEnlistValue.Value;
-            }
-            else
-            {
-                _enlist = connectionOptions._enlist;
-            }
-
-            _mars = connectionOptions._mars;
-            _persistSecurityInfo = connectionOptions._persistSecurityInfo;
-            _pooling = connectionOptions._pooling;
-            _replication = connectionOptions._replication;
-            _userInstance = userInstance;
-            _connectTimeout = connectionOptions._connectTimeout;
-            _loadBalanceTimeout = connectionOptions._loadBalanceTimeout;
-#if NETCOREAPP
-            _poolBlockingPeriod = connectionOptions._poolBlockingPeriod;
-#endif
-            _maxPoolSize = connectionOptions._maxPoolSize;
-            _minPoolSize = connectionOptions._minPoolSize;
-            _multiSubnetFailover = connectionOptions._multiSubnetFailover;
-            _packetSize = connectionOptions._packetSize;
-            _applicationName = connectionOptions._applicationName;
-            _attachDBFileName = connectionOptions._attachDBFileName;
-            _currentLanguage = connectionOptions._currentLanguage;
-            _dataSource = dataSource;
-            _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
-            _failoverPartner = connectionOptions._failoverPartner;
-            _initialCatalog = connectionOptions._initialCatalog;
-            _password = connectionOptions._password;
-            _userID = connectionOptions._userID;
-            _workstationId = connectionOptions._workstationId;
-            _typeSystemVersion = connectionOptions._typeSystemVersion;
-            _transactionBinding = connectionOptions._transactionBinding;
-            _applicationIntent = connectionOptions._applicationIntent;
-            _connectRetryCount = connectionOptions._connectRetryCount;
-            _connectRetryInterval = connectionOptions._connectRetryInterval;
-
-            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
-        }
-
-        internal bool IntegratedSecurity { get { return _integratedSecurity; } }
-
-        // We always initialize in Async mode so that both synchronous and asynchronous methods
-        // will work.  In the future we can deprecate the keyword entirely.
-        internal bool Asynchronous { get { return true; } }
-        // SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security
-        internal bool ConnectionReset { get { return true; } }
-        //        internal bool EnableUdtDownload { get { return _enableUdtDownload;} }
-        internal bool Encrypt { get { return _encrypt; } }
-        internal bool TrustServerCertificate { get { return _trustServerCertificate; } }
-        internal bool Enlist { get { return _enlist; } }
-        internal bool MARS { get { return _mars; } }
-        internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } }
-
-        internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } }
-        internal bool Pooling { get { return _pooling; } }
-        internal bool Replication { get { return _replication; } }
-        internal bool UserInstance { get { return _userInstance; } }
-
-        internal int ConnectTimeout { get { return _connectTimeout; } }
-        internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } }
-        internal int MaxPoolSize { get { return _maxPoolSize; } }
-        internal int MinPoolSize { get { return _minPoolSize; } }
-        internal int PacketSize { get { return _packetSize; } }
-        internal int ConnectRetryCount { get { return _connectRetryCount; } }
-        internal int ConnectRetryInterval { get { return _connectRetryInterval; } }
-
-        internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } }
-        internal string ApplicationName { get { return _applicationName; } }
-        internal string AttachDBFilename { get { return _attachDBFileName; } }
-        internal string CurrentLanguage { get { return _currentLanguage; } }
-        internal string DataSource { get { return _dataSource; } }
-        internal string LocalDBInstance { get { return _localDBInstance; } }
-        internal string FailoverPartner { get { return _failoverPartner; } }
-        internal string InitialCatalog { get { return _initialCatalog; } }
-        internal string Password { get { return _password; } }
-        internal string UserID { get { return _userID; } }
-        internal string WorkstationId { get { return _workstationId; } }
-
-        internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } }
-        internal Version TypeSystemAssemblyVersion { get { return _typeSystemAssemblyVersion; } }
-
-        internal TransactionBindingEnum TransactionBinding { get { return _transactionBinding; } }
-
-        // This dictionary is meant to be read-only translation of parsed string
-        // keywords/synonyms to a known keyword string.
-        internal static Dictionary<string, string> GetParseSynonyms()
-        {
-            Dictionary<string, string> synonyms = s_sqlClientSynonyms;
-            if (null == synonyms)
-            {
-                int count = SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount;
-                synonyms = new Dictionary<string, string>(count)
-                {
-                    { KEY.ApplicationIntent, KEY.ApplicationIntent },
-                    { KEY.Application_Name, KEY.Application_Name },
-                    { KEY.AsynchronousProcessing, KEY.AsynchronousProcessing },
-                    { KEY.AttachDBFilename, KEY.AttachDBFilename },
-#if NETCOREAPP
-                    { KEY.PoolBlockingPeriod, KEY.PoolBlockingPeriod},
-#endif
-                    { KEY.Connect_Timeout, KEY.Connect_Timeout },
-                    { KEY.Connection_Reset, KEY.Connection_Reset },
-                    { KEY.Context_Connection, KEY.Context_Connection },
-                    { KEY.Current_Language, KEY.Current_Language },
-                    { KEY.Data_Source, KEY.Data_Source },
-                    { KEY.Encrypt, KEY.Encrypt },
-                    { KEY.Enlist, KEY.Enlist },
-                    { KEY.FailoverPartner, KEY.FailoverPartner },
-                    { KEY.Initial_Catalog, KEY.Initial_Catalog },
-                    { KEY.Integrated_Security, KEY.Integrated_Security },
-                    { KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout },
-                    { KEY.MARS, KEY.MARS },
-                    { KEY.Max_Pool_Size, KEY.Max_Pool_Size },
-                    { KEY.Min_Pool_Size, KEY.Min_Pool_Size },
-                    { KEY.MultiSubnetFailover, KEY.MultiSubnetFailover },
-                    { KEY.Network_Library, KEY.Network_Library },
-                    { KEY.Packet_Size, KEY.Packet_Size },
-                    { KEY.Password, KEY.Password },
-                    { KEY.Persist_Security_Info, KEY.Persist_Security_Info },
-                    { KEY.Pooling, KEY.Pooling },
-                    { KEY.Replication, KEY.Replication },
-                    { KEY.TrustServerCertificate, KEY.TrustServerCertificate },
-                    { KEY.TransactionBinding, KEY.TransactionBinding },
-                    { KEY.Type_System_Version, KEY.Type_System_Version },
-                    { KEY.User_ID, KEY.User_ID },
-                    { KEY.User_Instance, KEY.User_Instance },
-                    { KEY.Workstation_Id, KEY.Workstation_Id },
-                    { KEY.Connect_Retry_Count, KEY.Connect_Retry_Count },
-                    { KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval },
-
-                    { SYNONYM.APP, KEY.Application_Name },
-                    { SYNONYM.Async, KEY.AsynchronousProcessing },
-                    { SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename },
-                    { SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename },
-                    { SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout },
-                    { SYNONYM.TIMEOUT, KEY.Connect_Timeout },
-                    { SYNONYM.LANGUAGE, KEY.Current_Language },
-                    { SYNONYM.ADDR, KEY.Data_Source },
-                    { SYNONYM.ADDRESS, KEY.Data_Source },
-                    { SYNONYM.NETWORK_ADDRESS, KEY.Data_Source },
-                    { SYNONYM.SERVER, KEY.Data_Source },
-                    { SYNONYM.DATABASE, KEY.Initial_Catalog },
-                    { SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security },
-                    { SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout },
-                    { SYNONYM.NET, KEY.Network_Library },
-                    { SYNONYM.NETWORK, KEY.Network_Library },
-                    { SYNONYM.Pwd, KEY.Password },
-                    { SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info },
-                    { SYNONYM.UID, KEY.User_ID },
-                    { SYNONYM.User, KEY.User_ID },
-                    { SYNONYM.WSID, KEY.Workstation_Id }
-                };
-                Debug.Assert(synonyms.Count == count, "incorrect initial ParseSynonyms size");
-                Interlocked.CompareExchange(ref s_sqlClientSynonyms, synonyms, null);
-            }
-            return synonyms;
-        }
-
-        internal string ObtainWorkstationId()
-        {
-            // If not supplied by the user, the default value is the MachineName
-            // Note: In Longhorn you'll be able to rename a machine without
-            // rebooting.  Therefore, don't cache this machine name.
-            string result = WorkstationId;
-            if (null == result)
-            {
-                // permission to obtain Environment.MachineName is Asserted
-                // since permission to open the connection has been granted
-                // the information is shared with the server, but not directly with the user
-                result = ADP.MachineName();
-                ValidateValueLength(result, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
-            }
-            return result;
-        }
-
-
-        private void ValidateValueLength(string value, int limit, string key)
-        {
-            if (limit < value.Length)
-            {
-                throw ADP.InvalidConnectionOptionValueLength(key, limit);
-            }
-        }
-
-
-        internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent()
-        {
-            string value;
-            if (!TryGetParsetableValue(KEY.ApplicationIntent, out value))
-            {
-                return DEFAULT.ApplicationIntent;
-            }
-
-            // when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor,
-            // wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool)
-            try
-            {
-                return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value);
-            }
-            catch (FormatException e)
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
-            }
-            catch (OverflowException e)
-            {
-                throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
-            }
-            // ArgumentException and other types are raised as is (no wrapping)
-        }
-
-        internal void ThrowUnsupportedIfKeywordSet(string keyword)
-        {
-            if (ContainsKey(keyword))
-            {
-                throw SQL.UnsupportedKeyword(keyword);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.NetCoreApp.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.NetCoreApp.cs
deleted file mode 100644 (file)
index 4882975..0000000
+++ /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.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlConnectionStringBuilder : DbConnectionStringBuilder
-    {
-        private PoolBlockingPeriod _poolBlockingPeriod = DbConnectionStringDefaults.PoolBlockingPeriod;
-
-        private void SetPoolBlockingPeriodValue(PoolBlockingPeriod value)
-        {
-            Debug.Assert(DbConnectionStringBuilderUtil.IsValidPoolBlockingPeriodValue(value), "Invalid value for PoolBlockingPeriod");
-            base[DbConnectionStringKeywords.PoolBlockingPeriod] = DbConnectionStringBuilderUtil.PoolBlockingPeriodToString(value);
-        }
-
-        private static PoolBlockingPeriod ConvertToPoolBlockingPeriod(string keyword, object value)
-        {
-            return DbConnectionStringBuilderUtil.ConvertToPoolBlockingPeriod(keyword, value);
-        }
-
-        public PoolBlockingPeriod PoolBlockingPeriod
-        {
-            get { return _poolBlockingPeriod; }
-            set
-            {
-                if (!DbConnectionStringBuilderUtil.IsValidPoolBlockingPeriodValue(value))
-                {
-                    throw ADP.InvalidEnumerationValue(typeof(PoolBlockingPeriod), (int)value);
-                }
-
-                SetPoolBlockingPeriodValue(value);
-                _poolBlockingPeriod = value;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs
deleted file mode 100644 (file)
index 733f604..0000000
+++ /dev/null
@@ -1,1007 +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.ComponentModel;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlConnectionStringBuilder : DbConnectionStringBuilder
-    {
-        private enum Keywords
-        { // specific ordering for ConnectionString output construction
-            // NamedConnection,
-            DataSource,
-            FailoverPartner,
-            AttachDBFilename,
-            InitialCatalog,
-            IntegratedSecurity,
-            PersistSecurityInfo,
-            UserID,
-            Password,
-
-            Enlist,
-            Pooling,
-            MinPoolSize,
-            MaxPoolSize,
-#if NETCOREAPP
-            PoolBlockingPeriod,
-#endif
-
-            MultipleActiveResultSets,
-            Replication,
-
-            ConnectTimeout,
-            Encrypt,
-            TrustServerCertificate,
-            LoadBalanceTimeout,
-            PacketSize,
-            TypeSystemVersion,
-
-            ApplicationName,
-            CurrentLanguage,
-            WorkstationID,
-
-            UserInstance,
-
-            TransactionBinding,
-
-            ApplicationIntent,
-
-            MultiSubnetFailover,
-
-            ConnectRetryCount,
-
-            ConnectRetryInterval,
-
-            // keep the count value last
-            KeywordsCount
-        }
-
-        internal const int KeywordsCount = (int)Keywords.KeywordsCount;
-        internal const int DeprecatedKeywordsCount = 4;
-
-        private static readonly string[] s_validKeywords = CreateValidKeywords();
-        private static readonly Dictionary<string, Keywords> s_keywords = CreateKeywordsDictionary();
-
-        private ApplicationIntent _applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
-        private string _applicationName = DbConnectionStringDefaults.ApplicationName;
-        private string _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
-        private string _currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
-        private string _dataSource = DbConnectionStringDefaults.DataSource;
-        private string _failoverPartner = DbConnectionStringDefaults.FailoverPartner;
-        private string _initialCatalog = DbConnectionStringDefaults.InitialCatalog;
-        //      private string _namedConnection   = DbConnectionStringDefaults.NamedConnection;
-        private string _password = DbConnectionStringDefaults.Password;
-        private string _transactionBinding = DbConnectionStringDefaults.TransactionBinding;
-        private string _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
-        private string _userID = DbConnectionStringDefaults.UserID;
-        private string _workstationID = DbConnectionStringDefaults.WorkstationID;
-
-        private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
-        private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
-        private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
-        private int _minPoolSize = DbConnectionStringDefaults.MinPoolSize;
-        private int _packetSize = DbConnectionStringDefaults.PacketSize;
-        private int _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
-        private int _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
-
-        private bool _encrypt = DbConnectionStringDefaults.Encrypt;
-        private bool _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
-        private bool _enlist = DbConnectionStringDefaults.Enlist;
-        private bool _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
-        private bool _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
-        private bool _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
-        private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
-        private bool _pooling = DbConnectionStringDefaults.Pooling;
-        private bool _replication = DbConnectionStringDefaults.Replication;
-        private bool _userInstance = DbConnectionStringDefaults.UserInstance;
-
-        private static string[] CreateValidKeywords()
-        {
-            string[] validKeywords = new string[KeywordsCount];
-            validKeywords[(int)Keywords.ApplicationIntent] = DbConnectionStringKeywords.ApplicationIntent;
-            validKeywords[(int)Keywords.ApplicationName] = DbConnectionStringKeywords.ApplicationName;
-            validKeywords[(int)Keywords.AttachDBFilename] = DbConnectionStringKeywords.AttachDBFilename;
-#if NETCOREAPP
-            validKeywords[(int)Keywords.PoolBlockingPeriod] = DbConnectionStringKeywords.PoolBlockingPeriod;
-#endif
-            validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout;
-            validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage;
-            validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource;
-            validKeywords[(int)Keywords.Encrypt] = DbConnectionStringKeywords.Encrypt;
-            validKeywords[(int)Keywords.Enlist] = DbConnectionStringKeywords.Enlist;
-            validKeywords[(int)Keywords.FailoverPartner] = DbConnectionStringKeywords.FailoverPartner;
-            validKeywords[(int)Keywords.InitialCatalog] = DbConnectionStringKeywords.InitialCatalog;
-            validKeywords[(int)Keywords.IntegratedSecurity] = DbConnectionStringKeywords.IntegratedSecurity;
-            validKeywords[(int)Keywords.LoadBalanceTimeout] = DbConnectionStringKeywords.LoadBalanceTimeout;
-            validKeywords[(int)Keywords.MaxPoolSize] = DbConnectionStringKeywords.MaxPoolSize;
-            validKeywords[(int)Keywords.MinPoolSize] = DbConnectionStringKeywords.MinPoolSize;
-            validKeywords[(int)Keywords.MultipleActiveResultSets] = DbConnectionStringKeywords.MultipleActiveResultSets;
-            validKeywords[(int)Keywords.MultiSubnetFailover] = DbConnectionStringKeywords.MultiSubnetFailover;
-            //          validKeywords[(int)Keywords.NamedConnection]          = DbConnectionStringKeywords.NamedConnection;
-            validKeywords[(int)Keywords.PacketSize] = DbConnectionStringKeywords.PacketSize;
-            validKeywords[(int)Keywords.Password] = DbConnectionStringKeywords.Password;
-            validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo;
-            validKeywords[(int)Keywords.Pooling] = DbConnectionStringKeywords.Pooling;
-            validKeywords[(int)Keywords.Replication] = DbConnectionStringKeywords.Replication;
-            validKeywords[(int)Keywords.TransactionBinding] = DbConnectionStringKeywords.TransactionBinding;
-            validKeywords[(int)Keywords.TrustServerCertificate] = DbConnectionStringKeywords.TrustServerCertificate;
-            validKeywords[(int)Keywords.TypeSystemVersion] = DbConnectionStringKeywords.TypeSystemVersion;
-            validKeywords[(int)Keywords.UserID] = DbConnectionStringKeywords.UserID;
-            validKeywords[(int)Keywords.UserInstance] = DbConnectionStringKeywords.UserInstance;
-            validKeywords[(int)Keywords.WorkstationID] = DbConnectionStringKeywords.WorkstationID;
-            validKeywords[(int)Keywords.ConnectRetryCount] = DbConnectionStringKeywords.ConnectRetryCount;
-            validKeywords[(int)Keywords.ConnectRetryInterval] = DbConnectionStringKeywords.ConnectRetryInterval;
-            return validKeywords;
-        }
-
-        private static Dictionary<string, Keywords> CreateKeywordsDictionary()
-        {
-            Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(KeywordsCount + SqlConnectionString.SynonymCount, StringComparer.OrdinalIgnoreCase);
-            hash.Add(DbConnectionStringKeywords.ApplicationIntent, Keywords.ApplicationIntent);
-            hash.Add(DbConnectionStringKeywords.ApplicationName, Keywords.ApplicationName);
-            hash.Add(DbConnectionStringKeywords.AttachDBFilename, Keywords.AttachDBFilename);
-#if NETCOREAPP
-            hash.Add(DbConnectionStringKeywords.PoolBlockingPeriod, Keywords.PoolBlockingPeriod);
-#endif
-            hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout);
-            hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage);
-            hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource);
-            hash.Add(DbConnectionStringKeywords.Encrypt, Keywords.Encrypt);
-            hash.Add(DbConnectionStringKeywords.Enlist, Keywords.Enlist);
-            hash.Add(DbConnectionStringKeywords.FailoverPartner, Keywords.FailoverPartner);
-            hash.Add(DbConnectionStringKeywords.InitialCatalog, Keywords.InitialCatalog);
-            hash.Add(DbConnectionStringKeywords.IntegratedSecurity, Keywords.IntegratedSecurity);
-            hash.Add(DbConnectionStringKeywords.LoadBalanceTimeout, Keywords.LoadBalanceTimeout);
-            hash.Add(DbConnectionStringKeywords.MultipleActiveResultSets, Keywords.MultipleActiveResultSets);
-            hash.Add(DbConnectionStringKeywords.MaxPoolSize, Keywords.MaxPoolSize);
-            hash.Add(DbConnectionStringKeywords.MinPoolSize, Keywords.MinPoolSize);
-            hash.Add(DbConnectionStringKeywords.MultiSubnetFailover, Keywords.MultiSubnetFailover);
-            //          hash.Add(DbConnectionStringKeywords.NamedConnection,          Keywords.NamedConnection);
-            hash.Add(DbConnectionStringKeywords.PacketSize, Keywords.PacketSize);
-            hash.Add(DbConnectionStringKeywords.Password, Keywords.Password);
-            hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo);
-            hash.Add(DbConnectionStringKeywords.Pooling, Keywords.Pooling);
-            hash.Add(DbConnectionStringKeywords.Replication, Keywords.Replication);
-            hash.Add(DbConnectionStringKeywords.TransactionBinding, Keywords.TransactionBinding);
-            hash.Add(DbConnectionStringKeywords.TrustServerCertificate, Keywords.TrustServerCertificate);
-            hash.Add(DbConnectionStringKeywords.TypeSystemVersion, Keywords.TypeSystemVersion);
-            hash.Add(DbConnectionStringKeywords.UserID, Keywords.UserID);
-            hash.Add(DbConnectionStringKeywords.UserInstance, Keywords.UserInstance);
-            hash.Add(DbConnectionStringKeywords.WorkstationID, Keywords.WorkstationID);
-            hash.Add(DbConnectionStringKeywords.ConnectRetryCount, Keywords.ConnectRetryCount);
-            hash.Add(DbConnectionStringKeywords.ConnectRetryInterval, Keywords.ConnectRetryInterval);
-
-            hash.Add(DbConnectionStringSynonyms.APP, Keywords.ApplicationName);
-            hash.Add(DbConnectionStringSynonyms.EXTENDEDPROPERTIES, Keywords.AttachDBFilename);
-            hash.Add(DbConnectionStringSynonyms.INITIALFILENAME, Keywords.AttachDBFilename);
-            hash.Add(DbConnectionStringSynonyms.CONNECTIONTIMEOUT, Keywords.ConnectTimeout);
-            hash.Add(DbConnectionStringSynonyms.TIMEOUT, Keywords.ConnectTimeout);
-            hash.Add(DbConnectionStringSynonyms.LANGUAGE, Keywords.CurrentLanguage);
-            hash.Add(DbConnectionStringSynonyms.ADDR, Keywords.DataSource);
-            hash.Add(DbConnectionStringSynonyms.ADDRESS, Keywords.DataSource);
-            hash.Add(DbConnectionStringSynonyms.NETWORKADDRESS, Keywords.DataSource);
-            hash.Add(DbConnectionStringSynonyms.SERVER, Keywords.DataSource);
-            hash.Add(DbConnectionStringSynonyms.DATABASE, Keywords.InitialCatalog);
-            hash.Add(DbConnectionStringSynonyms.TRUSTEDCONNECTION, Keywords.IntegratedSecurity);
-            hash.Add(DbConnectionStringSynonyms.ConnectionLifetime, Keywords.LoadBalanceTimeout);
-            hash.Add(DbConnectionStringSynonyms.Pwd, Keywords.Password);
-            hash.Add(DbConnectionStringSynonyms.PERSISTSECURITYINFO, Keywords.PersistSecurityInfo);
-            hash.Add(DbConnectionStringSynonyms.UID, Keywords.UserID);
-            hash.Add(DbConnectionStringSynonyms.User, Keywords.UserID);
-            hash.Add(DbConnectionStringSynonyms.WSID, Keywords.WorkstationID);
-            Debug.Assert((KeywordsCount + SqlConnectionString.SynonymCount) == hash.Count, "initial expected size is incorrect");
-            return hash;
-        }
-
-        public SqlConnectionStringBuilder() : this((string)null)
-        {
-        }
-
-        public SqlConnectionStringBuilder(string connectionString) : base()
-        {
-            if (!string.IsNullOrEmpty(connectionString))
-            {
-                ConnectionString = connectionString;
-            }
-        }
-
-        public override object this[string keyword]
-        {
-            get
-            {
-                Keywords index = GetIndex(keyword);
-                return GetAt(index);
-            }
-            set
-            {
-                if (null != value)
-                {
-                    Keywords index = GetIndex(keyword);
-                    switch (index)
-                    {
-                        case Keywords.ApplicationIntent: this.ApplicationIntent = ConvertToApplicationIntent(keyword, value); break;
-                        case Keywords.ApplicationName: ApplicationName = ConvertToString(value); break;
-                        case Keywords.AttachDBFilename: AttachDBFilename = ConvertToString(value); break;
-                        case Keywords.CurrentLanguage: CurrentLanguage = ConvertToString(value); break;
-                        case Keywords.DataSource: DataSource = ConvertToString(value); break;
-                        case Keywords.FailoverPartner: FailoverPartner = ConvertToString(value); break;
-                        case Keywords.InitialCatalog: InitialCatalog = ConvertToString(value); break;
-                        //                  case Keywords.NamedConnection:          NamedConnection = ConvertToString(value); break;
-                        case Keywords.Password: Password = ConvertToString(value); break;
-                        case Keywords.UserID: UserID = ConvertToString(value); break;
-                        case Keywords.TransactionBinding: TransactionBinding = ConvertToString(value); break;
-                        case Keywords.TypeSystemVersion: TypeSystemVersion = ConvertToString(value); break;
-                        case Keywords.WorkstationID: WorkstationID = ConvertToString(value); break;
-
-                        case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break;
-                        case Keywords.LoadBalanceTimeout: LoadBalanceTimeout = ConvertToInt32(value); break;
-                        case Keywords.MaxPoolSize: MaxPoolSize = ConvertToInt32(value); break;
-                        case Keywords.MinPoolSize: MinPoolSize = ConvertToInt32(value); break;
-                        case Keywords.PacketSize: PacketSize = ConvertToInt32(value); break;
-
-                        case Keywords.IntegratedSecurity: IntegratedSecurity = ConvertToIntegratedSecurity(value); break;
-#if NETCOREAPP
-                        case Keywords.PoolBlockingPeriod: PoolBlockingPeriod = ConvertToPoolBlockingPeriod(keyword, value); break;
-#endif
-                        case Keywords.Encrypt: Encrypt = ConvertToBoolean(value); break;
-                        case Keywords.TrustServerCertificate: TrustServerCertificate = ConvertToBoolean(value); break;
-                        case Keywords.Enlist: Enlist = ConvertToBoolean(value); break;
-                        case Keywords.MultipleActiveResultSets: MultipleActiveResultSets = ConvertToBoolean(value); break;
-                        case Keywords.MultiSubnetFailover: MultiSubnetFailover = ConvertToBoolean(value); break;
-                        case Keywords.PersistSecurityInfo: PersistSecurityInfo = ConvertToBoolean(value); break;
-                        case Keywords.Pooling: Pooling = ConvertToBoolean(value); break;
-                        case Keywords.Replication: Replication = ConvertToBoolean(value); break;
-                        case Keywords.UserInstance: UserInstance = ConvertToBoolean(value); break;
-                        case Keywords.ConnectRetryCount: ConnectRetryCount = ConvertToInt32(value); break;
-                        case Keywords.ConnectRetryInterval: ConnectRetryInterval = ConvertToInt32(value); break;
-
-                        default:
-                            Debug.Fail("unexpected keyword");
-                            throw UnsupportedKeyword(keyword);
-                    }
-                }
-                else
-                {
-                    Remove(keyword);
-                }
-            }
-        }
-
-        public ApplicationIntent ApplicationIntent
-        {
-            get { return _applicationIntent; }
-            set
-            {
-                if (!DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value))
-                {
-                    throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)value);
-                }
-
-                SetApplicationIntentValue(value);
-                _applicationIntent = value;
-            }
-        }
-
-        public string ApplicationName
-        {
-            get { return _applicationName; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.ApplicationName, value);
-                _applicationName = value;
-            }
-        }
-
-        public string AttachDBFilename
-        {
-            get { return _attachDBFilename; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.AttachDBFilename, value);
-                _attachDBFilename = value;
-            }
-        }
-
-        public int ConnectTimeout
-        {
-            get { return _connectTimeout; }
-            set
-            {
-                if (value < 0)
-                {
-                    throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectTimeout);
-                }
-                SetValue(DbConnectionStringKeywords.ConnectTimeout, value);
-                _connectTimeout = value;
-            }
-        }
-
-        public string CurrentLanguage
-        {
-            get { return _currentLanguage; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.CurrentLanguage, value);
-                _currentLanguage = value;
-            }
-        }
-
-        public string DataSource
-        {
-            get { return _dataSource; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.DataSource, value);
-                _dataSource = value;
-            }
-        }
-
-        public bool Encrypt
-        {
-            get { return _encrypt; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.Encrypt, value);
-                _encrypt = value;
-            }
-        }
-
-        public bool TrustServerCertificate
-        {
-            get { return _trustServerCertificate; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.TrustServerCertificate, value);
-                _trustServerCertificate = value;
-            }
-        }
-
-        public bool Enlist
-        {
-            get { return _enlist; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.Enlist, value);
-                _enlist = value;
-            }
-        }
-
-        public string FailoverPartner
-        {
-            get { return _failoverPartner; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.FailoverPartner, value);
-                _failoverPartner = value;
-            }
-        }
-
-        [TypeConverter(typeof(SqlInitialCatalogConverter))]
-        public string InitialCatalog
-        {
-            get { return _initialCatalog; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.InitialCatalog, value);
-                _initialCatalog = value;
-            }
-        }
-
-        public bool IntegratedSecurity
-        {
-            get { return _integratedSecurity; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.IntegratedSecurity, value);
-                _integratedSecurity = value;
-            }
-        }
-
-        public int LoadBalanceTimeout
-        {
-            get { return _loadBalanceTimeout; }
-            set
-            {
-                if (value < 0)
-                {
-                    throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.LoadBalanceTimeout);
-                }
-                SetValue(DbConnectionStringKeywords.LoadBalanceTimeout, value);
-                _loadBalanceTimeout = value;
-            }
-        }
-
-        public int MaxPoolSize
-        {
-            get { return _maxPoolSize; }
-            set
-            {
-                if (value < 1)
-                {
-                    throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MaxPoolSize);
-                }
-                SetValue(DbConnectionStringKeywords.MaxPoolSize, value);
-                _maxPoolSize = value;
-            }
-        }
-
-        public int ConnectRetryCount
-        {
-            get { return _connectRetryCount; }
-            set
-            {
-                if ((value < 0) || (value > 255))
-                {
-                    throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryCount);
-                }
-                SetValue(DbConnectionStringKeywords.ConnectRetryCount, value);
-                _connectRetryCount = value;
-            }
-        }
-
-        public int ConnectRetryInterval
-        {
-            get { return _connectRetryInterval; }
-            set
-            {
-                if ((value < 1) || (value > 60))
-                {
-                    throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryInterval);
-                }
-                SetValue(DbConnectionStringKeywords.ConnectRetryInterval, value);
-                _connectRetryInterval = value;
-            }
-        }
-
-
-
-        public int MinPoolSize
-        {
-            get { return _minPoolSize; }
-            set
-            {
-                if (value < 0)
-                {
-                    throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MinPoolSize);
-                }
-                SetValue(DbConnectionStringKeywords.MinPoolSize, value);
-                _minPoolSize = value;
-            }
-        }
-
-        public bool MultipleActiveResultSets
-        {
-            get { return _multipleActiveResultSets; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.MultipleActiveResultSets, value);
-                _multipleActiveResultSets = value;
-            }
-        }
-
-        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed and Approved by UE")]
-        public bool MultiSubnetFailover
-        {
-            get { return _multiSubnetFailover; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.MultiSubnetFailover, value);
-                _multiSubnetFailover = value;
-            }
-        }
-        /*
-                [DisplayName(DbConnectionStringKeywords.NamedConnection)]
-                [ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
-                [ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)]
-                [RefreshPropertiesAttribute(RefreshProperties.All)]
-                [TypeConverter(typeof(NamedConnectionStringConverter))]
-                public string NamedConnection {
-                    get { return _namedConnection; }
-                    set {
-                        SetValue(DbConnectionStringKeywords.NamedConnection, value);
-                        _namedConnection = value;
-                    }
-                }
-        */
-        public int PacketSize
-        {
-            get { return _packetSize; }
-            set
-            {
-                if ((value < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < value))
-                {
-                    throw SQL.InvalidPacketSizeValue();
-                }
-                SetValue(DbConnectionStringKeywords.PacketSize, value);
-                _packetSize = value;
-            }
-        }
-
-        public string Password
-        {
-            get { return _password; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.Password, value);
-                _password = value;
-            }
-        }
-
-        public bool PersistSecurityInfo
-        {
-            get { return _persistSecurityInfo; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value);
-                _persistSecurityInfo = value;
-            }
-        }
-
-        public bool Pooling
-        {
-            get { return _pooling; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.Pooling, value);
-                _pooling = value;
-            }
-        }
-
-        public bool Replication
-        {
-            get { return _replication; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.Replication, value);
-                _replication = value;
-            }
-        }
-
-        public string TransactionBinding
-        {
-            get { return _transactionBinding; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.TransactionBinding, value);
-                _transactionBinding = value;
-            }
-        }
-
-        public string TypeSystemVersion
-        {
-            get { return _typeSystemVersion; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.TypeSystemVersion, value);
-                _typeSystemVersion = value;
-            }
-        }
-
-        public string UserID
-        {
-            get { return _userID; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.UserID, value);
-                _userID = value;
-            }
-        }
-
-        public bool UserInstance
-        {
-            get { return _userInstance; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.UserInstance, value);
-                _userInstance = value;
-            }
-        }
-
-        public string WorkstationID
-        {
-            get { return _workstationID; }
-            set
-            {
-                SetValue(DbConnectionStringKeywords.WorkstationID, value);
-                _workstationID = value;
-            }
-        }
-
-
-        public override ICollection Keys
-        {
-            get
-            {
-                return new System.Collections.ObjectModel.ReadOnlyCollection<string>(s_validKeywords);
-            }
-        }
-
-        public override ICollection Values
-        {
-            get
-            {
-                // written this way so if the ordering of Keywords & _validKeywords changes
-                // this is one less place to maintain
-                object[] values = new object[s_validKeywords.Length];
-                for (int i = 0; i < values.Length; ++i)
-                {
-                    values[i] = GetAt((Keywords)i);
-                }
-                return new System.Collections.ObjectModel.ReadOnlyCollection<object>(values);
-            }
-        }
-
-        public override void Clear()
-        {
-            base.Clear();
-            for (int i = 0; i < s_validKeywords.Length; ++i)
-            {
-                Reset((Keywords)i);
-            }
-        }
-
-        public override bool ContainsKey(string keyword)
-        {
-            ADP.CheckArgumentNull(keyword, nameof(keyword));
-            return s_keywords.ContainsKey(keyword);
-        }
-
-        private static bool ConvertToBoolean(object value)
-        {
-            return DbConnectionStringBuilderUtil.ConvertToBoolean(value);
-        }
-        private static int ConvertToInt32(object value)
-        {
-            return DbConnectionStringBuilderUtil.ConvertToInt32(value);
-        }
-        private static bool ConvertToIntegratedSecurity(object value)
-        {
-            return DbConnectionStringBuilderUtil.ConvertToIntegratedSecurity(value);
-        }
-        private static string ConvertToString(object value)
-        {
-            return DbConnectionStringBuilderUtil.ConvertToString(value);
-        }
-        private static ApplicationIntent ConvertToApplicationIntent(string keyword, object value)
-        {
-            return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(keyword, value);
-        }
-
-        private object GetAt(Keywords index)
-        {
-            switch (index)
-            {
-                case Keywords.ApplicationIntent: return this.ApplicationIntent;
-                case Keywords.ApplicationName: return ApplicationName;
-                case Keywords.AttachDBFilename: return AttachDBFilename;
-#if NETCOREAPP
-                case Keywords.PoolBlockingPeriod: return PoolBlockingPeriod;
-#endif
-                case Keywords.ConnectTimeout: return ConnectTimeout;
-                case Keywords.CurrentLanguage: return CurrentLanguage;
-                case Keywords.DataSource: return DataSource;
-                case Keywords.Encrypt: return Encrypt;
-                case Keywords.Enlist: return Enlist;
-                case Keywords.FailoverPartner: return FailoverPartner;
-                case Keywords.InitialCatalog: return InitialCatalog;
-                case Keywords.IntegratedSecurity: return IntegratedSecurity;
-                case Keywords.LoadBalanceTimeout: return LoadBalanceTimeout;
-                case Keywords.MultipleActiveResultSets: return MultipleActiveResultSets;
-                case Keywords.MaxPoolSize: return MaxPoolSize;
-                case Keywords.MinPoolSize: return MinPoolSize;
-                case Keywords.MultiSubnetFailover: return MultiSubnetFailover;
-                //          case Keywords.NamedConnection:          return NamedConnection;
-                case Keywords.PacketSize: return PacketSize;
-                case Keywords.Password: return Password;
-                case Keywords.PersistSecurityInfo: return PersistSecurityInfo;
-                case Keywords.Pooling: return Pooling;
-                case Keywords.Replication: return Replication;
-                case Keywords.TransactionBinding: return TransactionBinding;
-                case Keywords.TrustServerCertificate: return TrustServerCertificate;
-                case Keywords.TypeSystemVersion: return TypeSystemVersion;
-                case Keywords.UserID: return UserID;
-                case Keywords.UserInstance: return UserInstance;
-                case Keywords.WorkstationID: return WorkstationID;
-                case Keywords.ConnectRetryCount: return ConnectRetryCount;
-                case Keywords.ConnectRetryInterval: return ConnectRetryInterval;
-
-                default:
-                    Debug.Fail("unexpected keyword");
-                    throw UnsupportedKeyword(s_validKeywords[(int)index]);
-            }
-        }
-
-        private Keywords GetIndex(string keyword)
-        {
-            ADP.CheckArgumentNull(keyword, nameof(keyword));
-            Keywords index;
-            if (s_keywords.TryGetValue(keyword, out index))
-            {
-                return index;
-            }
-            throw UnsupportedKeyword(keyword);
-        }
-
-
-        public override bool Remove(string keyword)
-        {
-            ADP.CheckArgumentNull(keyword, nameof(keyword));
-            Keywords index;
-            if (s_keywords.TryGetValue(keyword, out index))
-            {
-                if (base.Remove(s_validKeywords[(int)index]))
-                {
-                    Reset(index);
-                    return true;
-                }
-            }
-            return false;
-        }
-
-        private void Reset(Keywords index)
-        {
-            switch (index)
-            {
-                case Keywords.ApplicationIntent:
-                    _applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
-                    break;
-                case Keywords.ApplicationName:
-                    _applicationName = DbConnectionStringDefaults.ApplicationName;
-                    break;
-                case Keywords.AttachDBFilename:
-                    _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
-                    break;
-#if NETCOREAPP
-                case Keywords.PoolBlockingPeriod:
-                    _poolBlockingPeriod = DbConnectionStringDefaults.PoolBlockingPeriod;
-                    break;
-#endif
-                case Keywords.ConnectTimeout:
-                    _connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
-                    break;
-                case Keywords.CurrentLanguage:
-                    _currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
-                    break;
-                case Keywords.DataSource:
-                    _dataSource = DbConnectionStringDefaults.DataSource;
-                    break;
-                case Keywords.Encrypt:
-                    _encrypt = DbConnectionStringDefaults.Encrypt;
-                    break;
-                case Keywords.Enlist:
-                    _enlist = DbConnectionStringDefaults.Enlist;
-                    break;
-                case Keywords.FailoverPartner:
-                    _failoverPartner = DbConnectionStringDefaults.FailoverPartner;
-                    break;
-                case Keywords.InitialCatalog:
-                    _initialCatalog = DbConnectionStringDefaults.InitialCatalog;
-                    break;
-                case Keywords.IntegratedSecurity:
-                    _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
-                    break;
-                case Keywords.LoadBalanceTimeout:
-                    _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
-                    break;
-                case Keywords.MultipleActiveResultSets:
-                    _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
-                    break;
-                case Keywords.MaxPoolSize:
-                    _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
-                    break;
-                case Keywords.MinPoolSize:
-                    _minPoolSize = DbConnectionStringDefaults.MinPoolSize;
-                    break;
-                case Keywords.MultiSubnetFailover:
-                    _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
-                    break;
-                //          case Keywords.NamedConnection:
-                //              _namedConnection = DbConnectionStringDefaults.NamedConnection;
-                //              break;
-                case Keywords.PacketSize:
-                    _packetSize = DbConnectionStringDefaults.PacketSize;
-                    break;
-                case Keywords.Password:
-                    _password = DbConnectionStringDefaults.Password;
-                    break;
-                case Keywords.PersistSecurityInfo:
-                    _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
-                    break;
-                case Keywords.Pooling:
-                    _pooling = DbConnectionStringDefaults.Pooling;
-                    break;
-                case Keywords.ConnectRetryCount:
-                    _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
-                    break;
-                case Keywords.ConnectRetryInterval:
-                    _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
-                    break;
-                case Keywords.Replication:
-                    _replication = DbConnectionStringDefaults.Replication;
-                    break;
-                case Keywords.TransactionBinding:
-                    _transactionBinding = DbConnectionStringDefaults.TransactionBinding;
-                    break;
-                case Keywords.TrustServerCertificate:
-                    _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
-                    break;
-                case Keywords.TypeSystemVersion:
-                    _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
-                    break;
-                case Keywords.UserID:
-                    _userID = DbConnectionStringDefaults.UserID;
-                    break;
-                case Keywords.UserInstance:
-                    _userInstance = DbConnectionStringDefaults.UserInstance;
-                    break;
-                case Keywords.WorkstationID:
-                    _workstationID = DbConnectionStringDefaults.WorkstationID;
-                    break;
-                default:
-                    Debug.Fail("unexpected keyword");
-                    throw UnsupportedKeyword(s_validKeywords[(int)index]);
-            }
-        }
-
-        private void SetValue(string keyword, bool value)
-        {
-            base[keyword] = value.ToString();
-        }
-        private void SetValue(string keyword, int value)
-        {
-            base[keyword] = value.ToString((System.IFormatProvider)null);
-        }
-        private void SetValue(string keyword, string value)
-        {
-            ADP.CheckArgumentNull(value, keyword);
-            base[keyword] = value;
-        }
-        private void SetApplicationIntentValue(ApplicationIntent value)
-        {
-            Debug.Assert(DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value), "invalid value");
-            base[DbConnectionStringKeywords.ApplicationIntent] = DbConnectionStringBuilderUtil.ApplicationIntentToString(value);
-        }
-
-        public override bool ShouldSerialize(string keyword)
-        {
-            ADP.CheckArgumentNull(keyword, nameof(keyword));
-            Keywords index;
-            return s_keywords.TryGetValue(keyword, out index) && base.ShouldSerialize(s_validKeywords[(int)index]);
-        }
-
-        public override bool TryGetValue(string keyword, out object value)
-        {
-            Keywords index;
-            if (s_keywords.TryGetValue(keyword, out index))
-            {
-                value = GetAt(index);
-                return true;
-            }
-            value = null;
-            return false;
-        }
-
-        private static readonly string[] s_notSupportedKeywords = new string[] {
-            DbConnectionStringKeywords.AsynchronousProcessing,
-            DbConnectionStringKeywords.ConnectionReset,
-            DbConnectionStringKeywords.ContextConnection,
-            DbConnectionStringKeywords.TransactionBinding,
-
-            DbConnectionStringSynonyms.Async
-        };
-
-        private static readonly string[] s_notSupportedNetworkLibraryKeywords = new string[] {
-            DbConnectionStringKeywords.NetworkLibrary,
-
-            DbConnectionStringSynonyms.NET,
-            DbConnectionStringSynonyms.NETWORK
-        };
-
-        private Exception UnsupportedKeyword(string keyword)
-        {
-            if (s_notSupportedKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase))
-            {
-                return SQL.UnsupportedKeyword(keyword);
-            }
-            else if (s_notSupportedNetworkLibraryKeywords.Contains(keyword, StringComparer.OrdinalIgnoreCase))
-            {
-                return SQL.NetworkLibraryKeywordNotSupported();
-            }
-            else
-            {
-                return ADP.KeywordNotSupported(keyword);
-            }
-        }
-
-        private sealed class SqlInitialCatalogConverter : StringConverter
-        {
-            // converter classes should have public ctor
-            public SqlInitialCatalogConverter()
-            {
-            }
-
-            public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
-            {
-                return GetStandardValuesSupportedInternal(context);
-            }
-
-            private bool GetStandardValuesSupportedInternal(ITypeDescriptorContext context)
-            {
-                // Only say standard values are supported if the connection string has enough
-                // information set to instantiate a connection and retrieve a list of databases
-                bool flag = false;
-                if (null != context)
-                {
-                    SqlConnectionStringBuilder constr = (context.Instance as SqlConnectionStringBuilder);
-                    if (null != constr)
-                    {
-                        if ((0 < constr.DataSource.Length) && (constr.IntegratedSecurity || (0 < constr.UserID.Length)))
-                        {
-                            flag = true;
-                        }
-                    }
-                }
-                return flag;
-            }
-
-            public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
-            {
-                // Although theoretically this could be true, some people may want to just type in a name
-                return false;
-            }
-
-            public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
-            {
-                // There can only be standard values if the connection string is in a state that might
-                // be able to instantiate a connection
-                if (GetStandardValuesSupportedInternal(context))
-                {
-
-                    // Create an array list to store the database names
-                    List<string> values = new List<string>();
-
-                    try
-                    {
-                        SqlConnectionStringBuilder constr = (SqlConnectionStringBuilder)context.Instance;
-
-                        // Create a connection
-                        using (SqlConnection connection = new SqlConnection())
-                        {
-
-                            // Create a basic connection string from current property values
-                            connection.ConnectionString = constr.ConnectionString;
-
-                            // Try to open the connection
-                            connection.Open();
-
-                            DataTable databaseTable = connection.GetSchema("DATABASES");
-
-                            foreach (DataRow row in databaseTable.Rows)
-                            {
-                                string dbName = (string)row["database_name"];
-                                values.Add(dbName);
-                            }
-                        }
-                    }
-                    catch (SqlException e)
-                    {
-                        ADP.TraceExceptionWithoutRethrow(e);
-                        // silently fail
-                    }
-
-                    // Return values as a StandardValuesCollection
-                    return new StandardValuesCollection(values);
-                }
-                return null;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionTimeoutErrorInternal.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionTimeoutErrorInternal.cs
deleted file mode 100644 (file)
index 0f71e5e..0000000
+++ /dev/null
@@ -1,231 +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.Text;
-
-namespace System.Data.SqlClient
-{
-    // VSTFDevDiv# 643319 - Improve timeout error message reported when SqlConnection.Open fails
-    internal enum SqlConnectionTimeoutErrorPhase
-    {
-        Undefined = 0,
-        PreLoginBegin,              // [PRE-LOGIN PHASE]        Start of the pre-login phase; Initialize global variables;
-        InitializeConnection,       // [PRE-LOGIN PHASE]        Create and initialize socket.
-        SendPreLoginHandshake,      // [PRE-LOGIN PHASE]        Make pre-login handshake request.
-        ConsumePreLoginHandshake,   // [PRE-LOGIN PHASE]        Receive pre-login handshake response and consume it; Establish an SSL channel.
-        LoginBegin,                 // [LOGIN PHASE]            End of the pre-login phase; Start of the login phase;
-        ProcessConnectionAuth,      // [LOGIN PHASE]            Process SSPI or SQL Authenticate.
-        PostLogin,                  // [POST-LOGIN PHASE]       End of the login phase; And post-login phase;
-        Complete,                   // Marker for the successful completion of the connection
-        Count                       // ** This is to track the length of the enum. ** Do not add any phase after this. **
-    }
-
-    internal enum SqlConnectionInternalSourceType
-    {
-        Principle,
-        Failover,
-        RoutingDestination
-    }
-
-    // DEVNOTE: Class to capture the duration spent in each SqlConnectionTimeoutErrorPhase.
-    internal class SqlConnectionTimeoutPhaseDuration
-    {
-        private readonly Stopwatch _swDuration = new Stopwatch();
-
-        internal void StartCapture()
-        {
-            Debug.Assert(_swDuration != null, "Time capture stopwatch cannot be null.");
-            _swDuration.Start();
-        }
-
-        internal void StopCapture()
-        {
-            //Debug.Assert(swDuration.IsRunning == true, "The stop operation of the stopwatch cannot be called when it is not running.");
-            if (_swDuration.IsRunning == true)
-                _swDuration.Stop();
-        }
-
-        internal long GetMilliSecondDuration()
-        {
-            // DEVNOTE: In a phase fails in between a phase, the stop watch may still be running.
-            // Hence the check to verify if the stop watch is running hasn't been added in.
-            return _swDuration.ElapsedMilliseconds;
-        }
-    }
-
-    internal class SqlConnectionTimeoutErrorInternal
-    {
-        private SqlConnectionTimeoutPhaseDuration[] _phaseDurations = null;
-        private SqlConnectionTimeoutPhaseDuration[] _originalPhaseDurations = null;
-
-        private SqlConnectionTimeoutErrorPhase _currentPhase = SqlConnectionTimeoutErrorPhase.Undefined;
-        private SqlConnectionInternalSourceType _currentSourceType = SqlConnectionInternalSourceType.Principle;
-        private bool _isFailoverScenario = false;
-
-        internal SqlConnectionTimeoutErrorPhase CurrentPhase
-        {
-            get { return _currentPhase; }
-        }
-
-        public SqlConnectionTimeoutErrorInternal()
-        {
-            _phaseDurations = new SqlConnectionTimeoutPhaseDuration[(int)SqlConnectionTimeoutErrorPhase.Count];
-            for (int i = 0; i < _phaseDurations.Length; i++)
-                _phaseDurations[i] = null;
-        }
-
-        public void SetFailoverScenario(bool useFailoverServer)
-        {
-            _isFailoverScenario = useFailoverServer;
-        }
-
-        public void SetInternalSourceType(SqlConnectionInternalSourceType sourceType)
-        {
-            _currentSourceType = sourceType;
-
-            if (_currentSourceType == SqlConnectionInternalSourceType.RoutingDestination)
-            {
-                // When we get routed, save the current phase durations so that we can use them in the error message later
-                Debug.Assert(_currentPhase == SqlConnectionTimeoutErrorPhase.PostLogin, "Should not be switching to the routing destination until Post Login is completed");
-                _originalPhaseDurations = _phaseDurations;
-                _phaseDurations = new SqlConnectionTimeoutPhaseDuration[(int)SqlConnectionTimeoutErrorPhase.Count];
-                SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin);
-            }
-        }
-
-        internal void ResetAndRestartPhase()
-        {
-            _currentPhase = SqlConnectionTimeoutErrorPhase.PreLoginBegin;
-            for (int i = 0; i < _phaseDurations.Length; i++)
-                _phaseDurations[i] = null;
-        }
-
-        internal void SetAndBeginPhase(SqlConnectionTimeoutErrorPhase timeoutErrorPhase)
-        {
-            _currentPhase = timeoutErrorPhase;
-            if (_phaseDurations[(int)timeoutErrorPhase] == null)
-            {
-                _phaseDurations[(int)timeoutErrorPhase] = new SqlConnectionTimeoutPhaseDuration();
-            }
-            _phaseDurations[(int)timeoutErrorPhase].StartCapture();
-        }
-
-        internal void EndPhase(SqlConnectionTimeoutErrorPhase timeoutErrorPhase)
-        {
-            Debug.Assert(_phaseDurations[(int)timeoutErrorPhase] != null, "End phase capture cannot be invoked when the phase duration object is a null.");
-            _phaseDurations[(int)timeoutErrorPhase].StopCapture();
-        }
-
-        internal void SetAllCompleteMarker()
-        {
-            _currentPhase = SqlConnectionTimeoutErrorPhase.Complete;
-        }
-
-        internal string GetErrorMessage()
-        {
-            StringBuilder errorBuilder;
-            string durationString;
-            switch (_currentPhase)
-            {
-                case SqlConnectionTimeoutErrorPhase.PreLoginBegin:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_Begin());
-                    durationString = SQLMessage.Duration_PreLogin_Begin(
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration());
-                    break;
-                case SqlConnectionTimeoutErrorPhase.InitializeConnection:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_InitializeConnection());
-                    durationString = SQLMessage.Duration_PreLogin_Begin(
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration());
-                    break;
-                case SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_SendHandshake());
-                    durationString = SQLMessage.Duration_PreLoginHandshake(
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration());
-                    break;
-                case SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout_PreLogin_ConsumeHandshake());
-                    durationString = SQLMessage.Duration_PreLoginHandshake(
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration());
-                    break;
-                case SqlConnectionTimeoutErrorPhase.LoginBegin:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout_Login_Begin());
-                    durationString = SQLMessage.Duration_Login_Begin(
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration());
-                    break;
-                case SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout_Login_ProcessConnectionAuth());
-                    durationString = SQLMessage.Duration_Login_ProcessConnectionAuth(
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration());
-                    break;
-                case SqlConnectionTimeoutErrorPhase.PostLogin:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout_PostLogin());
-                    durationString = SQLMessage.Duration_PostLogin(
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration(),
-                        _phaseDurations[(int)SqlConnectionTimeoutErrorPhase.PostLogin].GetMilliSecondDuration());
-                    break;
-                default:
-                    errorBuilder = new StringBuilder(SQLMessage.Timeout());
-                    durationString = null;
-                    break;
-            }
-
-            // This message is to be added only when within the various stages of a connection.
-            // In all other cases, it will default to the original error message.
-            if ((_currentPhase != SqlConnectionTimeoutErrorPhase.Undefined) && (_currentPhase != SqlConnectionTimeoutErrorPhase.Complete))
-            {
-                // NOTE: In case of a failover scenario, add a string that this failure occurred as part of the primary or secondary server
-                if (_isFailoverScenario)
-                {
-                    errorBuilder.Append("  ");
-                    errorBuilder.AppendFormat((IFormatProvider)null, SQLMessage.Timeout_FailoverInfo(), _currentSourceType);
-                }
-                else if (_currentSourceType == SqlConnectionInternalSourceType.RoutingDestination)
-                {
-                    errorBuilder.Append("  ");
-                    errorBuilder.AppendFormat((IFormatProvider)null, SQLMessage.Timeout_RoutingDestination(),
-                        _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.PreLoginBegin].GetMilliSecondDuration() +
-                        _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.InitializeConnection].GetMilliSecondDuration(),
-                        _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake].GetMilliSecondDuration() +
-                        _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake].GetMilliSecondDuration(),
-                        _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.LoginBegin].GetMilliSecondDuration(),
-                        _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth].GetMilliSecondDuration(),
-                        _originalPhaseDurations[(int)SqlConnectionTimeoutErrorPhase.PostLogin].GetMilliSecondDuration());
-                }
-            }
-
-            // NOTE: To display duration in each phase.
-            if (durationString != null)
-            {
-                errorBuilder.Append("  ");
-                errorBuilder.Append(durationString);
-            }
-
-            return errorBuilder.ToString();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCredential.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlCredential.cs
deleted file mode 100644 (file)
index 6a6434d..0000000
+++ /dev/null
@@ -1,51 +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.Data.Common;
-using System.Security;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlCredential
-    {
-        private readonly string _userId;
-        private readonly SecureString _password;
-
-        public SqlCredential(string userId, SecureString password)
-        {
-            if (userId == null)
-            {
-                throw ADP.ArgumentNull(nameof(userId));
-            }
-
-            if (userId.Length > TdsEnums.MAXLEN_USERNAME)
-            {
-                throw ADP.InvalidArgumentLength(nameof(userId), TdsEnums.MAXLEN_USERNAME);
-            }
-
-            if (password == null)
-            {
-                throw ADP.ArgumentNull(nameof(password));
-            }
-
-            if (password.Length > TdsEnums.MAXLEN_PASSWORD)
-            {
-                throw ADP.InvalidArgumentLength(nameof(password), TdsEnums.MAXLEN_PASSWORD);
-            }
-
-            if (!password.IsReadOnly())
-            {
-                throw ADP.MustBeReadOnly(nameof(password));
-            }
-
-            _userId = userId;
-            _password = password;
-        }
-
-        public string UserId => _userId;
-
-        public SecureString Password => _password;
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataAdapter.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataAdapter.cs
deleted file mode 100644 (file)
index 3041e5a..0000000
+++ /dev/null
@@ -1,249 +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;
-using System.ComponentModel;
-using System.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlDataAdapter : DbDataAdapter, IDbDataAdapter, ICloneable
-    {
-        private static readonly object EventRowUpdated = new object();
-        private static readonly object EventRowUpdating = new object();
-
-        private SqlCommand _deleteCommand, _insertCommand, _selectCommand, _updateCommand;
-
-        private SqlCommandSet _commandSet;
-        private int _updateBatchSize = 1;
-
-        public SqlDataAdapter() : base()
-        {
-            GC.SuppressFinalize(this);
-        }
-
-        public SqlDataAdapter(SqlCommand selectCommand) : this()
-        {
-            SelectCommand = selectCommand;
-        }
-
-        public SqlDataAdapter(string selectCommandText, string selectConnectionString) : this()
-        {
-            SqlConnection connection = new SqlConnection(selectConnectionString);
-            SelectCommand = new SqlCommand(selectCommandText, connection);
-        }
-
-        public SqlDataAdapter(string selectCommandText, SqlConnection selectConnection) : this()
-        {
-            SelectCommand = new SqlCommand(selectCommandText, selectConnection);
-        }
-
-        private SqlDataAdapter(SqlDataAdapter from) : base(from)
-        {   // Clone
-            GC.SuppressFinalize(this);
-        }
-
-        public new SqlCommand DeleteCommand
-        {
-            get { return _deleteCommand; }
-            set { _deleteCommand = value; }
-        }
-
-        IDbCommand IDbDataAdapter.DeleteCommand
-        {
-            get { return _deleteCommand; }
-            set { _deleteCommand = (SqlCommand)value; }
-        }
-
-        public new SqlCommand InsertCommand
-        {
-            get { return _insertCommand; }
-            set { _insertCommand = value; }
-        }
-
-        IDbCommand IDbDataAdapter.InsertCommand
-        {
-            get { return _insertCommand; }
-            set { _insertCommand = (SqlCommand)value; }
-        }
-
-        public new SqlCommand SelectCommand
-        {
-            get { return _selectCommand; }
-            set { _selectCommand = value; }
-        }
-
-        IDbCommand IDbDataAdapter.SelectCommand
-        {
-            get { return _selectCommand; }
-            set { _selectCommand = (SqlCommand)value; }
-        }
-
-        public new SqlCommand UpdateCommand
-        {
-            get { return _updateCommand; }
-            set { _updateCommand = value; }
-        }
-
-        IDbCommand IDbDataAdapter.UpdateCommand
-        {
-            get { return _updateCommand; }
-            set { _updateCommand = (SqlCommand)value; }
-        }
-
-        public override int UpdateBatchSize
-        {
-            get
-            {
-                return _updateBatchSize;
-            }
-            set
-            {
-                if (0 > value)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(UpdateBatchSize));
-                }
-                _updateBatchSize = value;
-            }
-        }
-
-        protected override int AddToBatch(IDbCommand command)
-        {
-            int commandIdentifier = _commandSet.CommandCount;
-            _commandSet.Append((SqlCommand)command);
-            return commandIdentifier;
-        }
-
-        protected override void ClearBatch()
-        {
-            _commandSet.Clear();
-        }
-
-        protected override int ExecuteBatch()
-        {
-            Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands");
-            return _commandSet.ExecuteNonQuery();
-        }
-
-        protected override IDataParameter GetBatchedParameter(int commandIdentifier, int parameterIndex)
-        {
-            Debug.Assert(commandIdentifier < _commandSet.CommandCount, "commandIdentifier out of range");
-            Debug.Assert(parameterIndex < _commandSet.GetParameterCount(commandIdentifier), "parameter out of range");
-            IDataParameter parameter = _commandSet.GetParameter(commandIdentifier, parameterIndex);
-            return parameter;
-        }
-
-        protected override bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out Exception error)
-        {
-            Debug.Assert(commandIdentifier < _commandSet.CommandCount, "commandIdentifier out of range");
-            return _commandSet.GetBatchedAffected(commandIdentifier, out recordsAffected, out error);
-        }
-
-        protected override void InitializeBatching()
-        {
-            _commandSet = new SqlCommandSet();
-            SqlCommand command = SelectCommand;
-            if (null == command)
-            {
-                command = InsertCommand;
-                if (null == command)
-                {
-                    command = UpdateCommand;
-                    if (null == command)
-                    {
-                        command = DeleteCommand;
-                    }
-                }
-            }
-            if (null != command)
-            {
-                _commandSet.Connection = command.Connection;
-                _commandSet.Transaction = command.Transaction;
-                _commandSet.CommandTimeout = command.CommandTimeout;
-            }
-        }
-
-        protected override void TerminateBatching()
-        {
-            if (null != _commandSet)
-            {
-                _commandSet.Dispose();
-                _commandSet = null;
-            }
-        }
-
-        object ICloneable.Clone()
-        {
-            return new SqlDataAdapter(this);
-        }
-
-        protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
-        {
-            return new SqlRowUpdatedEventArgs(dataRow, command, statementType, tableMapping);
-        }
-
-        protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
-        {
-            return new SqlRowUpdatingEventArgs(dataRow, command, statementType, tableMapping);
-        }
-
-        public event SqlRowUpdatedEventHandler RowUpdated
-        {
-            add
-            {
-                Events.AddHandler(EventRowUpdated, value);
-            }
-            remove
-            {
-                Events.RemoveHandler(EventRowUpdated, value);
-            }
-        }
-
-        public event SqlRowUpdatingEventHandler RowUpdating
-        {
-            add
-            {
-                SqlRowUpdatingEventHandler handler = (SqlRowUpdatingEventHandler)Events[EventRowUpdating];
-
-                // Prevent someone from registering two different command builders on the adapter by
-                // silently removing the old one.
-                if ((null != handler) && (value.Target is DbCommandBuilder))
-                {
-                    SqlRowUpdatingEventHandler d = (SqlRowUpdatingEventHandler)ADP.FindBuilder(handler);
-                    if (null != d)
-                    {
-                        Events.RemoveHandler(EventRowUpdating, d);
-                    }
-                }
-                Events.AddHandler(EventRowUpdating, value);
-            }
-            remove
-            {
-                Events.RemoveHandler(EventRowUpdating, value);
-            }
-        }
-
-        protected override void OnRowUpdated(RowUpdatedEventArgs value)
-        {
-            SqlRowUpdatedEventHandler handler = (SqlRowUpdatedEventHandler)Events[EventRowUpdated];
-            if ((null != handler) && (value is SqlRowUpdatedEventArgs))
-            {
-                handler(this, (SqlRowUpdatedEventArgs)value);
-            }
-            base.OnRowUpdated(value);
-        }
-
-        protected override void OnRowUpdating(RowUpdatingEventArgs value)
-        {
-            SqlRowUpdatingEventHandler handler = (SqlRowUpdatingEventHandler)Events[EventRowUpdating];
-            if ((null != handler) && (value is SqlRowUpdatingEventArgs))
-            {
-                handler(this, (SqlRowUpdatingEventArgs)value);
-            }
-            base.OnRowUpdating(value);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs
deleted file mode 100644 (file)
index dbad81a..0000000
+++ /dev/null
@@ -1,5038 +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.ObjectModel;
-using System.Data.Common;
-using System.Data.ProviderBase;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.IO;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-
-using Microsoft.SqlServer.Server;
-using System.Globalization;
-
-namespace System.Data.SqlClient
-{
-    public class SqlDataReader : DbDataReader, IDataReader, IDbColumnSchemaGenerator
-    {
-        private enum ALTROWSTATUS
-        {
-            Null = 0,           // default and after Done
-            AltRow,             // after calling NextResult and the first AltRow is available for read
-            Done,               // after consuming the value (GetValue -> GetValueInternal)
-        }
-
-        internal class SharedState
-        { // parameters needed to execute cleanup from parser
-            internal int _nextColumnHeaderToRead;
-            internal int _nextColumnDataToRead;
-            internal long _columnDataBytesRemaining;
-            internal bool _dataReady; // ready to ProcessRow
-        }
-
-        internal SharedState _sharedState = new SharedState();
-
-        private TdsParser _parser;
-        private TdsParserStateObject _stateObj;
-        private SqlCommand _command;
-        private SqlConnection _connection;
-        private int _defaultLCID;
-        private bool _haltRead;               // bool to denote whether we have read first row for single row behavior
-        private bool _metaDataConsumed;
-        private bool _browseModeInfoConsumed;
-        private bool _isClosed;
-        private bool _isInitialized;          // Webdata 104560
-        private bool _hasRows;
-        private ALTROWSTATUS _altRowStatus;
-        private int _recordsAffected = -1;
-        private readonly long _defaultTimeoutMilliseconds;
-        private readonly SqlConnectionString.TypeSystem _typeSystem;
-
-        // SQLStatistics support
-        private SqlStatistics _statistics;
-        private SqlBuffer[] _data;         // row buffer, filled in by ReadColumnData()
-        private SqlStreamingXml _streamingXml; // Used by Getchars on an Xml column for sequential access
-
-        // buffers and metadata
-        private _SqlMetaDataSet _metaData;                 // current metaData for the stream, it is lazily loaded
-        private _SqlMetaDataSetCollection _altMetaDataSetCollection;
-        private FieldNameLookup _fieldNameLookup;
-        private CommandBehavior _commandBehavior;
-
-        private static int s_objectTypeCount; // Bid counter
-        private static readonly ReadOnlyCollection<DbColumn> s_emptySchema = new ReadOnlyCollection<DbColumn>(Array.Empty<DbColumn>());
-        internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
-
-        // metadata (no explicit table, use 'Table')
-        private MultiPartTableName[] _tableNames = null;
-        private string _resetOptionsString;
-
-        private int _lastColumnWithDataChunkRead;
-        private long _columnDataBytesRead;       // last byte read by user
-        private long _columnDataCharsRead;       // last char read by user
-        private char[] _columnDataChars;
-        private int _columnDataCharsIndex;      // Column index that is currently loaded in _columnDataChars
-
-        private Task _currentTask;
-        private Snapshot _snapshot;
-        private readonly CancellationTokenSource _cancelAsyncOnCloseTokenSource;
-        private readonly CancellationToken _cancelAsyncOnCloseToken;
-
-        // Used for checking if the Type parameter provided to GetValue<T> is an INullable
-        internal static readonly Type _typeofINullable = typeof(INullable);
-        private static readonly Type s_typeofSqlString = typeof(SqlString);
-
-        private SqlSequentialStream _currentStream;
-        private SqlSequentialTextReader _currentTextReader;
-
-        internal SqlDataReader(SqlCommand command, CommandBehavior behavior)
-        {
-            _command = command;
-            _commandBehavior = behavior;
-            if (_command != null)
-            {
-                _defaultTimeoutMilliseconds = (long)command.CommandTimeout * 1000L;
-                _connection = command.Connection;
-                if (_connection != null)
-                {
-                    _statistics = _connection.Statistics;
-                    _typeSystem = _connection.TypeSystem;
-                }
-            }
-            _sharedState._dataReady = false;
-            _metaDataConsumed = false;
-            _hasRows = false;
-            _browseModeInfoConsumed = false;
-            _currentStream = null;
-            _currentTextReader = null;
-            _cancelAsyncOnCloseTokenSource = new CancellationTokenSource();
-            _cancelAsyncOnCloseToken = _cancelAsyncOnCloseTokenSource.Token;
-            _columnDataCharsIndex = -1;
-        }
-
-        internal bool BrowseModeInfoConsumed
-        {
-            set
-            {
-                _browseModeInfoConsumed = value;
-            }
-        }
-
-        internal SqlCommand Command
-        {
-            get
-            {
-                return _command;
-            }
-        }
-
-        protected SqlConnection Connection
-        {
-            get
-            {
-                return _connection;
-            }
-        }
-
-        public override int Depth
-        {
-            get
-            {
-                if (this.IsClosed)
-                {
-                    throw ADP.DataReaderClosed();
-                }
-
-                return 0;
-            }
-        }
-
-        // fields/attributes collection
-        public override int FieldCount
-        {
-            get
-            {
-                if (this.IsClosed)
-                {
-                    throw ADP.DataReaderClosed();
-                }
-                if (_currentTask != null)
-                {
-                    throw ADP.AsyncOperationPending();
-                }
-
-                if (MetaData == null)
-                {
-                    return 0;
-                }
-
-                return _metaData.Length;
-            }
-        }
-
-        public override bool HasRows
-        {
-            get
-            {
-                if (this.IsClosed)
-                {
-                    throw ADP.DataReaderClosed();
-                }
-                if (_currentTask != null)
-                {
-                    throw ADP.AsyncOperationPending();
-                }
-
-                return _hasRows;
-            }
-        }
-
-        public override bool IsClosed
-        {
-            get
-            {
-                return _isClosed;
-            }
-        }
-
-        internal bool IsInitialized
-        {
-            get
-            {
-                return _isInitialized;
-            }
-            set
-            {
-                Debug.Assert(value, "attempting to uninitialize a data reader?");
-                _isInitialized = value;
-            }
-        }
-
-        // NOTE: For PLP values this indicates the amount of data left in the current chunk (or 0 if there are no more chunks left)
-        internal long ColumnDataBytesRemaining()
-        {
-            // If there are an unknown (-1) number of bytes left for a PLP, read its size
-            if (-1 == _sharedState._columnDataBytesRemaining)
-            {
-                _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
-            }
-
-            return _sharedState._columnDataBytesRemaining;
-        }
-
-        internal _SqlMetaDataSet MetaData
-        {
-            get
-            {
-                if (IsClosed)
-                {
-                    throw ADP.DataReaderClosed();
-                }
-                // metaData comes in pieces: colmetadata, tabname, colinfo, etc
-                // if we have any metaData, return it.  If we have none,
-                // then fetch it
-                if (_metaData == null && !_metaDataConsumed)
-                {
-                    if (_currentTask != null)
-                    {
-                        throw SQL.PendingBeginXXXExists();
-                    }
-
-                    Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-                    if (!TryConsumeMetaData())
-                    {
-                        throw SQL.SynchronousCallMayNotPend();
-                    }
-                }
-                return _metaData;
-            }
-        }
-
-        internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData()
-        {
-            SmiExtendedMetaData[] metaDataReturn = null;
-            _SqlMetaDataSet metaData = this.MetaData;
-
-            if (null != metaData && 0 < metaData.Length)
-            {
-                metaDataReturn = new SmiExtendedMetaData[metaData.visibleColumns];
-
-                for (int index = 0; index < metaData.Length; index++)
-                {
-                    _SqlMetaData colMetaData = metaData[index];
-
-                    if (!colMetaData.IsHidden)
-                    {
-                        SqlCollation collation = colMetaData.collation;
-
-                        string typeSpecificNamePart1 = null;
-                        string typeSpecificNamePart2 = null;
-                        string typeSpecificNamePart3 = null;
-
-                        if (SqlDbType.Xml == colMetaData.type)
-                        {
-                            typeSpecificNamePart1 = colMetaData.xmlSchemaCollection?.Database;
-                            typeSpecificNamePart2 = colMetaData.xmlSchemaCollection?.OwningSchema;
-                            typeSpecificNamePart3 = colMetaData.xmlSchemaCollection?.Name;
-                        }
-                        else if (SqlDbType.Udt == colMetaData.type)
-                        {
-                            Connection.CheckGetExtendedUDTInfo(colMetaData, true); // Ensure that colMetaData.udtType is set
-
-                            typeSpecificNamePart1 = colMetaData.udt?.DatabaseName;
-                            typeSpecificNamePart2 = colMetaData.udt?.SchemaName;
-                            typeSpecificNamePart3 = colMetaData.udt?.TypeName;
-                        }
-
-                        int length = colMetaData.length;
-                        if (length > TdsEnums.MAXSIZE)
-                        {
-                            length = (int)SmiMetaData.UnlimitedMaxLengthIndicator;
-                        }
-                        else if (SqlDbType.NChar == colMetaData.type
-                                || SqlDbType.NVarChar == colMetaData.type)
-                        {
-                            length /= ADP.CharSize;
-                        }
-
-                        metaDataReturn[index] =
-                            new SmiQueryMetaData(
-                                colMetaData.type,
-                                length,
-                                colMetaData.precision,
-                                colMetaData.scale,
-                                (null != collation) ? collation.LCID : _defaultLCID,
-                                (null != collation) ? collation.SqlCompareOptions : SqlCompareOptions.None,
-                                colMetaData.udt?.Type,
-                                false, // isMultiValued
-                                null, // fieldmetadata
-                                null, // extended properties
-                                colMetaData.column,
-                                typeSpecificNamePart1,
-                                typeSpecificNamePart2,
-                                typeSpecificNamePart3,
-                                colMetaData.IsNullable,
-                                colMetaData.serverName,
-                                colMetaData.catalogName,
-                                colMetaData.schemaName,
-                                colMetaData.tableName,
-                                colMetaData.baseColumn,
-                                colMetaData.IsKey,
-                                colMetaData.IsIdentity,
-                                colMetaData.IsReadOnly,
-                                colMetaData.IsExpression,
-                                colMetaData.IsDifferentName,
-                                colMetaData.IsHidden
-                            );
-                    }
-                }
-            }
-
-            return metaDataReturn;
-        }
-
-        public override int RecordsAffected
-        {
-            get
-            {
-                if (null != _command)
-                    return _command.InternalRecordsAffected;
-
-                // cached locally for after Close() when command is nulled out
-                return _recordsAffected;
-            }
-        }
-
-        internal string ResetOptionsString
-        {
-            set
-            {
-                _resetOptionsString = value;
-            }
-        }
-
-        private SqlStatistics Statistics
-        {
-            get
-            {
-                return _statistics;
-            }
-        }
-
-        internal MultiPartTableName[] TableNames
-        {
-            get
-            {
-                return _tableNames;
-            }
-            set
-            {
-                _tableNames = value;
-            }
-        }
-
-        public override int VisibleFieldCount
-        {
-            get
-            {
-                if (this.IsClosed)
-                {
-                    throw ADP.DataReaderClosed();
-                }
-                _SqlMetaDataSet md = this.MetaData;
-                if (md == null)
-                {
-                    return 0;
-                }
-                return (md.visibleColumns);
-            }
-        }
-
-        // this operator
-        public override object this[int i]
-        {
-            get
-            {
-                return GetValue(i);
-            }
-        }
-
-        public override object this[string name]
-        {
-            get
-            {
-                return GetValue(GetOrdinal(name));
-            }
-        }
-
-        internal void Bind(TdsParserStateObject stateObj)
-        {
-            Debug.Assert(null != stateObj, "null stateobject");
-
-            Debug.Assert(null == _snapshot, "Should not change during execution of asynchronous command");
-
-            stateObj.Owner = this;
-            _stateObj = stateObj;
-            _parser = stateObj.Parser;
-            _defaultLCID = _parser.DefaultLCID;
-        }
-
-        internal DataTable BuildSchemaTable()
-        {
-            _SqlMetaDataSet md = this.MetaData;
-            Debug.Assert(null != md, "BuildSchemaTable - unexpected null metadata information");
-
-            DataTable schemaTable = new DataTable("SchemaTable");
-            schemaTable.Locale = CultureInfo.InvariantCulture;
-            schemaTable.MinimumCapacity = md.Length;
-
-            DataColumn columnName = new DataColumn(SchemaTableColumn.ColumnName, typeof(string));
-            DataColumn ordinal = new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(int));
-            DataColumn size = new DataColumn(SchemaTableColumn.ColumnSize, typeof(int));
-            DataColumn precision = new DataColumn(SchemaTableColumn.NumericPrecision, typeof(short));
-            DataColumn scale = new DataColumn(SchemaTableColumn.NumericScale, typeof(short));
-
-            DataColumn dataType = new DataColumn(SchemaTableColumn.DataType, typeof(System.Type));
-            DataColumn providerSpecificDataType = new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type));
-            DataColumn nonVersionedProviderType = new DataColumn(SchemaTableColumn.NonVersionedProviderType, typeof(int));
-            DataColumn providerType = new DataColumn(SchemaTableColumn.ProviderType, typeof(int));
-
-            DataColumn isLong = new DataColumn(SchemaTableColumn.IsLong, typeof(bool));
-            DataColumn allowDBNull = new DataColumn(SchemaTableColumn.AllowDBNull, typeof(bool));
-            DataColumn isReadOnly = new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(bool));
-            DataColumn isRowVersion = new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(bool));
-
-            DataColumn isUnique = new DataColumn(SchemaTableColumn.IsUnique, typeof(bool));
-            DataColumn isKey = new DataColumn(SchemaTableColumn.IsKey, typeof(bool));
-            DataColumn isAutoIncrement = new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool));
-            DataColumn isHidden = new DataColumn(SchemaTableOptionalColumn.IsHidden, typeof(bool));
-
-            DataColumn baseCatalogName = new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(string));
-            DataColumn baseSchemaName = new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(string));
-            DataColumn baseTableName = new DataColumn(SchemaTableColumn.BaseTableName, typeof(string));
-            DataColumn baseColumnName = new DataColumn(SchemaTableColumn.BaseColumnName, typeof(string));
-
-            // unique to SqlClient
-            DataColumn baseServerName = new DataColumn(SchemaTableOptionalColumn.BaseServerName, typeof(string));
-            DataColumn isAliased = new DataColumn(SchemaTableColumn.IsAliased, typeof(bool));
-            DataColumn isExpression = new DataColumn(SchemaTableColumn.IsExpression, typeof(bool));
-            DataColumn isIdentity = new DataColumn("IsIdentity", typeof(bool));
-            DataColumn dataTypeName = new DataColumn("DataTypeName", typeof(string));
-            DataColumn udtAssemblyQualifiedName = new DataColumn("UdtAssemblyQualifiedName", typeof(string));
-            // Xml metadata specific
-            DataColumn xmlSchemaCollectionDatabase = new DataColumn("XmlSchemaCollectionDatabase", typeof(string));
-            DataColumn xmlSchemaCollectionOwningSchema = new DataColumn("XmlSchemaCollectionOwningSchema", typeof(string));
-            DataColumn xmlSchemaCollectionName = new DataColumn("XmlSchemaCollectionName", typeof(string));
-            // SparseColumnSet
-            DataColumn isColumnSet = new DataColumn("IsColumnSet", typeof(bool));
-
-            ordinal.DefaultValue = 0;
-            isLong.DefaultValue = false;
-
-            DataColumnCollection columns = schemaTable.Columns;
-
-            // must maintain order for backward compatibility
-            columns.Add(columnName);
-            columns.Add(ordinal);
-            columns.Add(size);
-            columns.Add(precision);
-            columns.Add(scale);
-            columns.Add(isUnique);
-            columns.Add(isKey);
-            columns.Add(baseServerName);
-            columns.Add(baseCatalogName);
-            columns.Add(baseColumnName);
-            columns.Add(baseSchemaName);
-            columns.Add(baseTableName);
-            columns.Add(dataType);
-            columns.Add(allowDBNull);
-            columns.Add(providerType);
-            columns.Add(isAliased);
-            columns.Add(isExpression);
-            columns.Add(isIdentity);
-            columns.Add(isAutoIncrement);
-            columns.Add(isRowVersion);
-            columns.Add(isHidden);
-            columns.Add(isLong);
-            columns.Add(isReadOnly);
-            columns.Add(providerSpecificDataType);
-            columns.Add(dataTypeName);
-            columns.Add(xmlSchemaCollectionDatabase);
-            columns.Add(xmlSchemaCollectionOwningSchema);
-            columns.Add(xmlSchemaCollectionName);
-            columns.Add(udtAssemblyQualifiedName);
-            columns.Add(nonVersionedProviderType);
-            columns.Add(isColumnSet);
-
-            for (int i = 0; i < md.Length; i++)
-            {
-                _SqlMetaData col = md[i];
-                DataRow schemaRow = schemaTable.NewRow();
-
-                schemaRow[columnName] = col.column;
-                schemaRow[ordinal] = col.ordinal;
-                //
-                // be sure to return character count for string types, byte count otherwise
-                // col.length is always byte count so for unicode types, half the length
-                //
-                // For MAX and XML datatypes, we get 0x7fffffff from the server. Do not divide this.
-                schemaRow[size] = (col.metaType.IsSizeInCharacters && (col.length != 0x7fffffff)) ? (col.length / 2) : col.length;
-
-                schemaRow[dataType] = GetFieldTypeInternal(col);
-                schemaRow[providerSpecificDataType] = GetProviderSpecificFieldTypeInternal(col);
-                schemaRow[nonVersionedProviderType] = (int)col.type; // SqlDbType enum value - does not change with TypeSystem.
-                schemaRow[dataTypeName] = GetDataTypeNameInternal(col);
-
-                if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType)
-                {
-                    schemaRow[providerType] = SqlDbType.NVarChar;
-                    switch (col.type)
-                    {
-                        case SqlDbType.Date:
-                            schemaRow[size] = TdsEnums.WHIDBEY_DATE_LENGTH;
-                            break;
-                        case SqlDbType.Time:
-                            Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for Time column: " + col.scale);
-                            schemaRow[size] = TdsEnums.WHIDBEY_TIME_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
-                            break;
-                        case SqlDbType.DateTime2:
-                            Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for DateTime2 column: " + col.scale);
-                            schemaRow[size] = TdsEnums.WHIDBEY_DATETIME2_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
-                            break;
-                        case SqlDbType.DateTimeOffset:
-                            Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for DateTimeOffset column: " + col.scale);
-                            schemaRow[size] = TdsEnums.WHIDBEY_DATETIMEOFFSET_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
-                            break;
-                    }
-                }
-                else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsLargeUdt)
-                {
-                    if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005)
-                    {
-                        schemaRow[providerType] = SqlDbType.VarBinary;
-                    }
-                    else
-                    {
-                        // TypeSystem.SQLServer2000
-                        schemaRow[providerType] = SqlDbType.Image;
-                    }
-                }
-                else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
-                {
-                    // TypeSystem.SQLServer2005 and above
-
-                    // SqlDbType enum value - always the actual type for SQLServer2005.
-                    schemaRow[providerType] = (int)col.type;
-
-                    if (col.type == SqlDbType.Udt)
-                    { // Additional metadata for UDTs.
-                        Debug.Assert(Connection.IsKatmaiOrNewer, "Invalid Column type received from the server");
-                        schemaRow[udtAssemblyQualifiedName] = col.udt?.AssemblyQualifiedName;
-                    }
-                    else if (col.type == SqlDbType.Xml)
-                    { // Additional metadata for Xml.
-                        Debug.Assert(Connection.IsKatmaiOrNewer, "Invalid DataType (Xml) for the column");
-                        schemaRow[xmlSchemaCollectionDatabase] = col.xmlSchemaCollection?.Database;
-                        schemaRow[xmlSchemaCollectionOwningSchema] = col.xmlSchemaCollection?.OwningSchema;
-                        schemaRow[xmlSchemaCollectionName] = col.xmlSchemaCollection?.Name;
-                    }
-                }
-                else
-                {
-                    // TypeSystem.SQLServer2000
-
-                    // SqlDbType enum value - variable for certain types when SQLServer2000.
-                    schemaRow[providerType] = GetVersionedMetaType(col.metaType).SqlDbType;
-                }
-
-                if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.precision)
-                {
-                    schemaRow[precision] = col.precision;
-                }
-                else
-                {
-                    schemaRow[precision] = col.metaType.Precision;
-                }
-
-                if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType)
-                {
-                    schemaRow[scale] = MetaType.MetaNVarChar.Scale;
-                }
-                else if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale)
-                {
-                    schemaRow[scale] = col.scale;
-                }
-                else
-                {
-                    schemaRow[scale] = col.metaType.Scale;
-                }
-
-                schemaRow[allowDBNull] = col.IsNullable;
-
-                // If no ColInfo token received, do not set value, leave as null.
-                if (_browseModeInfoConsumed)
-                {
-                    schemaRow[isAliased] = col.IsDifferentName;
-                    schemaRow[isKey] = col.IsKey;
-                    schemaRow[isHidden] = col.IsHidden;
-                    schemaRow[isExpression] = col.IsExpression;
-                }
-
-                schemaRow[isIdentity] = col.IsIdentity;
-                schemaRow[isAutoIncrement] = col.IsIdentity;
-
-                schemaRow[isLong] = col.metaType.IsLong;
-
-                // mark unique for timestamp columns
-                if (SqlDbType.Timestamp == col.type)
-                {
-                    schemaRow[isUnique] = true;
-                    schemaRow[isRowVersion] = true;
-                }
-                else
-                {
-                    schemaRow[isUnique] = false;
-                    schemaRow[isRowVersion] = false;
-                }
-
-                schemaRow[isReadOnly] = col.IsReadOnly;
-                schemaRow[isColumnSet] = col.IsColumnSet;
-
-                if (!string.IsNullOrEmpty(col.serverName))
-                {
-                    schemaRow[baseServerName] = col.serverName;
-                }
-                if (!string.IsNullOrEmpty(col.catalogName))
-                {
-                    schemaRow[baseCatalogName] = col.catalogName;
-                }
-                if (!string.IsNullOrEmpty(col.schemaName))
-                {
-                    schemaRow[baseSchemaName] = col.schemaName;
-                }
-                if (!string.IsNullOrEmpty(col.tableName))
-                {
-                    schemaRow[baseTableName] = col.tableName;
-                }
-                if (!string.IsNullOrEmpty(col.baseColumn))
-                {
-                    schemaRow[baseColumnName] = col.baseColumn;
-                }
-                else if (!string.IsNullOrEmpty(col.column))
-                {
-                    schemaRow[baseColumnName] = col.column;
-                }
-
-                schemaTable.Rows.Add(schemaRow);
-                schemaRow.AcceptChanges();
-            }
-
-            // mark all columns as readonly
-            foreach (DataColumn column in columns)
-            {
-                column.ReadOnly = true; // MDAC 70943
-            }
-
-            return schemaTable;
-        }
-
-        internal void Cancel(SqlCommand command)
-        {
-            Debug.Assert(command == _command, "Calling command from an object that isn't this reader's command");
-            TdsParserStateObject stateObj = _stateObj;
-            if (null != stateObj)
-            {
-                stateObj.Cancel(command);
-            }
-        }
-
-        // wipe any data off the wire from a partial read
-        // and reset all pointers for sequential access
-        private bool TryCleanPartialRead()
-        {
-            AssertReaderState(requireData: true, permitAsync: true);
-
-            // VSTS DEVDIV2 380446: It is possible that read attempt we are cleaning after ended with partially
-            // processed header (if it falls between network packets). In this case the first thing to do is to
-            // finish reading the header, otherwise code will start treating unread header as TDS payload.
-            if (_stateObj._partialHeaderBytesRead > 0)
-            {
-                if (!_stateObj.TryProcessHeader())
-                {
-                    return false;
-                }
-            }
-
-            // following cases for sequential read
-            // i. user called read but didn't fetch anything
-            // iia. user called read and fetched a subset of the columns
-            // iib. user called read and fetched a subset of the column data
-
-            // Wipe out any Streams or TextReaders
-            if (-1 != _lastColumnWithDataChunkRead)
-            {
-                CloseActiveSequentialStreamAndTextReader();
-            }
-
-            // i. user called read but didn't fetch anything
-            if (0 == _sharedState._nextColumnHeaderToRead)
-            {
-                if (!_stateObj.Parser.TrySkipRow(_metaData, _stateObj))
-                {
-                    return false;
-                }
-            }
-            else
-            {
-                // iia.  if we still have bytes left from a partially read column, skip
-                if (!TryResetBlobState())
-                {
-                    return false;
-                }
-
-                // iib.
-                // now read the remaining values off the wire for this row
-                if (!_stateObj.Parser.TrySkipRow(_metaData, _sharedState._nextColumnHeaderToRead, _stateObj))
-                {
-                    return false;
-                }
-            }
-
-#if DEBUG
-            if (_stateObj._pendingData)
-            {
-                byte token;
-                if (!_stateObj.TryPeekByte(out token))
-                {
-                    return false;
-                }
-
-                Debug.Assert(TdsParser.IsValidTdsToken(token), $"Invalid token after performing CleanPartialRead: {token,-2:X2}");
-            }
-#endif
-            _sharedState._dataReady = false;
-
-            return true;
-        }
-
-        private void CleanPartialReadReliable()
-        {
-            AssertReaderState(requireData: true, permitAsync: false);
-
-            bool result = TryCleanPartialRead();
-            Debug.Assert(result, "Should not pend on sync call");
-            Debug.Assert(!_sharedState._dataReady, "_dataReady should be cleared");
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            if (disposing)
-            {
-                Close();
-            }
-            base.Dispose(disposing);
-        }
-
-        public override void Close()
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                TdsParserStateObject stateObj = _stateObj;
-
-                // Request that the current task is stopped
-                _cancelAsyncOnCloseTokenSource.Cancel();
-                var currentTask = _currentTask;
-                if ((currentTask != null) && (!currentTask.IsCompleted))
-                {
-                    try
-                    {
-                        // Wait for the task to complete
-                        ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
-
-                        // Ensure that we've finished reading any pending data
-                        var networkPacketTaskSource = stateObj._networkPacketTaskSource;
-                        if (networkPacketTaskSource != null)
-                        {
-                            ((IAsyncResult)networkPacketTaskSource.Task).AsyncWaitHandle.WaitOne();
-                        }
-                    }
-                    catch (Exception)
-                    {
-                        // If we receive any exceptions while waiting, something has gone horribly wrong and we need to doom the connection and fast-fail the reader
-                        _connection.InnerConnection.DoomThisConnection();
-                        _isClosed = true;
-
-                        if (stateObj != null)
-                        {
-                            lock (stateObj)
-                            {
-                                _stateObj = null;
-                                _command = null;
-                                _connection = null;
-                            }
-                        }
-
-                        throw;
-                    }
-                }
-
-                // Close down any active Streams and TextReaders (this will also wait for them to finish their async tasks)
-                // NOTE: This must be done outside of the lock on the stateObj otherwise it will deadlock with CleanupAfterAsyncInvocation
-                CloseActiveSequentialStreamAndTextReader();
-
-                if (stateObj != null)
-                {
-                    // protect against concurrent close and cancel
-                    lock (stateObj)
-                    {
-                        if (_stateObj != null)
-                        {  // reader not closed while we waited for the lock
-                            // TryCloseInternal will clear out the snapshot when it is done
-                            if (_snapshot != null)
-                            {
-#if DEBUG
-                                // The stack trace for replays will differ since they weren't captured during close
-                                stateObj._permitReplayStackTraceToDiffer = true;
-#endif
-                                PrepareForAsyncContinuation();
-                            }
-
-                            SetTimeout(_defaultTimeoutMilliseconds);
-
-                            // Close can be called from async methods in error cases,
-                            // in which case we need to switch to syncOverAsync
-                            stateObj._syncOverAsync = true;
-
-                            if (!TryCloseInternal(true /*closeReader*/))
-                            {
-                                throw SQL.SynchronousCallMayNotPend();
-                            }
-                            // DO NOT USE stateObj after this point - it has been returned to the TdsParser's session pool and potentially handed out to another thread
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private bool TryCloseInternal(bool closeReader)
-        {
-            TdsParser parser = _parser;
-            TdsParserStateObject stateObj = _stateObj;
-            bool closeConnection = (IsCommandBehavior(CommandBehavior.CloseConnection));
-            bool aborting = false;
-            bool cleanDataFailed = false;
-
-            try
-            {
-                if ((!_isClosed) && (parser != null) && (stateObj != null) && (stateObj._pendingData))
-                {
-                    // It is possible for this to be called during connection close on a
-                    // broken connection, so check state first.
-                    if (parser.State == TdsParserState.OpenLoggedIn)
-                    {
-                        // if user called read but didn't fetch any values, skip the row
-                        // same applies after NextResult on ALTROW because NextResult starts rowconsumption in that case ...
-
-                        Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, $"The SniContext should be Snix_Read but it actually is {stateObj.SniContext}");
-
-                        if (_altRowStatus == ALTROWSTATUS.AltRow)
-                        {
-                            _sharedState._dataReady = true;      // set _sharedState._dataReady to not confuse CleanPartialRead
-                        }
-                        _stateObj._internalTimeout = false;
-                        if (_sharedState._dataReady)
-                        {
-                            cleanDataFailed = true;
-                            if (TryCleanPartialRead())
-                            {
-                                cleanDataFailed = false;
-                            }
-                            else
-                            {
-                                return false;
-                            }
-                        }
-#if DEBUG
-                        else
-                        {
-                            byte token;
-                            if (!_stateObj.TryPeekByte(out token))
-                            {
-                                return false;
-                            }
-
-                            Debug.Assert(TdsParser.IsValidTdsToken(token), $"DataReady is false, but next token is invalid: {token,-2:X2}");
-                        }
-#endif
-
-
-                        bool ignored;
-                        if (!parser.TryRun(RunBehavior.Clean, _command, this, null, stateObj, out ignored))
-                        {
-                            return false;
-                        }
-                    }
-                }
-
-                RestoreServerSettings(parser, stateObj);
-                return true;
-            }
-            finally
-            {
-                if (aborting)
-                {
-                    _isClosed = true;
-                    _command = null; // we are done at this point, don't allow navigation to the connection
-                    _connection = null;
-                    _statistics = null;
-                    _stateObj = null;
-                    _parser = null;
-                }
-                else if (closeReader)
-                {
-                    bool wasClosed = _isClosed;
-                    _isClosed = true;
-                    _parser = null;
-                    _stateObj = null;
-                    _data = null;
-
-                    if (_snapshot != null)
-                    {
-                        CleanupAfterAsyncInvocationInternal(stateObj);
-                    }
-
-                    // Note the order here is extremely important:
-                    //
-                    // (1) First, we remove the reader from the reference collection
-                    //     to prevent it from being forced closed by the parser if
-                    //     any future work occurs.
-                    //
-                    // (2) Next, we ensure that cancellation can no longer happen by
-                    //     calling CloseSession.
-
-                    if (Connection != null)
-                    {
-                        Connection.RemoveWeakReference(this);  // This doesn't catch everything -- the connection may be closed, but it prevents dead readers from clogging the collection
-                    }
-
-
-                    // IsClosed may be true if CloseReaderFromConnection was called - in which case, the session has already been closed
-                    if ((!wasClosed) && (null != stateObj))
-                    {
-                        if (!cleanDataFailed)
-                        {
-                            stateObj.CloseSession();
-                        }
-                        else
-                        {
-                            if (parser != null)
-                            {
-                                parser.State = TdsParserState.Broken; // We failed while draining data, so TDS pointer can be between tokens - cannot recover
-                                parser.PutSession(stateObj);
-                                parser.Connection.BreakConnection();
-                            }
-                        }
-                    }
-                    // DO NOT USE stateObj after this point - it has been returned to the TdsParser's session pool and potentially handed out to another thread
-
-                    // do not retry here
-                    bool result = TrySetMetaData(null, false);
-                    Debug.Assert(result, "Should not pend a synchronous request");
-                    _fieldNameLookup = null;
-
-                    // if the user calls ExecuteReader(CommandBehavior.CloseConnection)
-                    // then we close down the connection when we are done reading results
-                    if (closeConnection)
-                    {
-                        if (Connection != null)
-                        {
-                            Connection.Close();
-                        }
-                    }
-                    if (_command != null)
-                    {
-                        // cache recordsaffected to be returnable after DataReader.Close();
-                        _recordsAffected = _command.InternalRecordsAffected;
-                    }
-
-                    _command = null; // we are done at this point, don't allow navigation to the connection
-                    _connection = null;
-                    _statistics = null;
-                }
-            }
-        }
-
-        internal virtual void CloseReaderFromConnection()
-        {
-            var parser = _parser;
-            Debug.Assert(parser == null || parser.State != TdsParserState.OpenNotLoggedIn, "Reader on a connection that is not logged in");
-            if ((parser != null) && (parser.State == TdsParserState.OpenLoggedIn))
-            {
-                // Connection is ok - proper cleanup
-                // NOTE: This is NOT thread-safe
-                Close();
-            }
-            else
-            {
-                // Connection is broken - quick cleanup
-                // NOTE: This MUST be thread-safe as a broken connection can happen at any time
-
-                var stateObj = _stateObj;
-                _isClosed = true;
-                // Request that the current task is stopped
-                _cancelAsyncOnCloseTokenSource.Cancel();
-                if (stateObj != null)
-                {
-                    var networkPacketTaskSource = stateObj._networkPacketTaskSource;
-                    if (networkPacketTaskSource != null)
-                    {
-                        // If the connection is closed or broken, this will never complete
-                        networkPacketTaskSource.TrySetException(ADP.ClosedConnectionError());
-                    }
-                    if (_snapshot != null)
-                    {
-                        // CleanWire will do cleanup - so we don't really care about the snapshot
-                        CleanupAfterAsyncInvocationInternal(stateObj, resetNetworkPacketTaskSource: false);
-                    }
-                    // Switch to sync to prepare for cleanwire
-                    stateObj._syncOverAsync = true;
-                    // Remove owner (this will allow the stateObj to be disposed after the connection is closed)
-                    stateObj.RemoveOwner();
-                }
-            }
-        }
-
-        private bool TryConsumeMetaData()
-        {
-            // warning:  Don't check the MetaData property within this function
-            // warning:  as it will be a reentrant call
-            while (_parser != null && _stateObj != null && _stateObj._pendingData && !_metaDataConsumed)
-            {
-                if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
-                {
-                    // Happened for DEVDIV2:180509    (SqlDataReader.ConsumeMetaData Hangs In 100% CPU Loop Forever When TdsParser._state == TdsParserState.Broken)
-                    // during request for DTC address.
-                    // NOTE: We doom connection for TdsParserState.Closed since it indicates that it is in some abnormal and unstable state, probably as a result of
-                    // closing from another thread. In general, TdsParserState.Closed does not necessitate dooming the connection.
-                    if (_parser.Connection != null)
-                        _parser.Connection.DoomThisConnection();
-                    throw SQL.ConnectionDoomed();
-                }
-                bool ignored;
-                if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored))
-                {
-                    return false;
-                }
-                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;
-        }
-
-        public override string GetDataTypeName(int i)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                CheckMetaDataIsReady(columnIndex: i);
-
-                return GetDataTypeNameInternal(_metaData[i]);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private string GetDataTypeNameInternal(_SqlMetaData metaData)
-        {
-            string dataTypeName = null;
-
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
-            {
-                dataTypeName = MetaType.MetaNVarChar.TypeName;
-            }
-            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
-            {
-                if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005)
-                {
-                    dataTypeName = MetaType.MetaMaxVarBinary.TypeName;
-                }
-                else
-                {
-                    // TypeSystem.SQLServer2000
-                    dataTypeName = MetaType.MetaImage.TypeName;
-                }
-            }
-            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
-            {
-                // TypeSystem.SQLServer2005 and above
-
-                if (metaData.type == SqlDbType.Udt)
-                {
-                    dataTypeName = metaData.udt?.DatabaseName + "." + metaData.udt?.SchemaName + "." + metaData.udt?.TypeName;
-                }
-                else
-                { // For all other types, including Xml - use data in MetaType.
-                    dataTypeName = metaData.metaType.TypeName;
-                }
-            }
-            else
-            {
-                // TypeSystem.SQLServer2000
-
-                dataTypeName = GetVersionedMetaType(metaData.metaType).TypeName;
-            }
-
-            return dataTypeName;
-        }
-
-        internal virtual SqlBuffer.StorageType GetVariantInternalStorageType(int i)
-        {
-            Debug.Assert(null != _data, "Attempting to get variant internal storage type");
-            Debug.Assert(i < _data.Length, "Reading beyond data length?");
-
-            return _data[i].VariantInternalStorageType;
-        }
-
-        public override IEnumerator GetEnumerator()
-        {
-            return new DbEnumerator(this, IsCommandBehavior(CommandBehavior.CloseConnection));
-        }
-
-        public override Type GetFieldType(int i)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                CheckMetaDataIsReady(columnIndex: i);
-
-                return GetFieldTypeInternal(_metaData[i]);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private Type GetFieldTypeInternal(_SqlMetaData metaData)
-        {
-            Type fieldType = null;
-
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
-            {
-                // Return katmai types as string
-                fieldType = MetaType.MetaNVarChar.ClassType;
-            }
-            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
-            {
-                if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005)
-                {
-                    fieldType = MetaType.MetaMaxVarBinary.ClassType;
-                }
-                else
-                {
-                    // TypeSystem.SQLServer2000
-                    fieldType = MetaType.MetaImage.ClassType;
-                }
-            }
-            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
-            {
-                // TypeSystem.SQLServer2005 and above
-                if (metaData.type == SqlDbType.Udt)
-                {
-                    Connection.CheckGetExtendedUDTInfo(metaData, false);
-                    fieldType = metaData.udt?.Type;
-                }
-                else
-                { // For all other types, including Xml - use data in MetaType.
-                    fieldType = metaData.metaType.ClassType; // Com+ type.
-                }
-            }
-            else
-            {
-                // TypeSystem.SQLServer2000
-                fieldType = GetVersionedMetaType(metaData.metaType).ClassType; // Com+ type.
-            }
-
-            return fieldType;
-        }
-
-        internal virtual int GetLocaleId(int i)
-        {
-            _SqlMetaData sqlMetaData = MetaData[i];
-            int lcid;
-
-            if (sqlMetaData.collation != null)
-            {
-                lcid = sqlMetaData.collation.LCID;
-            }
-            else
-            {
-                lcid = 0;
-            }
-            return lcid;
-        }
-
-        public override string GetName(int i)
-        {
-            CheckMetaDataIsReady(columnIndex: i);
-            return _metaData[i].column;
-        }
-
-        public override Type GetProviderSpecificFieldType(int i)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                CheckMetaDataIsReady(columnIndex: i);
-
-                return GetProviderSpecificFieldTypeInternal(_metaData[i]);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private Type GetProviderSpecificFieldTypeInternal(_SqlMetaData metaData)
-        {
-            Type providerSpecificFieldType = null;
-
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
-            {
-                providerSpecificFieldType = MetaType.MetaNVarChar.SqlType;
-            }
-            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
-            {
-                if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005)
-                {
-                    providerSpecificFieldType = MetaType.MetaMaxVarBinary.SqlType;
-                }
-                else
-                {
-                    // TypeSystem.SQLServer2000
-                    providerSpecificFieldType = MetaType.MetaImage.SqlType;
-                }
-            }
-            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
-            {
-                // TypeSystem.SQLServer2005 and above
-                if (metaData.type == SqlDbType.Udt)
-                {
-                    Connection.CheckGetExtendedUDTInfo(metaData, false);
-                    providerSpecificFieldType = metaData.udt?.Type;
-                }
-                else
-                {
-                    providerSpecificFieldType = metaData.metaType.SqlType; // SqlType type.
-                }
-            }
-            else
-            {
-                // TypeSystem.SQLServer2000
-                providerSpecificFieldType = GetVersionedMetaType(metaData.metaType).SqlType; // SqlType type.
-            }
-
-            return providerSpecificFieldType;
-        }
-
-        // named field access
-        public override int GetOrdinal(string name)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                if (null == _fieldNameLookup)
-                {
-                    CheckMetaDataIsReady();
-                    _fieldNameLookup = new FieldNameLookup(this, _defaultLCID);
-                }
-                return _fieldNameLookup.GetOrdinal(name);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public override object GetProviderSpecificValue(int i)
-        {
-            return GetSqlValue(i);
-        }
-
-        public override int GetProviderSpecificValues(object[] values)
-        {
-            return GetSqlValues(values);
-        }
-
-        public override DataTable GetSchemaTable()
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                if (null == _metaData || null == _metaData.schemaTable)
-                {
-                    if (null != this.MetaData)
-                    {
-                        _metaData.schemaTable = BuildSchemaTable();
-                        Debug.Assert(null != _metaData.schemaTable, "No schema information yet!");
-                    }
-                }
-                return _metaData?.schemaTable;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public override bool GetBoolean(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Boolean;
-        }
-
-        public virtual XmlReader GetXmlReader(int i)
-        {
-            // NOTE: sql_variant can not contain a XML data type: https://docs.microsoft.com/en-us/sql/t-sql/data-types/sql-variant-transact-sql
-            // If this ever changes, the following code should be changed to be like GetStream\GetTextReader
-            CheckDataIsReady(columnIndex: i);
-
-            MetaType mt = _metaData[i].metaType;
-
-            // XmlReader only allowed on XML types
-            if (mt.SqlDbType != SqlDbType.Xml)
-            {
-                throw SQL.XmlReaderNotSupportOnColumnType(_metaData[i].column);
-            }
-
-            if (IsCommandBehavior(CommandBehavior.SequentialAccess))
-            {
-                // Wrap the sequential stream in an XmlReader
-                _currentStream = new SqlSequentialStream(this, i);
-                _lastColumnWithDataChunkRead = i;
-                return SqlTypeWorkarounds.SqlXmlCreateSqlXmlReader(_currentStream, closeInput: true);
-            }
-            else
-            {
-                // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlBinary) rather than calling anther Get*() method
-                ReadColumn(i);
-
-                if (_data[i].IsNull)
-                {
-                    // A 'null' stream
-                    return SqlTypeWorkarounds.SqlXmlCreateSqlXmlReader(new MemoryStream(Array.Empty<byte>(), writable: false), closeInput: true);
-                }
-                else
-                {
-                    // Grab already read data
-                    return _data[i].SqlXml.CreateReader();
-                }
-            }
-        }
-
-        public override Stream GetStream(int i)
-        {
-            CheckDataIsReady(columnIndex: i);
-
-            // Stream is only for Binary, Image, VarBinary, Udt and Xml types
-            // NOTE: IsBinType also includes Timestamp for some reason...
-            MetaType mt = _metaData[i].metaType;
-            if (((!mt.IsBinType) || (mt.SqlDbType == SqlDbType.Timestamp)) && (mt.SqlDbType != SqlDbType.Variant))
-            {
-                throw SQL.StreamNotSupportOnColumnType(_metaData[i].column);
-            }
-
-            // For non-variant types with sequential access, we support proper streaming
-            if ((mt.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess)))
-            {
-                _currentStream = new SqlSequentialStream(this, i);
-                _lastColumnWithDataChunkRead = i;
-                return _currentStream;
-            }
-            else
-            {
-                // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlBinary) rather than calling anther Get*() method
-                ReadColumn(i);
-
-                byte[] data;
-                if (_data[i].IsNull)
-                {
-                    // A 'null' stream
-                    data = Array.Empty<byte>();
-                }
-                else
-                {
-                    // Grab already read data
-                    data = _data[i].SqlBinary.Value;
-                }
-
-                // If non-sequential then we just have a read-only MemoryStream
-                return new MemoryStream(data, writable: false);
-            }
-        }
-
-        public override byte GetByte(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Byte;
-        }
-
-        public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length)
-        {
-            SqlStatistics statistics = null;
-            long cbBytes = 0;
-
-            CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true);
-
-            // don't allow get bytes on non-long or non-binary columns
-            MetaType mt = _metaData[i].metaType;
-            if (!(mt.IsLong || mt.IsBinType) || (SqlDbType.Xml == mt.SqlDbType))
-            {
-                throw SQL.NonBlobColumn(_metaData[i].column);
-            }
-
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                SetTimeout(_defaultTimeoutMilliseconds);
-                cbBytes = GetBytesInternal(i, dataIndex, buffer, bufferIndex, length);
-                _lastColumnWithDataChunkRead = i;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-            return cbBytes;
-        }
-
-        // Used (indirectly) by SqlCommand.CompleteXmlReader
-        internal virtual long GetBytesInternal(int i, long dataIndex, byte[] buffer, int bufferIndex, int length)
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            long value;
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryGetBytesInternal(i, dataIndex, buffer, bufferIndex, length, out value);
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-            return value;
-        }
-
-        private bool TryGetBytesInternal(int i, long dataIndex, byte[] buffer, int bufferIndex, int length, out long remaining)
-        {
-            remaining = 0;
-
-            int cbytes = 0;
-            AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
-
-            // sequential reading
-            if (IsCommandBehavior(CommandBehavior.SequentialAccess))
-            {
-                Debug.Assert(!HasActiveStreamOrTextReaderOnColumn(i), "Column has an active Stream or TextReader");
-
-                if (_sharedState._nextColumnHeaderToRead <= i)
-                {
-                    if (!TryReadColumnHeader(i))
-                    {
-                        return false;
-                    }
-                }
-
-                // If data is null, ReadColumnHeader sets the data.IsNull bit.
-                if (_data[i] != null && _data[i].IsNull)
-                {
-                    throw new SqlNullValueException();
-                }
-
-                // If there are an unknown (-1) number of bytes left for a PLP, read its size
-                if ((-1 == _sharedState._columnDataBytesRemaining) && (_metaData[i].metaType.IsPlp))
-                {
-                    ulong left;
-                    if (!_parser.TryPlpBytesLeft(_stateObj, out left))
-                    {
-                        return false;
-                    }
-                    _sharedState._columnDataBytesRemaining = (long)left;
-                }
-
-                if (0 == _sharedState._columnDataBytesRemaining)
-                {
-                    return true; // We've read this column to the end
-                }
-
-                // if no buffer is passed in, return the number total of bytes, or -1
-                if (null == buffer)
-                {
-                    if (_metaData[i].metaType.IsPlp)
-                    {
-                        remaining = (long)_parser.PlpBytesTotalLength(_stateObj);
-                        return true;
-                    }
-                    remaining = _sharedState._columnDataBytesRemaining;
-                    return true;
-                }
-
-                if (dataIndex < 0)
-                    throw ADP.NegativeParameter(nameof(dataIndex));
-
-                if (dataIndex < _columnDataBytesRead)
-                {
-                    throw ADP.NonSeqByteAccess(dataIndex, _columnDataBytesRead, nameof(GetBytes));
-                }
-
-                // if the dataIndex is not equal to bytes read, then we have to skip bytes
-                long cb = dataIndex - _columnDataBytesRead;
-
-                // if dataIndex is outside of the data range, return 0
-                if ((cb > _sharedState._columnDataBytesRemaining) && !_metaData[i].metaType.IsPlp)
-                {
-                    return true;
-                }
-
-                // if bad buffer index, throw
-                if (bufferIndex < 0 || bufferIndex >= buffer.Length)
-                    throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, nameof(bufferIndex));
-
-                // if there is not enough room in the buffer for data
-                if (length + bufferIndex > buffer.Length)
-                    throw ADP.InvalidBufferSizeOrIndex(length, bufferIndex);
-
-                if (length < 0)
-                    throw ADP.InvalidDataLength(length);
-
-                // Skip if needed
-                if (cb > 0)
-                {
-                    if (_metaData[i].metaType.IsPlp)
-                    {
-                        ulong skipped;
-                        if (!_parser.TrySkipPlpValue((ulong)cb, _stateObj, out skipped))
-                        {
-                            return false;
-                        }
-                        _columnDataBytesRead += (long)skipped;
-                    }
-                    else
-                    {
-                        if (!_stateObj.TrySkipLongBytes(cb))
-                        {
-                            return false;
-                        }
-                        _columnDataBytesRead += cb;
-                        _sharedState._columnDataBytesRemaining -= cb;
-                    }
-                }
-
-                int bytesRead;
-                bool result = TryGetBytesInternalSequential(i, buffer, bufferIndex, length, out bytesRead);
-                remaining = (int)bytesRead;
-                return result;
-            }
-
-            // random access now!
-            // note that since we are caching in an array, and arrays aren't 64 bit ready yet,
-            // we need can cast to int if the dataIndex is in range
-            if (dataIndex < 0)
-                throw ADP.NegativeParameter(nameof(dataIndex));
-
-            if (dataIndex > int.MaxValue)
-            {
-                throw ADP.InvalidSourceBufferIndex(cbytes, dataIndex, nameof(dataIndex));
-            }
-
-            int ndataIndex = (int)dataIndex;
-            byte[] data;
-
-            // WebData 99342 - in the non-sequential case, we need to support
-            //                 the use of GetBytes on string data columns, but
-            //                 GetSqlBinary isn't supposed to.  What we end up
-            //                 doing isn't exactly pretty, but it does work.
-            if (_metaData[i].metaType.IsBinType)
-            {
-                data = GetSqlBinary(i).Value;
-            }
-            else
-            {
-                Debug.Assert(_metaData[i].metaType.IsLong, "non long type?");
-                Debug.Assert(_metaData[i].metaType.IsCharType, "non-char type?");
-
-                SqlString temp = GetSqlString(i);
-                if (_metaData[i].metaType.IsNCharType)
-                {
-                    data = temp.GetUnicodeBytes();
-                }
-                else
-                {
-                    data = temp.GetNonUnicodeBytes();
-                }
-            }
-
-            cbytes = data.Length;
-
-            // if no buffer is passed in, return the number of characters we have
-            if (null == buffer)
-            {
-                remaining = cbytes;
-                return true;
-            }
-
-            // if dataIndex is outside of data range, return 0
-            if (ndataIndex < 0 || ndataIndex >= cbytes)
-            {
-                return true;
-            }
-            try
-            {
-                if (ndataIndex < cbytes)
-                {
-                    // help the user out in the case where there's less data than requested
-                    if ((ndataIndex + length) > cbytes)
-                        cbytes = cbytes - ndataIndex;
-                    else
-                        cbytes = length;
-                }
-
-                Buffer.BlockCopy(data, ndataIndex, buffer, bufferIndex, cbytes);
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-                cbytes = data.Length;
-
-                if (length < 0)
-                    throw ADP.InvalidDataLength(length);
-
-                // if bad buffer index, throw
-                if (bufferIndex < 0 || bufferIndex >= buffer.Length)
-                    throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, nameof(bufferIndex));
-
-                // if there is not enough room in the buffer for data
-                if (cbytes + bufferIndex > buffer.Length)
-                    throw ADP.InvalidBufferSizeOrIndex(cbytes, bufferIndex);
-
-                throw;
-            }
-
-            remaining = cbytes;
-            return true;
-        }
-
-        internal int GetBytesInternalSequential(int i, byte[] buffer, int index, int length, long? timeoutMilliseconds = null)
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            int value;
-            SqlStatistics statistics = null;
-            Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                SetTimeout(timeoutMilliseconds ?? _defaultTimeoutMilliseconds);
-
-                bool result = TryReadColumnHeader(i);
-                if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-
-                result = TryGetBytesInternalSequential(i, buffer, index, length, out value);
-                if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-
-            return value;
-        }
-
-        // This is meant to be called from other internal methods once we are at the column to read
-        // NOTE: This method must be retriable WITHOUT replaying a snapshot
-        // Every time you call this method increment the index and decrease length by the value of bytesRead
-        internal bool TryGetBytesInternalSequential(int i, byte[] buffer, int index, int length, out int bytesRead)
-        {
-            AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
-            Debug.Assert(_sharedState._nextColumnHeaderToRead == i + 1 && _sharedState._nextColumnDataToRead == i, "Non sequential access");
-            Debug.Assert(buffer != null, "Null buffer");
-            Debug.Assert(index >= 0, "Invalid index");
-            Debug.Assert(length >= 0, "Invalid length");
-            Debug.Assert(index + length <= buffer.Length, "Buffer too small");
-
-            bytesRead = 0;
-
-            if ((_sharedState._columnDataBytesRemaining == 0) || (length == 0))
-            {
-                // No data left or nothing requested, return 0
-                bytesRead = 0;
-                return true;
-            }
-            else
-            {
-                // if plp columns, do partial reads. Don't read the entire value in one shot.
-                if (_metaData[i].metaType.IsPlp)
-                {
-                    // Read in data
-                    bool result = _stateObj.TryReadPlpBytes(ref buffer, index, length, out bytesRead);
-                    _columnDataBytesRead += bytesRead;
-                    if (!result)
-                    {
-                        return false;
-                    }
-
-                    // Query for number of bytes left
-                    ulong left;
-                    if (!_parser.TryPlpBytesLeft(_stateObj, out left))
-                    {
-                        _sharedState._columnDataBytesRemaining = -1;
-                        return false;
-                    }
-                    _sharedState._columnDataBytesRemaining = (long)left;
-                    return true;
-                }
-                else
-                {
-                    // Read data (not exceeding the total amount of data available)
-                    int bytesToRead = (int)Math.Min((long)length, _sharedState._columnDataBytesRemaining);
-                    bool result = _stateObj.TryReadByteArray(buffer.AsSpan(index), bytesToRead, out bytesRead);
-                    _columnDataBytesRead += bytesRead;
-                    _sharedState._columnDataBytesRemaining -= bytesRead;
-                    return result;
-                }
-            }
-        }
-
-        public override TextReader GetTextReader(int i)
-        {
-            CheckDataIsReady(columnIndex: i);
-
-            // Xml type is not supported
-            MetaType mt = _metaData[i].metaType;
-            if (((!mt.IsCharType) && (mt.SqlDbType != SqlDbType.Variant)) || (mt.SqlDbType == SqlDbType.Xml))
-            {
-                throw SQL.TextReaderNotSupportOnColumnType(_metaData[i].column);
-            }
-
-            // For non-variant types with sequential access, we support proper streaming
-            if ((mt.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess)))
-            {
-                System.Text.Encoding encoding;
-                if (mt.IsNCharType)
-                {
-                    // NChar types always use unicode
-                    encoding = SqlUnicodeEncoding.SqlUnicodeEncodingInstance;
-                }
-                else
-                {
-                    encoding = _metaData[i].encoding;
-                }
-
-                _currentTextReader = new SqlSequentialTextReader(this, i, encoding);
-                _lastColumnWithDataChunkRead = i;
-                return _currentTextReader;
-            }
-            else
-            {
-                // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlString) rather than calling anther Get*() method
-                ReadColumn(i);
-
-                string data;
-                if (_data[i].IsNull)
-                {
-                    // A 'null' stream
-                    data = string.Empty;
-                }
-                else
-                {
-                    // Grab already read data
-                    data = _data[i].SqlString.Value;
-                }
-
-                // We've already read the data, so just wrap it in a StringReader
-                return new StringReader(data);
-            }
-        }
-
-        public override char GetChar(int i)
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length)
-        {
-            SqlStatistics statistics = null;
-
-            CheckMetaDataIsReady(columnIndex: i);
-
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                SetTimeout(_defaultTimeoutMilliseconds);
-                if ((_metaData[i].metaType.IsPlp) &&
-                    (IsCommandBehavior(CommandBehavior.SequentialAccess)))
-                {
-                    if (length < 0)
-                    {
-                        throw ADP.InvalidDataLength(length);
-                    }
-
-                    // if bad buffer index, throw
-                    if ((bufferIndex < 0) || (buffer != null && bufferIndex >= buffer.Length))
-                    {
-                        throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, nameof(bufferIndex));
-                    }
-
-                    // if there is not enough room in the buffer for data
-                    if (buffer != null && (length + bufferIndex > buffer.Length))
-                    {
-                        throw ADP.InvalidBufferSizeOrIndex(length, bufferIndex);
-                    }
-                    long charsRead = 0;
-                    if (_metaData[i].type == SqlDbType.Xml)
-                    {
-                        try
-                        {
-                            CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true);
-                        }
-                        catch (Exception ex)
-                        {
-                            // We need to wrap all exceptions inside a TargetInvocationException to simulate calling CreateSqlReader via MethodInfo.Invoke
-                            if (ADP.IsCatchableExceptionType(ex))
-                            {
-                                throw new TargetInvocationException(ex);
-                            }
-                            else
-                            {
-                                throw;
-                            }
-                        }
-                        charsRead = GetStreamingXmlChars(i, dataIndex, buffer, bufferIndex, length);
-                    }
-                    else
-                    {
-                        CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true);
-                        charsRead = GetCharsFromPlpData(i, dataIndex, buffer, bufferIndex, length);
-                    }
-                    _lastColumnWithDataChunkRead = i;
-                    return charsRead;
-                }
-
-                // Did we start reading this value yet?
-                if ((_sharedState._nextColumnDataToRead == (i + 1)) && (_sharedState._nextColumnHeaderToRead == (i + 1)) && (_columnDataChars != null) && (IsCommandBehavior(CommandBehavior.SequentialAccess)) && (dataIndex < _columnDataCharsRead))
-                {
-                    // Don't allow re-read of same chars in sequential access mode
-                    throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, nameof(GetChars));
-                }
-
-                if (_columnDataCharsIndex != i)
-                {
-                    // if the object doesn't contain a char[] then the user will get an exception
-                    string s = GetSqlString(i).Value;
-
-                    _columnDataChars = s.ToCharArray();
-                    _columnDataCharsRead = 0;
-                    _columnDataCharsIndex = i;
-                }
-
-                int cchars = _columnDataChars.Length;
-
-                // note that since we are caching in an array, and arrays aren't 64 bit ready yet,
-                // we need can cast to int if the dataIndex is in range
-                if (dataIndex > int.MaxValue)
-                {
-                    throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, nameof(dataIndex));
-                }
-                int ndataIndex = (int)dataIndex;
-
-                // if no buffer is passed in, return the number of characters we have
-                if (null == buffer)
-                    return cchars;
-
-                // if dataIndex outside of data range, return 0
-                if (ndataIndex < 0 || ndataIndex >= cchars)
-                    return 0;
-
-                try
-                {
-                    if (ndataIndex < cchars)
-                    {
-                        // help the user out in the case where there's less data than requested
-                        if ((ndataIndex + length) > cchars)
-                            cchars = cchars - ndataIndex;
-                        else
-                            cchars = length;
-                    }
-
-                    Array.Copy(_columnDataChars, ndataIndex, buffer, bufferIndex, cchars);
-                    _columnDataCharsRead += cchars;
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableExceptionType(e))
-                    {
-                        throw;
-                    }
-                    cchars = _columnDataChars.Length;
-
-                    if (length < 0)
-                        throw ADP.InvalidDataLength(length);
-
-                    // if bad buffer index, throw
-                    if (bufferIndex < 0 || bufferIndex >= buffer.Length)
-                        throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, nameof(bufferIndex));
-
-                    // if there is not enough room in the buffer for data
-                    if (cchars + bufferIndex > buffer.Length)
-                        throw ADP.InvalidBufferSizeOrIndex(cchars, bufferIndex);
-
-                    throw;
-                }
-
-                return cchars;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int bufferIndex, int length)
-        {
-            long cch;
-
-            AssertReaderState(requireData: true, permitAsync: false, columnIndex: i, enforceSequentialAccess: true);
-            Debug.Assert(!HasActiveStreamOrTextReaderOnColumn(i), "Column has active Stream or TextReader");
-            // don't allow get bytes on non-long or non-binary columns
-            Debug.Assert(_metaData[i].metaType.IsPlp, "GetCharsFromPlpData called on a non-plp column!");
-            // Must be sequential reading
-            Debug.Assert(IsCommandBehavior(CommandBehavior.SequentialAccess), "GetCharsFromPlpData called for non-Sequential access");
-
-            if (!_metaData[i].metaType.IsCharType)
-            {
-                throw SQL.NonCharColumn(_metaData[i].column);
-            }
-
-            if (_sharedState._nextColumnHeaderToRead <= i)
-            {
-                ReadColumnHeader(i);
-            }
-
-            // If data is null, ReadColumnHeader sets the data.IsNull bit.
-            if (_data[i] != null && _data[i].IsNull)
-            {
-                throw new SqlNullValueException();
-            }
-
-            if (dataIndex < _columnDataCharsRead)
-            {
-                // Don't allow re-read of same chars in sequential access mode
-                throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, nameof(GetChars));
-            }
-
-            // If we start reading the new column, either dataIndex is 0 or
-            // _columnDataCharsRead is 0 and dataIndex > _columnDataCharsRead is true below.
-            // In both cases we will clean decoder
-            if (dataIndex == 0)
-                _stateObj._plpdecoder = null;
-
-            bool isUnicode = _metaData[i].metaType.IsNCharType;
-
-            // If there are an unknown (-1) number of bytes left for a PLP, read its size
-            if (-1 == _sharedState._columnDataBytesRemaining)
-            {
-                _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
-            }
-
-            if (0 == _sharedState._columnDataBytesRemaining)
-            {
-                _stateObj._plpdecoder = null;
-                return 0; // We've read this column to the end
-            }
-
-            // if no buffer is passed in, return the total number of characters or -1
-            if (null == buffer)
-            {
-                cch = (long)_parser.PlpBytesTotalLength(_stateObj);
-                return (isUnicode && (cch > 0)) ? cch >> 1 : cch;
-            }
-            if (dataIndex > _columnDataCharsRead)
-            {
-                // Skip chars
-
-                // Clean decoder state: we do not reset it, but destroy to ensure
-                // that we do not start decoding the column with decoder from the old one
-                _stateObj._plpdecoder = null;
-                cch = dataIndex - _columnDataCharsRead;
-                cch = isUnicode ? (cch << 1) : cch;
-                cch = (long)_parser.SkipPlpValue((ulong)(cch), _stateObj);
-                _columnDataBytesRead += cch;
-                _columnDataCharsRead += (isUnicode && (cch > 0)) ? cch >> 1 : cch;
-            }
-            cch = length;
-
-            if (isUnicode)
-            {
-                cch = (long)_parser.ReadPlpUnicodeChars(ref buffer, bufferIndex, length, _stateObj);
-                _columnDataBytesRead += (cch << 1);
-            }
-            else
-            {
-                cch = (long)_parser.ReadPlpAnsiChars(ref buffer, bufferIndex, length, _metaData[i], _stateObj);
-                _columnDataBytesRead += cch << 1;
-            }
-            _columnDataCharsRead += cch;
-            _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
-            return cch;
-        }
-
-        internal long GetStreamingXmlChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length)
-        {
-            SqlStreamingXml localSXml = null;
-            if ((_streamingXml != null) && (_streamingXml.ColumnOrdinal != i))
-            {
-                _streamingXml.Close();
-                _streamingXml = null;
-            }
-            if (_streamingXml == null)
-            {
-                localSXml = new SqlStreamingXml(i, this);
-            }
-            else
-            {
-                localSXml = _streamingXml;
-            }
-            long cnt = localSXml.GetChars(dataIndex, buffer, bufferIndex, length);
-            if (_streamingXml == null)
-            {
-                // Data is read through GetBytesInternal which may dispose _streamingXml if it has to advance the column ordinal.
-                // Therefore save the new SqlStreamingXml class after the read succeeds.
-                _streamingXml = localSXml;
-            }
-            return cnt;
-        }
-
-
-        public override DateTime GetDateTime(int i)
-        {
-            ReadColumn(i);
-
-            DateTime dt = _data[i].DateTime;
-            // This accessor can be called for regular DateTime column. In this case we should not throw
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
-            {
-                // TypeSystem.SQLServer2005 or less
-
-                // If the above succeeds, then we received a valid DateTime instance, now we need to force
-                // an InvalidCastException since DateTime is not exposed with the version knob in this setting.
-                // To do so, we simply force the exception by casting the string representation of the value
-                // To DateTime.
-                object temp = (object)_data[i].String;
-                dt = (DateTime)temp;
-            }
-
-            return dt;
-        }
-
-        public override decimal GetDecimal(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Decimal;
-        }
-
-        public override double GetDouble(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Double;
-        }
-
-        public override float GetFloat(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Single;
-        }
-
-        public override Guid GetGuid(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Guid;
-        }
-
-        public override short GetInt16(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Int16;
-        }
-
-        public override int GetInt32(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Int32;
-        }
-
-        public override long GetInt64(int i)
-        {
-            ReadColumn(i);
-            return _data[i].Int64;
-        }
-
-        public virtual SqlBoolean GetSqlBoolean(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlBoolean;
-        }
-
-        public virtual SqlBinary GetSqlBinary(int i)
-        {
-            ReadColumn(i, setTimeout: true, allowPartiallyReadColumn: true);
-            return _data[i].SqlBinary;
-        }
-
-        public virtual SqlByte GetSqlByte(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlByte;
-        }
-
-        public virtual SqlBytes GetSqlBytes(int i)
-        {
-            ReadColumn(i);
-            SqlBinary data = _data[i].SqlBinary;
-            return new SqlBytes(data);
-        }
-
-        public virtual SqlChars GetSqlChars(int i)
-        {
-            ReadColumn(i);
-            SqlString data;
-            // Convert Katmai types to string
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
-            {
-                data = _data[i].KatmaiDateTimeSqlString;
-            }
-            else
-            {
-                data = _data[i].SqlString;
-            }
-            return new SqlChars(data);
-        }
-
-        public virtual SqlDateTime GetSqlDateTime(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlDateTime;
-        }
-
-        public virtual SqlDecimal GetSqlDecimal(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlDecimal;
-        }
-
-        public virtual SqlGuid GetSqlGuid(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlGuid;
-        }
-
-        public virtual SqlDouble GetSqlDouble(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlDouble;
-        }
-
-        public virtual SqlInt16 GetSqlInt16(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlInt16;
-        }
-
-        public virtual SqlInt32 GetSqlInt32(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlInt32;
-        }
-
-        public virtual SqlInt64 GetSqlInt64(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlInt64;
-        }
-
-        public virtual SqlMoney GetSqlMoney(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlMoney;
-        }
-
-        public virtual SqlSingle GetSqlSingle(int i)
-        {
-            ReadColumn(i);
-            return _data[i].SqlSingle;
-        }
-
-        public virtual SqlString GetSqlString(int i)
-        {
-            ReadColumn(i);
-
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
-            {
-                return _data[i].KatmaiDateTimeSqlString;
-            }
-
-            return _data[i].SqlString;
-        }
-
-        public virtual SqlXml GetSqlXml(int i)
-        {
-            ReadColumn(i);
-            SqlXml sx = null;
-
-            if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
-            {
-                // TypeSystem.SQLServer2005
-
-                sx = _data[i].IsNull ? SqlXml.Null : _data[i].SqlCachedBuffer.ToSqlXml();
-            }
-            else
-            {
-                // TypeSystem.SQLServer2000
-
-                // First, attempt to obtain SqlXml value.  If not SqlXml, we will throw the appropriate
-                // cast exception.
-                sx = _data[i].IsNull ? SqlXml.Null : _data[i].SqlCachedBuffer.ToSqlXml();
-
-                // If the above succeeds, then we received a valid SqlXml instance, now we need to force
-                // an InvalidCastException since SqlXml is not exposed with the version knob in this setting.
-                // To do so, we simply force the exception by casting the string representation of the value
-                // To SqlXml.
-                object temp = (object)_data[i].String;
-                sx = (SqlXml)temp;
-            }
-
-            return sx;
-        }
-
-        public virtual object GetSqlValue(int i)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                SetTimeout(_defaultTimeoutMilliseconds);
-                return GetSqlValueInternal(i);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private object GetSqlValueInternal(int i)
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryReadColumn(i, setTimeout: false);
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-
-            return GetSqlValueFromSqlBufferInternal(_data[i], _metaData[i]);
-        }
-
-        // NOTE: This method is called by the fast-paths in Async methods and, therefore, should be resilient to the DataReader being closed
-        //       Always make sure to take reference copies of anything set to null in TryCloseInternal()
-        private object GetSqlValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData)
-        {
-            Debug.Assert(!data.IsEmpty || data.IsNull || metaData.type == SqlDbType.Timestamp, "Data has been read, but the buffer is empty");
-
-            // Convert Katmai types to string
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
-            {
-                return data.KatmaiDateTimeSqlString;
-            }
-            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
-            {
-                return data.SqlValue;
-            }
-            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
-            {
-                // TypeSystem.SQLServer2005 and above
-
-                if (metaData.type == SqlDbType.Udt)
-                {
-                    SqlConnection connection = _connection;
-                    if (connection != null)
-                    {
-                        connection.CheckGetExtendedUDTInfo(metaData, true);
-                        return connection.GetUdtValue(data.Value, metaData, false);
-                    }
-                    else
-                    {
-                        throw ADP.DataReaderClosed(nameof(GetSqlValueFromSqlBufferInternal));
-                    }
-                }
-                else
-                {
-                    return data.SqlValue;
-                }
-            }
-            else
-            {
-                // TypeSystem.SQLServer2000
-
-                if (metaData.type == SqlDbType.Xml)
-                {
-                    return data.SqlString;
-                }
-                else
-                {
-                    return data.SqlValue;
-                }
-            }
-        }
-
-        public virtual int GetSqlValues(object[] values)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                CheckDataIsReady();
-                if (null == values)
-                {
-                    throw ADP.ArgumentNull(nameof(values));
-                }
-
-                SetTimeout(_defaultTimeoutMilliseconds);
-
-                int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns;
-
-                for (int i = 0; i < copyLen; i++)
-                {
-                    values[_metaData.indexMap[i]] = GetSqlValueInternal(i);
-                }
-                return copyLen;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public override string GetString(int i)
-        {
-            ReadColumn(i);
-
-            // Convert katmai value to string if type system knob is 2005 or earlier
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
-            {
-                return _data[i].KatmaiDateTimeString;
-            }
-
-            return _data[i].String;
-        }
-
-        public override T GetFieldValue<T>(int i)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                SetTimeout(_defaultTimeoutMilliseconds);
-                return GetFieldValueInternal<T>(i);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public override object GetValue(int i)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                SetTimeout(_defaultTimeoutMilliseconds);
-                return GetValueInternal(i);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public virtual TimeSpan GetTimeSpan(int i)
-        {
-            ReadColumn(i);
-
-            TimeSpan t = _data[i].Time;
-
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005)
-            {
-                // TypeSystem.SQLServer2005 or less
-
-                // If the above succeeds, then we received a valid TimeSpan instance, now we need to force
-                // an InvalidCastException since TimeSpan is not exposed with the version knob in this setting.
-                // To do so, we simply force the exception by casting the string representation of the value
-                // To TimeSpan.
-                object temp = (object)_data[i].String;
-                t = (TimeSpan)temp;
-            }
-
-            return t;
-        }
-
-        public virtual DateTimeOffset GetDateTimeOffset(int i)
-        {
-            ReadColumn(i);
-
-            DateTimeOffset dto = _data[i].DateTimeOffset;
-
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005)
-            {
-                // TypeSystem.SQLServer2005 or less
-
-                // If the above succeeds, then we received a valid DateTimeOffset instance, now we need to force
-                // an InvalidCastException since DateTime is not exposed with the version knob in this setting.
-                // To do so, we simply force the exception by casting the string representation of the value
-                // To DateTimeOffset.
-                object temp = (object)_data[i].String;
-                dto = (DateTimeOffset)temp;
-            }
-
-            return dto;
-        }
-
-        private object GetValueInternal(int i)
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryReadColumn(i, setTimeout: false);
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-
-            return GetValueFromSqlBufferInternal(_data[i], _metaData[i]);
-        }
-
-        // NOTE: This method is called by the fast-paths in Async methods and, therefore, should be resilient to the DataReader being closed
-        //       Always make sure to take reference copies of anything set to null in TryCloseInternal()
-        private object GetValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData)
-        {
-            Debug.Assert(!data.IsEmpty || data.IsNull || metaData.type == SqlDbType.Timestamp, "Data has been read, but the buffer is empty");
-
-            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
-            {
-                if (data.IsNull)
-                {
-                    return DBNull.Value;
-                }
-                else
-                {
-                    return data.KatmaiDateTimeString;
-                }
-            }
-            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
-            {
-                return data.Value;
-            }
-            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
-            {
-                // TypeSystem.SQLServer2005 and above
-
-                if (metaData.type != SqlDbType.Udt)
-                {
-                    return data.Value;
-                }
-                else
-                {
-                    SqlConnection connection = _connection;
-                    if (connection != null)
-                    {
-                        connection.CheckGetExtendedUDTInfo(metaData, true);
-                        return connection.GetUdtValue(data.Value, metaData, true);
-                    }
-                    else
-                    {
-                        throw ADP.DataReaderClosed(nameof(GetValueFromSqlBufferInternal));
-                    }
-                }
-            }
-            else
-            {
-                // TypeSystem.SQLServer2000
-                return data.Value;
-            }
-        }
-
-        private T GetFieldValueInternal<T>(int i)
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryReadColumn(i, setTimeout: false);
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-
-            return GetFieldValueFromSqlBufferInternal<T>(_data[i], _metaData[i]);
-        }
-
-        private T GetFieldValueFromSqlBufferInternal<T>(SqlBuffer data, _SqlMetaData metaData)
-        {
-            // this block of type specific shortcuts uses RyuJIT jit behaviours to achieve fast implementations of the primitive types
-            // RyuJIT will be able to determine at compilation time that the typeof(T)==typeof(<primitive>) options are constant
-            // and be able to remove all implementations which cannot be reached. this will eliminate non-specialized code for value types
-            Type dataType = data.GetTypeFromStorageType(false);
-            if (typeof(T) == typeof(int) && dataType == typeof(int))
-            {
-                return data.Int32As<T>();
-            }
-            else if (typeof(T) == typeof(byte) && dataType == typeof(byte))
-            {
-                return data.ByteAs<T>();
-            }
-            else if (typeof(T) == typeof(short) && dataType == typeof(short))
-            {
-                return data.Int16As<T>();
-            }
-            else if (typeof(T) == typeof(long) && dataType == typeof(long))
-            {
-                return data.Int64As<T>();
-            }
-            else if (typeof(T) == typeof(bool) && dataType == typeof(bool))
-            {
-                return data.BooleanAs<T>();
-            }
-            else if (typeof(T) == typeof(double) && dataType == typeof(double))
-            {
-                return data.DoubleAs<T>();
-            }
-            else if (typeof(T) == typeof(float) && dataType == typeof(float))
-            {
-                return data.SingleAs<T>();
-            }
-            else if (typeof(T) == typeof(Guid) && dataType == typeof(Guid))
-            {
-                return (T)(object)data.Guid;
-            }
-            else if (typeof(T) == typeof(decimal) && dataType == typeof(decimal))
-            {
-                return (T)(object)data.Decimal;
-            }
-            else if (typeof(T) == typeof(DateTimeOffset) && dataType == typeof(DateTimeOffset) && _typeSystem > SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
-            {
-                return (T)(object)data.DateTimeOffset;
-            }
-            else if (typeof(T) == typeof(DateTime) && dataType == typeof(DateTime) && _typeSystem > SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
-            {
-                return (T)(object)data.DateTime;
-            }
-            else
-            {
-                Type typeofT = typeof(T);
-                if (_typeofINullable.IsAssignableFrom(typeofT))
-                {
-                    // If its a SQL Type or Nullable UDT
-                    object rawValue = GetSqlValueFromSqlBufferInternal(data, metaData);
-
-                    if (typeofT == s_typeofSqlString)
-                    {
-                        // Special case: User wants SqlString, but we have a SqlXml
-                        // SqlXml can not be typecast into a SqlString, but we need to support SqlString on XML Types - so do a manual conversion
-                        SqlXml xmlValue = rawValue as SqlXml;
-                        if (xmlValue != null)
-                        {
-                            if (xmlValue.IsNull)
-                            {
-                                rawValue = SqlString.Null;
-                            }
-                            else
-                            {
-                                rawValue = new SqlString(xmlValue.Value);
-                            }
-                        }
-                    }
-
-                    return (T)rawValue;
-                }
-                else
-                {
-                    if (typeof(XmlReader) == typeofT)
-                    {
-                        if (metaData.metaType.SqlDbType != SqlDbType.Xml)
-                        {
-                            throw SQL.XmlReaderNotSupportOnColumnType(metaData.column);
-                        }
-                        else
-                        {
-                            object clrValue = null;
-                            if (!data.IsNull)
-                            {
-                                clrValue = GetValueFromSqlBufferInternal(data, metaData);
-                            }
-                            if (clrValue is null) // covers IsNull and when there is data which is present but is a clr null somehow
-                            {
-                                return (T)(object)SqlTypeWorkarounds.SqlXmlCreateSqlXmlReader(
-                                    new MemoryStream(Array.Empty<byte>(), writable: false),
-                                    closeInput: true
-                                );
-                            }
-                            else if (clrValue.GetType() == typeof(string))
-                            {
-                                return (T)(object)SqlTypeWorkarounds.SqlXmlCreateSqlXmlReader(
-                                    new StringReader(clrValue as string),
-                                    closeInput: true
-                                );
-                            }
-                            else
-                            {
-                                // try the type cast to throw the invalid cast exception and inform the user what types they're trying to use and that why it is wrong
-                                return (T)clrValue;
-                            }
-                        }
-                    }
-                    else
-                    {
-                        try
-                        {
-                            return (T)GetValueFromSqlBufferInternal(data, metaData);
-                        }
-                        catch (InvalidCastException)
-                        {
-                            if (data.IsNull)
-                            {
-                                // If the value was actually null, then we should throw a SqlNullValue instead
-                                throw SQL.SqlNullValue();
-                            }
-                            else
-                            {
-                                // Legitimate InvalidCast, rethrow
-                                throw;
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        public override int GetValues(object[] values)
-        {
-            SqlStatistics statistics = null;
-            bool sequentialAccess = IsCommandBehavior(CommandBehavior.SequentialAccess);
-
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                if (null == values)
-                {
-                    throw ADP.ArgumentNull(nameof(values));
-                }
-
-                CheckMetaDataIsReady();
-
-                int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns;
-                int maximumColumn = copyLen - 1;
-
-                SetTimeout(_defaultTimeoutMilliseconds);
-
-                // Temporarily disable sequential access
-                _commandBehavior &= ~CommandBehavior.SequentialAccess;
-
-                // Read in all of the columns in one TryReadColumn call
-                bool result = TryReadColumn(maximumColumn, setTimeout: false);
-                if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-
-                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]);
-
-                    // If this is sequential access, then we need to wipe the internal buffer
-                    if ((sequentialAccess) && (i < maximumColumn))
-                    {
-                        _data[i].Clear();
-                    }
-                }
-
-                return copyLen;
-            }
-            finally
-            {
-                // Restore sequential access
-                if (sequentialAccess)
-                {
-                    _commandBehavior |= CommandBehavior.SequentialAccess;
-                }
-
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private MetaType GetVersionedMetaType(MetaType actualMetaType)
-        {
-            Debug.Assert(_typeSystem == SqlConnectionString.TypeSystem.SQLServer2000, "Should not be in this function under anything else but SQLServer2000");
-
-            MetaType metaType = null;
-
-            if (actualMetaType == MetaType.MetaUdt)
-            {
-                metaType = MetaType.MetaVarBinary;
-            }
-            else if (actualMetaType == MetaType.MetaXml)
-            {
-                metaType = MetaType.MetaNText;
-            }
-            else if (actualMetaType == MetaType.MetaMaxVarBinary)
-            {
-                metaType = MetaType.MetaImage;
-            }
-            else if (actualMetaType == MetaType.MetaMaxVarChar)
-            {
-                metaType = MetaType.MetaText;
-            }
-            else if (actualMetaType == MetaType.MetaMaxNVarChar)
-            {
-                metaType = MetaType.MetaNText;
-            }
-            else
-            {
-                metaType = actualMetaType;
-            }
-
-            return metaType;
-        }
-
-        private bool TryHasMoreResults(out bool moreResults)
-        {
-            if (null != _parser)
-            {
-                bool moreRows;
-                if (!TryHasMoreRows(out moreRows))
-                {
-                    moreResults = false;
-                    return false;
-                }
-                if (moreRows)
-                {
-                    // When does this happen?  This is only called from NextResult(), which loops until Read() false.
-                    moreResults = false;
-                    return true;
-                }
-
-                Debug.Assert(null != _command, "unexpected null command from the data reader!");
-
-                while (_stateObj._pendingData)
-                {
-                    byte token;
-                    if (!_stateObj.TryPeekByte(out token))
-                    {
-                        moreResults = false;
-                        return false;
-                    }
-
-                    switch (token)
-                    {
-                        case TdsEnums.SQLALTROW:
-                            if (_altRowStatus == ALTROWSTATUS.Null)
-                            {
-                                // cache the regular metadata
-                                _altMetaDataSetCollection.metaDataSet = _metaData;
-                                _metaData = null;
-                            }
-                            else
-                            {
-                                Debug.Assert(_altRowStatus == ALTROWSTATUS.Done, "invalid AltRowStatus");
-                            }
-                            _altRowStatus = ALTROWSTATUS.AltRow;
-                            _hasRows = true;
-                            moreResults = true;
-                            return true;
-                        case TdsEnums.SQLROW:
-                        case TdsEnums.SQLNBCROW:
-                            // always happens if there is a row following an altrow
-                            moreResults = true;
-                            return true;
-                        case TdsEnums.SQLDONE:
-                            Debug.Assert(_altRowStatus == ALTROWSTATUS.Done || _altRowStatus == ALTROWSTATUS.Null, "invalid AltRowStatus");
-                            _altRowStatus = ALTROWSTATUS.Null;
-                            _metaData = null;
-                            _altMetaDataSetCollection = null;
-                            moreResults = true;
-                            return true;
-                        case TdsEnums.SQLCOLMETADATA:
-                            moreResults = true;
-                            return true;
-                    }
-
-                    // TryRun() will immediately return if the TdsParser is closed\broken, causing us to enter an infinite loop
-                    // Instead, we will throw a closed connection exception
-                    if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
-                    {
-                        throw ADP.ClosedConnectionError();
-                    }
-
-                    bool ignored;
-                    if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored))
-                    {
-                        moreResults = false;
-                        return false;
-                    }
-                }
-            }
-            moreResults = false;
-            return true;
-        }
-
-        private bool TryHasMoreRows(out bool moreRows)
-        {
-            if (null != _parser)
-            {
-                if (_sharedState._dataReady)
-                {
-                    moreRows = true;
-                    return true;
-                }
-
-                // NextResult: previous call to NextResult started to process the altrowpackage, can't peek anymore
-                // Read: Read prepared for final processing of altrow package, No more Rows until NextResult ...
-                // Done: Done processing the altrow, no more rows until NextResult ...
-                switch (_altRowStatus)
-                {
-                    case ALTROWSTATUS.AltRow:
-                        moreRows = true;
-                        return true;
-                    case ALTROWSTATUS.Done:
-                        moreRows = false;
-                        return true;
-                }
-                if (_stateObj._pendingData)
-                {
-                    // Consume error's, info's, done's on HasMoreRows, so user obtains error on Read.
-                    byte b;
-                    if (!_stateObj.TryPeekByte(out b))
-                    {
-                        moreRows = false;
-                        return false;
-                    }
-                    bool ParsedDoneToken = false;
-
-                    while (b == TdsEnums.SQLDONE ||
-                            b == TdsEnums.SQLDONEPROC ||
-                            b == TdsEnums.SQLDONEINPROC ||
-                            !ParsedDoneToken && (
-                                b == TdsEnums.SQLSESSIONSTATE ||
-                                b == TdsEnums.SQLENVCHANGE ||
-                                b == TdsEnums.SQLORDER ||
-                                b == TdsEnums.SQLERROR ||
-                                b == TdsEnums.SQLINFO))
-                    {
-                        if (b == TdsEnums.SQLDONE ||
-                            b == TdsEnums.SQLDONEPROC ||
-                            b == TdsEnums.SQLDONEINPROC)
-                        {
-                            ParsedDoneToken = true;
-                        }
-
-                        // TryRun() will immediately return if the TdsParser is closed\broken, causing us to enter an infinite loop
-                        // Instead, we will throw a closed connection exception
-                        if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
-                        {
-                            throw ADP.ClosedConnectionError();
-                        }
-
-                        bool ignored;
-                        if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored))
-                        {
-                            moreRows = false;
-                            return false;
-                        }
-                        if (_stateObj._pendingData)
-                        {
-                            if (!_stateObj.TryPeekByte(out b))
-                            {
-                                moreRows = false;
-                                return false;
-                            }
-                        }
-                        else
-                        {
-                            break;
-                        }
-                    }
-
-                    // Only return true when we are positioned on a row token.
-                    if (IsRowToken(b))
-                    {
-                        moreRows = true;
-                        return true;
-                    }
-                }
-            }
-            moreRows = false;
-            return true;
-        }
-
-        private bool IsRowToken(byte token)
-        {
-            return TdsEnums.SQLROW == token || TdsEnums.SQLNBCROW == token;
-        }
-
-        public override bool IsDBNull(int i)
-        {
-            {
-                CheckHeaderIsReady(columnIndex: i);
-
-                SetTimeout(_defaultTimeoutMilliseconds);
-
-                ReadColumnHeader(i);    // header data only
-            }
-
-            return _data[i].IsNull;
-        }
-
-        protected internal bool IsCommandBehavior(CommandBehavior condition)
-        {
-            return (condition == (condition & _commandBehavior));
-        }
-
-        public override bool NextResult()
-        {
-            if (_currentTask != null)
-            {
-                throw SQL.PendingBeginXXXExists();
-            }
-
-            bool more;
-            bool result;
-
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            result = TryNextResult(out more);
-
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-            return more;
-        }
-
-        // recordset is automatically positioned on the first result set
-        private bool TryNextResult(out bool more)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                SetTimeout(_defaultTimeoutMilliseconds);
-
-                if (IsClosed)
-                {
-                    throw ADP.DataReaderClosed(nameof(NextResult));
-                }
-                _fieldNameLookup = null;
-
-                bool success = false; // WebData 100390
-                _hasRows = false; // reset HasRows
-
-                // if we are specifically only processing a single result, then read all the results off the wire and detach
-                if (IsCommandBehavior(CommandBehavior.SingleResult))
-                {
-                    if (!TryCloseInternal(false /*closeReader*/))
-                    {
-                        more = false;
-                        return false;
-                    }
-
-                    // In the case of not closing the reader, null out the metadata AFTER
-                    // CloseInternal finishes - since CloseInternal may go to the wire
-                    // and use the metadata.
-                    ClearMetaData();
-                    more = success;
-                    return true;
-                }
-
-                if (null != _parser)
-                {
-                    // if there are more rows, then skip them, the user wants the next result
-                    bool moreRows = true;
-                    while (moreRows)
-                    {
-                        if (!TryReadInternal(false, out moreRows))
-                        { // don't reset set the timeout value
-                            more = false;
-                            return false;
-                        }
-                    }
-                }
-
-                // we may be done, so continue only if we have not detached ourselves from the parser
-                if (null != _parser)
-                {
-                    bool moreResults;
-                    if (!TryHasMoreResults(out moreResults))
-                    {
-                        more = false;
-                        return false;
-                    }
-                    if (moreResults)
-                    {
-                        _metaDataConsumed = false;
-                        _browseModeInfoConsumed = false;
-
-                        switch (_altRowStatus)
-                        {
-                            case ALTROWSTATUS.AltRow:
-                                int altRowId;
-                                if (!_parser.TryGetAltRowId(_stateObj, out altRowId))
-                                {
-                                    more = false;
-                                    return false;
-                                }
-                                _SqlMetaDataSet altMetaDataSet = _altMetaDataSetCollection.GetAltMetaData(altRowId);
-                                if (altMetaDataSet != null)
-                                {
-                                    _metaData = altMetaDataSet;
-                                }
-                                Debug.Assert((_metaData != null), "Can't match up altrowmetadata");
-                                break;
-                            case ALTROWSTATUS.Done:
-                                // restore the row-metaData
-                                _metaData = _altMetaDataSetCollection.metaDataSet;
-                                Debug.Assert(_altRowStatus == ALTROWSTATUS.Done, "invalid AltRowStatus");
-                                _altRowStatus = ALTROWSTATUS.Null;
-                                break;
-                            default:
-                                if (!TryConsumeMetaData())
-                                {
-                                    more = false;
-                                    return false;
-                                }
-                                if (_metaData == null)
-                                {
-                                    more = false;
-                                    return true;
-                                }
-                                break;
-                        }
-
-                        success = true;
-                    }
-                    else
-                    {
-                        // detach the parser from this reader now
-                        if (!TryCloseInternal(false /*closeReader*/))
-                        {
-                            more = false;
-                            return false;
-                        }
-
-                        // In the case of not closing the reader, null out the metadata AFTER
-                        // CloseInternal finishes - since CloseInternal may go to the wire
-                        // and use the metadata.
-                        if (!TrySetMetaData(null, false))
-                        {
-                            more = false;
-                            return false;
-                        }
-                    }
-                }
-                else
-                {
-                    // Clear state in case of Read calling CloseInternal() then user calls NextResult()
-                    // and the case where the Read() above will do essentially the same thing.
-                    ClearMetaData();
-                }
-
-                more = success;
-                return true;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        // user must call Read() to position on the first row
-        public override bool Read()
-        {
-            if (_currentTask != null)
-            {
-                throw SQL.PendingBeginXXXExists();
-            }
-
-            bool more;
-            bool result;
-
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            result = TryReadInternal(true, out more);
-
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-            return more;
-        }
-
-        // user must call Read() to position on the first row
-        private bool TryReadInternal(bool setTimeout, out bool more)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                if (null != _parser)
-                {
-                    if (setTimeout)
-                    {
-                        SetTimeout(_defaultTimeoutMilliseconds);
-                    }
-                    if (_sharedState._dataReady)
-                    {
-                        if (!TryCleanPartialRead())
-                        {
-                            more = false;
-                            return false;
-                        }
-                    }
-
-                    // clear out our buffers
-                    SqlBuffer.Clear(_data);
-
-                    _sharedState._nextColumnHeaderToRead = 0;
-                    _sharedState._nextColumnDataToRead = 0;
-                    _sharedState._columnDataBytesRemaining = -1; // unknown
-                    _lastColumnWithDataChunkRead = -1;
-
-                    if (!_haltRead)
-                    {
-                        bool moreRows;
-                        if (!TryHasMoreRows(out moreRows))
-                        {
-                            more = false;
-                            return false;
-                        }
-                        if (moreRows)
-                        {
-                            // read the row from the backend (unless it's an altrow were the marker is already inside the altrow ...)
-                            while (_stateObj._pendingData)
-                            {
-                                if (_altRowStatus != ALTROWSTATUS.AltRow)
-                                {
-                                    // if this is an ordinary row we let the run method consume the ROW token
-                                    if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out _sharedState._dataReady))
-                                    {
-                                        more = false;
-                                        return false;
-                                    }
-                                    if (_sharedState._dataReady)
-                                    {
-                                        break;
-                                    }
-                                }
-                                else
-                                {
-                                    // ALTROW token and AltrowId are already consumed ...
-                                    Debug.Assert(_altRowStatus == ALTROWSTATUS.AltRow, "invalid AltRowStatus");
-                                    _altRowStatus = ALTROWSTATUS.Done;
-                                    _sharedState._dataReady = true;
-                                    break;
-                                }
-                            }
-                            if (_sharedState._dataReady)
-                            {
-                                _haltRead = IsCommandBehavior(CommandBehavior.SingleRow);
-                                more = true;
-                                return true;
-                            }
-                        }
-
-                        if (!_stateObj._pendingData)
-                        {
-                            if (!TryCloseInternal(false /*closeReader*/))
-                            {
-                                more = false;
-                                return false;
-                            }
-                        }
-                    }
-                    else
-                    {
-                        // if we did not get a row and halt is true, clean off rows of result
-                        // success must be false - or else we could have just read off row and set
-                        // halt to true
-                        bool moreRows;
-                        if (!TryHasMoreRows(out moreRows))
-                        {
-                            more = false;
-                            return false;
-                        }
-                        while (moreRows)
-                        {
-                            // if we are in SingleRow mode, and we've read the first row,
-                            // read the rest of the rows, if any
-                            while (_stateObj._pendingData && !_sharedState._dataReady)
-                            {
-                                if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out _sharedState._dataReady))
-                                {
-                                    more = false;
-                                    return false;
-                                }
-                            }
-
-                            if (_sharedState._dataReady)
-                            {
-                                if (!TryCleanPartialRead())
-                                {
-                                    more = false;
-                                    return false;
-                                }
-                            }
-
-                            // clear out our buffers
-                            SqlBuffer.Clear(_data);
-
-                            _sharedState._nextColumnHeaderToRead = 0;
-
-                            if (!TryHasMoreRows(out moreRows))
-                            {
-                                more = false;
-                                return false;
-                            }
-                        }
-
-                        // reset haltRead
-                        _haltRead = false;
-                    }
-                }
-                else if (IsClosed)
-                {
-                    throw ADP.DataReaderClosed(nameof(Read));
-                }
-                more = false;
-
-#if DEBUG
-                if ((!_sharedState._dataReady) && (_stateObj._pendingData))
-                {
-                    byte token;
-                    if (!_stateObj.TryPeekByte(out token))
-                    {
-                        return false;
-                    }
-
-                    Debug.Assert(TdsParser.IsValidTdsToken(token), $"DataReady is false, but next token is invalid: {token,-2:X2}");
-                }
-#endif
-
-                return true;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private void ReadColumn(int i, bool setTimeout = true, bool allowPartiallyReadColumn = false)
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryReadColumn(i, setTimeout, allowPartiallyReadColumn);
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-        }
-
-        private bool TryReadColumn(int i, bool setTimeout, bool allowPartiallyReadColumn = false)
-        {
-            CheckDataIsReady(columnIndex: i, permitAsync: true, allowPartiallyReadColumn: allowPartiallyReadColumn, methodName: null);
-
-            Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large");
-            Debug.Assert(_sharedState._nextColumnDataToRead <= _metaData.Length, "_sharedState._nextColumnDataToRead too large");
-
-            if (setTimeout)
-            {
-                SetTimeout(_defaultTimeoutMilliseconds);
-            }
-
-            if (!TryReadColumnInternal(i, readHeaderOnly: false))
-            {
-                return false;
-            }
-
-            Debug.Assert(null != _data[i], " data buffer is null?");
-
-            return true;
-        }
-
-        private bool TryReadColumnData()
-        {
-            // If we've already read the value (because it was NULL) we don't
-            // bother to read here.
-            if (!_data[_sharedState._nextColumnDataToRead].IsNull)
-            {
-                _SqlMetaData columnMetaData = _metaData[_sharedState._nextColumnDataToRead];
-
-                if (!_parser.TryReadSqlValue(_data[_sharedState._nextColumnDataToRead], columnMetaData, (int)_sharedState._columnDataBytesRemaining, _stateObj))
-                { // will read UDTs as VARBINARY.
-                    return false;
-                }
-                _sharedState._columnDataBytesRemaining = 0;
-            }
-            _sharedState._nextColumnDataToRead++;
-            return true;
-        }
-
-        private void ReadColumnHeader(int i)
-        {
-            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryReadColumnHeader(i);
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-        }
-
-        private bool TryReadColumnHeader(int i)
-        {
-            if (!_sharedState._dataReady)
-            {
-                throw SQL.InvalidRead();
-            }
-            return TryReadColumnInternal(i, readHeaderOnly: true);
-        }
-
-        private bool TryReadColumnInternal(int i, bool readHeaderOnly = false)
-        {
-            AssertReaderState(requireData: true, permitAsync: true, columnIndex: i);
-
-            // Check if we've already read the header already
-            if (i < _sharedState._nextColumnHeaderToRead)
-            {
-                // Read the header, but we need to read the data
-                if ((i == _sharedState._nextColumnDataToRead) && (!readHeaderOnly))
-                {
-                    return TryReadColumnData();
-                }
-                // Else we've already read the data, or we're reading the header only
-                else
-                {
-                    // Ensure that, if we've read past the column, then we did store its data
-                    Debug.Assert(i == _sharedState._nextColumnDataToRead ||                                                          // Either we haven't read the column yet
-                        ((i + 1 < _sharedState._nextColumnDataToRead) && (IsCommandBehavior(CommandBehavior.SequentialAccess))) ||   // Or we're in sequential mode and we've read way past the column (i.e. it was not the last column we read)
-                        (!_data[i].IsEmpty || _data[i].IsNull) ||                                                       // Or we should have data stored for the column (unless the column was null)
-                        (_metaData[i].type == SqlDbType.Timestamp),                                                     // Or SqlClient: IsDBNull always returns false for timestamp datatype
-                        "Gone past column, be we have no data stored for it");
-                    return true;
-                }
-            }
-
-            Debug.Assert(_data[i].IsEmpty || _data[i].IsNull, "re-reading column value?");
-
-            // If we're in sequential access mode, we can safely clear out any
-            // data from the previous column.
-            bool isSequentialAccess = IsCommandBehavior(CommandBehavior.SequentialAccess);
-            if (isSequentialAccess)
-            {
-                if (0 < _sharedState._nextColumnDataToRead)
-                {
-                    _data[_sharedState._nextColumnDataToRead - 1].Clear();
-                }
-
-                // Only wipe out the blob objects if they aren't for a 'future' column (i.e. we haven't read up to them yet)
-                if ((_lastColumnWithDataChunkRead > -1) && (i > _lastColumnWithDataChunkRead))
-                {
-                    CloseActiveSequentialStreamAndTextReader();
-                }
-            }
-            else if (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead)
-            {
-                // We read the header but not the column for the previous column
-                if (!TryReadColumnData())
-                {
-                    return false;
-                }
-                Debug.Assert(_sharedState._nextColumnDataToRead == _sharedState._nextColumnHeaderToRead);
-            }
-
-            // if we still have bytes left from the previous blob read, clear the wire and reset
-            if (!TryResetBlobState())
-            {
-                return false;
-            }
-
-            do
-            {
-                _SqlMetaData columnMetaData = _metaData[_sharedState._nextColumnHeaderToRead];
-
-                if ((isSequentialAccess) && (_sharedState._nextColumnHeaderToRead < i))
-                {
-                    // SkipValue is no-op if the column appears in NBC bitmask
-                    // if not, it skips regular and PLP types
-                    if (!_parser.TrySkipValue(columnMetaData, _sharedState._nextColumnHeaderToRead, _stateObj))
-                    {
-                        return false;
-                    }
-
-                    _sharedState._nextColumnDataToRead = _sharedState._nextColumnHeaderToRead;
-                    _sharedState._nextColumnHeaderToRead++;
-                }
-                else
-                {
-                    bool isNull;
-                    ulong dataLength;
-                    if (!_parser.TryProcessColumnHeader(columnMetaData, _stateObj, _sharedState._nextColumnHeaderToRead, out isNull, out dataLength))
-                    {
-                        return false;
-                    }
-
-                    _sharedState._nextColumnDataToRead = _sharedState._nextColumnHeaderToRead;
-                    _sharedState._nextColumnHeaderToRead++;  // We read this one
-                    if (isNull && columnMetaData.type != SqlDbType.Timestamp)
-                    {
-                        _parser.GetNullSqlValue(_data[_sharedState._nextColumnDataToRead], columnMetaData);
-
-                        if (!readHeaderOnly)
-                        {
-                            _sharedState._nextColumnDataToRead++;
-                        }
-                    }
-                    else
-                    {
-                        if ((i > _sharedState._nextColumnDataToRead) || (!readHeaderOnly))
-                        {
-                            // If we're not in sequential access mode, we have to
-                            // save the data we skip over so that the consumer
-                            // can read it out of order
-                            if (!_parser.TryReadSqlValue(_data[_sharedState._nextColumnDataToRead], columnMetaData, (int)dataLength, _stateObj))
-                            { // will read UDTs as VARBINARY.
-                                return false;
-                            }
-                            _sharedState._nextColumnDataToRead++;
-                        }
-                        else
-                        {
-                            _sharedState._columnDataBytesRemaining = (long)dataLength;
-                        }
-                    }
-                }
-
-                if (_snapshot != null)
-                {
-                    // reset snapshot to save memory use.  We can safely do that here because all SqlDataReader values are stable.
-                    // The retry logic can use the current values to get back to the right state.
-                    _snapshot = null;
-                    PrepareAsyncInvocation(useSnapshot: true);
-                }
-            } while (_sharedState._nextColumnHeaderToRead <= i);
-
-            return true;
-        }
-
-        // Estimates if there is enough data available to read the number of columns requested
-        private bool WillHaveEnoughData(int targetColumn, bool headerOnly = false)
-        {
-            AssertReaderState(requireData: true, permitAsync: true, columnIndex: targetColumn);
-
-            if ((_lastColumnWithDataChunkRead == _sharedState._nextColumnDataToRead) && (_metaData[_lastColumnWithDataChunkRead].metaType.IsPlp))
-            {
-                // In the middle of reading a Plp - no idea how much is left
-                return false;
-            }
-
-            int bytesRemaining = Math.Min(checked(_stateObj._inBytesRead - _stateObj._inBytesUsed), _stateObj._inBytesPacket);
-
-            // There are some parts of our code that peeks at the next token after doing its read
-            // So we will make sure that there is always a spare byte for it to look at
-            bytesRemaining--;
-
-            if ((targetColumn >= _sharedState._nextColumnDataToRead) && (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead))
-            {
-                if (_sharedState._columnDataBytesRemaining > bytesRemaining)
-                {
-                    // The current column needs more data than we currently have
-                    // NOTE: Since the Long data types (TEXT, IMAGE, NTEXT) can have a size of Int32.MaxValue we cannot simply subtract
-                    // _columnDataBytesRemaining from bytesRemaining and then compare it to zero as this may lead to an overflow
-                    return false;
-                }
-                else
-                {
-                    // Already read the header, so subtract actual data size
-                    bytesRemaining = checked(bytesRemaining - (int)_sharedState._columnDataBytesRemaining);
-                }
-            }
-
-            // For each column that we need to read, subtract the size of its header and the size of its data
-            int currentColumn = _sharedState._nextColumnHeaderToRead;
-            while ((bytesRemaining >= 0) && (currentColumn <= targetColumn))
-            {
-                // Check NBC first
-                if (!_stateObj.IsNullCompressionBitSet(currentColumn))
-                {
-                    // NOTE: This is mostly duplicated from TryProcessColumnHeaderNoNBC and TryGetTokenLength
-                    var metaType = _metaData[currentColumn].metaType;
-                    if ((metaType.IsLong) || (metaType.IsPlp) || (metaType.SqlDbType == SqlDbType.Udt) || (metaType.SqlDbType == SqlDbType.Structured))
-                    {
-                        // Plp, Udt and TVP types have an unknowable size - so return that the estimate failed
-                        return false;
-                    }
-                    int maxHeaderSize;
-                    byte typeAndMask = (byte)(_metaData[currentColumn].tdsType & TdsEnums.SQLLenMask);
-                    if ((typeAndMask == TdsEnums.SQLVarLen) || (typeAndMask == TdsEnums.SQLVarCnt))
-                    {
-                        if (0 != (_metaData[currentColumn].tdsType & 0x80))
-                        {
-                            // UInt16 represents size
-                            maxHeaderSize = 2;
-                        }
-                        else if (0 == (_metaData[currentColumn].tdsType & 0x0c))
-                        {
-                            // UInt32 represents size
-                            maxHeaderSize = 4;
-                        }
-                        else
-                        {
-                            // Byte represents size
-                            maxHeaderSize = 1;
-                        }
-                    }
-                    else
-                    {
-                        maxHeaderSize = 0;
-                    }
-
-                    bytesRemaining = checked(bytesRemaining - maxHeaderSize);
-                    if ((currentColumn < targetColumn) || (!headerOnly))
-                    {
-                        bytesRemaining = checked(bytesRemaining - _metaData[currentColumn].length);
-                    }
-                }
-
-                currentColumn++;
-            }
-
-            return (bytesRemaining >= 0);
-        }
-
-        // clean remainder bytes for the column off the wire
-        private bool TryResetBlobState()
-        {
-            Debug.Assert(null != _stateObj, "null state object"); // _parser may be null at this point
-            AssertReaderState(requireData: true, permitAsync: true);
-            Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large");
-
-            // If we haven't already entirely read the column
-            if (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead)
-            {
-                if ((_sharedState._nextColumnHeaderToRead > 0) && (_metaData[_sharedState._nextColumnHeaderToRead - 1].metaType.IsPlp))
-                {
-                    if (_stateObj._longlen != 0)
-                    {
-                        ulong ignored;
-                        if (!_stateObj.Parser.TrySkipPlpValue(ulong.MaxValue, _stateObj, out ignored))
-                        {
-                            return false;
-                        }
-                    }
-                    if (_streamingXml != null)
-                    {
-                        SqlStreamingXml localSXml = _streamingXml;
-                        _streamingXml = null;
-                        localSXml.Close();
-                    }
-                }
-                else if (0 < _sharedState._columnDataBytesRemaining)
-                {
-                    if (!_stateObj.TrySkipLongBytes(_sharedState._columnDataBytesRemaining))
-                    {
-                        return false;
-                    }
-                }
-            }
-#if DEBUG
-            else
-            {
-                Debug.Assert((_sharedState._columnDataBytesRemaining == 0 || _sharedState._columnDataBytesRemaining == -1) && _stateObj._longlen == 0, "Haven't read header yet, but column is partially read?");
-            }
-#endif
-
-            _sharedState._columnDataBytesRemaining = 0;
-            _columnDataBytesRead = 0;
-            _columnDataCharsRead = 0;
-            _columnDataChars = null;
-            _columnDataCharsIndex = -1;
-            _stateObj._plpdecoder = null;
-
-            return true;
-        }
-
-        private void CloseActiveSequentialStreamAndTextReader()
-        {
-            if (_currentStream != null)
-            {
-                _currentStream.SetClosed();
-                _currentStream = null;
-            }
-            if (_currentTextReader != null)
-            {
-                _currentTextReader.SetClosed();
-                _currentStream = null;
-            }
-        }
-
-        private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateObj)
-        {
-            // turn off any set options
-            if (null != parser && null != _resetOptionsString)
-            {
-                // It is possible for this to be called during connection close on a
-                // broken connection, so check state first.
-                if (parser.State == TdsParserState.OpenLoggedIn)
-                {
-                    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");
-
-                    // must execute this one synchronously as we can't retry
-                    parser.Run(RunBehavior.UntilDone, _command, this, null, stateObj);
-                }
-                _resetOptionsString = null;
-            }
-        }
-
-        internal bool TrySetAltMetaDataSet(_SqlMetaDataSet metaDataSet, bool metaDataConsumed)
-        {
-            if (_altMetaDataSetCollection == null)
-            {
-                _altMetaDataSetCollection = new _SqlMetaDataSetCollection();
-            }
-            else if (_snapshot != null && object.ReferenceEquals(_snapshot._altMetaDataSetCollection, _altMetaDataSetCollection))
-            {
-                _altMetaDataSetCollection = (_SqlMetaDataSetCollection)_altMetaDataSetCollection.Clone();
-            }
-            _altMetaDataSetCollection.SetAltMetaData(metaDataSet);
-            _metaDataConsumed = metaDataConsumed;
-            if (_metaDataConsumed && null != _parser)
-            {
-                byte b;
-                if (!_stateObj.TryPeekByte(out b))
-                {
-                    return false;
-                }
-                if (TdsEnums.SQLORDER == b)
-                {
-                    bool ignored;
-                    if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored))
-                    {
-                        return false;
-                    }
-                    if (!_stateObj.TryPeekByte(out b))
-                    {
-                        return false;
-                    }
-                }
-                if (b == TdsEnums.SQLINFO)
-                {
-                    try
-                    {
-                        _stateObj._accumulateInfoEvents = true;
-                        bool ignored;
-                        if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, null, null, _stateObj, out ignored))
-                        {
-                            return false;
-                        }
-                    }
-                    finally
-                    {
-                        _stateObj._accumulateInfoEvents = false;
-                    }
-                    if (!_stateObj.TryPeekByte(out b))
-                    {
-                        return false;
-                    }
-                }
-                _hasRows = IsRowToken(b);
-            }
-            if (metaDataSet != null)
-            {
-                if (_data == null || _data.Length < metaDataSet.Length)
-                {
-                    _data = SqlBuffer.CreateBufferArray(metaDataSet.Length);
-                }
-            }
-            return true;
-        }
-
-        private void ClearMetaData()
-        {
-            _metaData = null;
-            _tableNames = null;
-            _fieldNameLookup = null;
-            _metaDataConsumed = false;
-            _browseModeInfoConsumed = false;
-        }
-
-        internal bool TrySetMetaData(_SqlMetaDataSet metaData, bool moreInfo)
-        {
-            _metaData = metaData;
-
-            // get rid of cached metadata info as well
-            _tableNames = null;
-            if (_metaData != null)
-            {
-                _data = SqlBuffer.CreateBufferArray(metaData.Length);
-            }
-
-            _fieldNameLookup = null;
-
-            if (null != metaData)
-            {
-                // we are done consuming metadata only if there is no moreInfo
-                if (!moreInfo)
-                {
-                    _metaDataConsumed = true;
-
-                    if (_parser != null)
-                    { // There is a valid case where parser is null
-                        // Peek, and if row token present, set _hasRows true since there is a
-                        // row in the result
-                        byte b;
-                        if (!_stateObj.TryPeekByte(out b))
-                        {
-                            return false;
-                        }
-
-                        // simply rip the order token off the wire
-                        if (b == TdsEnums.SQLORDER)
-                        {                     //  same logic as SetAltMetaDataSet
-                            bool ignored;
-                            if (!_parser.TryRun(RunBehavior.ReturnImmediately, null, null, null, _stateObj, out ignored))
-                            {
-                                return false;
-                            }
-                            if (!_stateObj.TryPeekByte(out b))
-                            {
-                                return false;
-                            }
-                        }
-                        if (b == TdsEnums.SQLINFO)
-                        {
-                            // VSTFDEVDIV713926
-                            // We are accumulating informational events and fire them at next
-                            // TdsParser.Run purely to avoid breaking change
-                            try
-                            {
-                                _stateObj._accumulateInfoEvents = true;
-                                bool ignored;
-                                if (!_parser.TryRun(RunBehavior.ReturnImmediately, null, null, null, _stateObj, out ignored))
-                                {
-                                    return false;
-                                }
-                            }
-                            finally
-                            {
-                                _stateObj._accumulateInfoEvents = false;
-                            }
-                            if (!_stateObj.TryPeekByte(out b))
-                            {
-                                return false;
-                            }
-                        }
-                        _hasRows = IsRowToken(b);
-                        if (TdsEnums.SQLALTMETADATA == b)
-                        {
-                            _metaDataConsumed = false;
-                        }
-                    }
-                }
-            }
-            else
-            {
-                _metaDataConsumed = false;
-            }
-
-            _browseModeInfoConsumed = false;
-            return true;
-        }
-
-        private void SetTimeout(long timeoutMilliseconds)
-        {
-            // WebData 111653,112003 -- we now set timeouts per operation, not
-            // per command (it's not supposed to be a cumulative per command).
-            TdsParserStateObject stateObj = _stateObj;
-            if (null != stateObj)
-            {
-                stateObj.SetTimeoutMilliseconds(timeoutMilliseconds);
-            }
-        }
-
-        private bool HasActiveStreamOrTextReaderOnColumn(int columnIndex)
-        {
-            bool active = false;
-
-            active |= ((_currentStream != null) && (_currentStream.ColumnIndex == columnIndex));
-            active |= ((_currentTextReader != null) && (_currentTextReader.ColumnIndex == columnIndex));
-
-            return active;
-        }
-
-        private void CheckMetaDataIsReady()
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-            if (MetaData == null)
-            {
-                throw SQL.InvalidRead();
-            }
-        }
-
-        private void CheckMetaDataIsReady(int columnIndex, bool permitAsync = false)
-        {
-            if ((!permitAsync) && (_currentTask != null))
-            {
-                throw ADP.AsyncOperationPending();
-            }
-            if (MetaData == null)
-            {
-                throw SQL.InvalidRead();
-            }
-            if ((columnIndex < 0) || (columnIndex >= _metaData.Length))
-            {
-                throw ADP.IndexOutOfRange();
-            }
-        }
-
-        private void CheckDataIsReady()
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
-            if ((!_sharedState._dataReady) || (_metaData == null))
-            {
-                throw SQL.InvalidRead();
-            }
-        }
-
-        private void CheckHeaderIsReady(int columnIndex, bool permitAsync = false, [CallerMemberName] string methodName = null)
-        {
-            if (_isClosed)
-            {
-                throw ADP.DataReaderClosed(methodName ?? nameof(CheckHeaderIsReady));
-            }
-            if ((!permitAsync) && (_currentTask != null))
-            {
-                throw ADP.AsyncOperationPending();
-            }
-            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
-            if ((!_sharedState._dataReady) || (_metaData == null))
-            {
-                throw SQL.InvalidRead();
-            }
-            if ((columnIndex < 0) || (columnIndex >= _metaData.Length))
-            {
-                throw ADP.IndexOutOfRange();
-            }
-            if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) &&                                          // Only for sequential access
-                ((_sharedState._nextColumnHeaderToRead > columnIndex + 1) || (_lastColumnWithDataChunkRead > columnIndex)))
-            {  // Read past column
-                throw ADP.NonSequentialColumnAccess(columnIndex, Math.Max(_sharedState._nextColumnHeaderToRead - 1, _lastColumnWithDataChunkRead));
-            }
-        }
-
-        private void CheckDataIsReady(int columnIndex, bool allowPartiallyReadColumn = false, bool permitAsync = false, [CallerMemberName] string methodName = null)
-        {
-            if (_isClosed)
-            {
-                throw ADP.DataReaderClosed(methodName ?? nameof(CheckDataIsReady));
-            }
-            if ((!permitAsync) && (_currentTask != null))
-            {
-                throw ADP.AsyncOperationPending();
-            }
-            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
-            if ((!_sharedState._dataReady) || (_metaData == null))
-            {
-                throw SQL.InvalidRead();
-            }
-            if ((columnIndex < 0) || (columnIndex >= _metaData.Length))
-            {
-                throw ADP.IndexOutOfRange();
-            }
-            if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) &&                                    // Only for sequential access
-                ((_sharedState._nextColumnDataToRead > columnIndex) || (_lastColumnWithDataChunkRead > columnIndex) ||   // Read past column
-                ((!allowPartiallyReadColumn) && (_lastColumnWithDataChunkRead == columnIndex)) ||           // Partially read column
-                ((allowPartiallyReadColumn) && (HasActiveStreamOrTextReaderOnColumn(columnIndex)))))
-            {      // Has a Stream or TextReader on a partially-read column
-                throw ADP.NonSequentialColumnAccess(columnIndex, Math.Max(_sharedState._nextColumnDataToRead, _lastColumnWithDataChunkRead + 1));
-            }
-        }
-
-        [Conditional("DEBUG")]
-        private void AssertReaderState(bool requireData, bool permitAsync, int? columnIndex = null, bool enforceSequentialAccess = false)
-        {
-            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
-            Debug.Assert(permitAsync || _currentTask == null, "Call while async operation is pending");
-            Debug.Assert(_metaData != null, "_metaData is null, check MetaData before calling this method");
-            Debug.Assert(!requireData || _sharedState._dataReady, "No data is ready to be read");
-            if (columnIndex.HasValue)
-            {
-                Debug.Assert(columnIndex.Value >= 0 && columnIndex.Value < _metaData.Length, "Invalid column index");
-                Debug.Assert((!enforceSequentialAccess) || (!IsCommandBehavior(CommandBehavior.SequentialAccess)) || ((_sharedState._nextColumnDataToRead <= columnIndex) && (_lastColumnWithDataChunkRead <= columnIndex)), "Already read past column");
-            }
-        }
-
-        public override Task<bool> NextResultAsync(CancellationToken cancellationToken)
-        {
-            TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
-
-            if (IsClosed)
-            {
-                source.SetException(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed()));
-                return source.Task;
-            }
-
-            IDisposable registration = null;
-            if (cancellationToken.CanBeCanceled)
-            {
-                if (cancellationToken.IsCancellationRequested)
-                {
-                    source.SetCanceled();
-                    return source.Task;
-                }
-                registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), _command);
-            }
-
-            Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
-            if (original != null)
-            {
-                source.SetException(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
-                return source.Task;
-            }
-
-            // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
-            if (_cancelAsyncOnCloseToken.IsCancellationRequested)
-            {
-                source.SetCanceled();
-                _currentTask = null;
-                return source.Task;
-            }
-
-            PrepareAsyncInvocation(useSnapshot: true);
-
-            Func<Task, Task<bool>> moreFunc = null;
-
-            moreFunc = (t) =>
-            {
-                if (t != null)
-                {
-                    PrepareForAsyncContinuation();
-                }
-
-                bool more;
-                if (TryNextResult(out more))
-                {
-                    // completed
-                    return more ? ADP.TrueTask : ADP.FalseTask;
-                }
-
-                return ContinueRetryable(moreFunc);
-            };
-
-            return InvokeRetryable(moreFunc, source, registration);
-        }
-
-        // NOTE: This will return null if it completed sequentially
-        // If this returns null, then you can use bytesRead to see how many bytes were read - otherwise bytesRead should be ignored
-        internal Task<int> GetBytesAsync(int i, byte[] buffer, int index, int length, int timeout, CancellationToken cancellationToken, out int bytesRead)
-        {
-            AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
-            Debug.Assert(IsCommandBehavior(CommandBehavior.SequentialAccess));
-
-            bytesRead = 0;
-            if (IsClosed)
-            {
-                return Task.FromException<int>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed()));
-            }
-
-            if (_currentTask != null)
-            {
-                return Task.FromException<int>(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-            }
-
-            if (cancellationToken.CanBeCanceled)
-            {
-                if (cancellationToken.IsCancellationRequested)
-                {
-                    return null;
-                }
-            }
-
-            // Check if we need to skip columns
-            Debug.Assert(_sharedState._nextColumnDataToRead <= _lastColumnWithDataChunkRead, "Non sequential access");
-            if ((_sharedState._nextColumnHeaderToRead <= _lastColumnWithDataChunkRead) || (_sharedState._nextColumnDataToRead < _lastColumnWithDataChunkRead))
-            {
-                TaskCompletionSource<int> source = new TaskCompletionSource<int>();
-                Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
-                if (original != null)
-                {
-                    source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-                    return source.Task;
-                }
-
-                PrepareAsyncInvocation(useSnapshot: true);
-
-                Func<Task, Task<int>> moreFunc = null;
-
-                // Timeout
-                CancellationToken timeoutToken = CancellationToken.None;
-                CancellationTokenSource timeoutCancellationSource = null;
-                if (timeout > 0)
-                {
-                    timeoutCancellationSource = new CancellationTokenSource();
-                    timeoutCancellationSource.CancelAfter(timeout);
-                    timeoutToken = timeoutCancellationSource.Token;
-                }
-
-                moreFunc = (t) =>
-                {
-                    if (t != null)
-                    {
-                        PrepareForAsyncContinuation();
-                    }
-
-                    // Prepare for stateObj timeout
-                    SetTimeout(_defaultTimeoutMilliseconds);
-
-                    if (TryReadColumnHeader(i))
-                    {
-                        // Only once we have read up to where we need to be can we check the cancellation tokens (otherwise we will be in an unknown state)
-
-                        if (cancellationToken.IsCancellationRequested)
-                        {
-                            // User requested cancellation
-                            return Task.FromCanceled<int>(cancellationToken);
-                        }
-                        else if (timeoutToken.IsCancellationRequested)
-                        {
-                            // Timeout
-                            return Task.FromException<int>(ADP.ExceptionWithStackTrace(ADP.IO(SQLMessage.Timeout())));
-                        }
-                        else
-                        {
-                            // Up to the correct column - continue to read
-                            SwitchToAsyncWithoutSnapshot();
-                            int totalBytesRead;
-                            var readTask = GetBytesAsyncReadDataStage(i, buffer, index, length, timeout, true, cancellationToken, timeoutToken, out totalBytesRead);
-                            if (readTask == null)
-                            {
-                                // Completed synchronously
-                                return Task.FromResult<int>(totalBytesRead);
-                            }
-                            else
-                            {
-                                return readTask;
-                            }
-                        }
-                    }
-                    else
-                    {
-                        return ContinueRetryable(moreFunc);
-                    }
-                };
-
-                return InvokeRetryable(moreFunc, source, timeoutCancellationSource);
-            }
-            else
-            {
-                // We're already at the correct column, just read the data
-
-                // Switch to async
-                PrepareAsyncInvocation(useSnapshot: false);
-
-                try
-                {
-                    return GetBytesAsyncReadDataStage(i, buffer, index, length, timeout, false, cancellationToken, CancellationToken.None, out bytesRead);
-                }
-                catch
-                {
-                    CleanupAfterAsyncInvocation();
-                    throw;
-                }
-            }
-        }
-
-        private Task<int> GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, int length, int timeout, bool isContinuation, CancellationToken cancellationToken, CancellationToken timeoutToken, out int bytesRead)
-        {
-            _lastColumnWithDataChunkRead = i;
-            TaskCompletionSource<int> source = null;
-            CancellationTokenSource timeoutCancellationSource = null;
-
-            // Prepare for stateObj timeout
-            SetTimeout(_defaultTimeoutMilliseconds);
-
-            // Try to read without any continuations (all the data may already be in the stateObj's buffer)
-            if (!TryGetBytesInternalSequential(i, buffer, index, length, out bytesRead))
-            {
-                // This will be the 'state' for the callback
-                int totalBytesRead = bytesRead;
-
-                if (!isContinuation)
-                {
-                    // This is the first async operation which is happening - setup the _currentTask and timeout
-                    source = new TaskCompletionSource<int>();
-                    Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
-                    if (original != null)
-                    {
-                        source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-                        return source.Task;
-                    }
-
-                    // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
-                    if (_cancelAsyncOnCloseToken.IsCancellationRequested)
-                    {
-                        source.SetCanceled();
-                        _currentTask = null;
-                        return source.Task;
-                    }
-
-                    // Timeout
-                    Debug.Assert(timeoutToken == CancellationToken.None, "TimeoutToken is set when GetBytesAsyncReadDataStage is not a continuation");
-                    if (timeout > 0)
-                    {
-                        timeoutCancellationSource = new CancellationTokenSource();
-                        timeoutCancellationSource.CancelAfter(timeout);
-                        timeoutToken = timeoutCancellationSource.Token;
-                    }
-                }
-
-                Func<Task, Task<int>> moreFunc = null;
-                moreFunc = (_ =>
-                {
-                    PrepareForAsyncContinuation();
-
-                    if (cancellationToken.IsCancellationRequested)
-                    {
-                        // User requested cancellation
-                        return Task.FromCanceled<int>(cancellationToken);
-                    }
-                    else if (timeoutToken.IsCancellationRequested)
-                    {
-                        // Timeout
-                        return Task.FromException<int>(ADP.ExceptionWithStackTrace(ADP.IO(SQLMessage.Timeout())));
-                    }
-                    else
-                    {
-                        // Prepare for stateObj timeout
-                        SetTimeout(_defaultTimeoutMilliseconds);
-
-                        int bytesReadThisIteration;
-                        bool result = TryGetBytesInternalSequential(i, buffer, index + totalBytesRead, length - totalBytesRead, out bytesReadThisIteration);
-                        totalBytesRead += bytesReadThisIteration;
-                        Debug.Assert(totalBytesRead <= length, "Read more bytes than required");
-
-                        if (result)
-                        {
-                            return Task.FromResult<int>(totalBytesRead);
-                        }
-                        else
-                        {
-                            return ContinueRetryable(moreFunc);
-                        }
-                    }
-                });
-
-                Task<int> retryTask = ContinueRetryable(moreFunc);
-                if (isContinuation)
-                {
-                    // Let the caller handle cleanup\completing
-                    return retryTask;
-                }
-                else
-                {
-                    // setup for cleanup\completing
-                    retryTask.ContinueWith((t) => CompleteRetryable(t, source, timeoutCancellationSource), TaskScheduler.Default);
-                    return source.Task;
-                }
-            }
-
-            if (!isContinuation)
-            {
-                // If this is the first async op, we need to cleanup
-                CleanupAfterAsyncInvocation();
-            }
-            // Completed synchronously, return null
-            return null;
-        }
-
-        public override Task<bool> ReadAsync(CancellationToken cancellationToken)
-        {
-            if (IsClosed)
-            {
-                return Task.FromException<bool>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed()));
-            }
-
-            // If user's token is canceled, return a canceled task
-            if (cancellationToken.IsCancellationRequested)
-            {
-                return Task.FromCanceled<bool>(cancellationToken);
-            }
-
-            // Check for existing async
-            if (_currentTask != null)
-            {
-                return Task.FromException<bool>(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
-            }
-
-            // These variables will be captured in moreFunc so that we can skip searching for a row token once one has been read
-            bool rowTokenRead = false;
-            bool more = false;
-
-            // Shortcut, do we have enough data to immediately do the ReadAsync?
-            try
-            {
-                // First, check if we can finish reading the current row
-                // NOTE: If we are in SingleRow mode and we've read that single row (i.e. _haltRead == true), then skip the shortcut
-                if ((!_haltRead) && ((!_sharedState._dataReady) || (WillHaveEnoughData(_metaData.Length - 1))))
-                {
-#if DEBUG
-                    try
-                    {
-                        _stateObj._shouldHaveEnoughData = true;
-#endif
-                        if (_sharedState._dataReady)
-                        {
-                            // Clean off current row
-                            CleanPartialReadReliable();
-                        }
-
-                        // If there a ROW token ready (as well as any metadata for the row)
-                        if (_stateObj.IsRowTokenReady())
-                        {
-                            // Read the ROW token
-                            bool result = TryReadInternal(true, out more);
-                            Debug.Assert(result, "Should not have run out of data");
-
-                            rowTokenRead = true;
-                            if (more)
-                            {
-                                // Sequential mode, nothing left to do
-                                if (IsCommandBehavior(CommandBehavior.SequentialAccess))
-                                {
-                                    return ADP.TrueTask;
-                                }
-                                // For non-sequential, check if we can read the row data now
-                                else if (WillHaveEnoughData(_metaData.Length - 1))
-                                {
-                                    // Read row data
-                                    result = TryReadColumn(_metaData.Length - 1, setTimeout: true);
-                                    Debug.Assert(result, "Should not have run out of data");
-                                    return ADP.TrueTask;
-                                }
-                            }
-                            else
-                            {
-                                // No data left, return
-                                return ADP.FalseTask;
-                            }
-                        }
-#if DEBUG
-                    }
-                    finally
-                    {
-                        _stateObj._shouldHaveEnoughData = false;
-                    }
-#endif
-                }
-            }
-            catch (Exception ex)
-            {
-                if (!ADP.IsCatchableExceptionType(ex))
-                {
-                    throw;
-                }
-                return Task.FromException<bool>(ex);
-            }
-
-            TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
-            Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
-            if (original != null)
-            {
-                source.SetException(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
-                return source.Task;
-            }
-
-            // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
-            if (_cancelAsyncOnCloseToken.IsCancellationRequested)
-            {
-                source.SetCanceled();
-                _currentTask = null;
-                return source.Task;
-            }
-
-            IDisposable registration = null;
-            if (cancellationToken.CanBeCanceled)
-            {
-                registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), _command);
-            }
-
-            PrepareAsyncInvocation(useSnapshot: true);
-
-            Func<Task, Task<bool>> moreFunc = null;
-            moreFunc = (t) =>
-            {
-                if (t != null)
-                {
-                    PrepareForAsyncContinuation();
-                }
-
-                if (rowTokenRead || TryReadInternal(true, out more))
-                {
-                    // If there are no more rows, or this is Sequential Access, then we are done
-                    if (!more || (_commandBehavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess)
-                    {
-                        // completed
-                        return more ? ADP.TrueTask : ADP.FalseTask;
-                    }
-                    else
-                    {
-                        // First time reading the row token - update the snapshot
-                        if (!rowTokenRead)
-                        {
-                            rowTokenRead = true;
-                            _snapshot = null;
-                            PrepareAsyncInvocation(useSnapshot: true);
-                        }
-
-                        // if non-sequentialaccess then read entire row before returning
-                        if (TryReadColumn(_metaData.Length - 1, true))
-                        {
-                            // completed
-                            return ADP.TrueTask;
-                        }
-                    }
-                }
-
-                return ContinueRetryable(moreFunc);
-            };
-
-            return InvokeRetryable(moreFunc, source, registration);
-        }
-
-        public override Task<bool> IsDBNullAsync(int i, CancellationToken cancellationToken)
-        {
-            try
-            {
-                CheckHeaderIsReady(columnIndex: i);
-            }
-            catch (Exception ex)
-            {
-                if (!ADP.IsCatchableExceptionType(ex))
-                {
-                    throw;
-                }
-                return Task.FromException<bool>(ex);
-            }
-
-            // Shortcut - if there are no issues and the data is already read, then just return the value
-            if ((_sharedState._nextColumnHeaderToRead > i) && (!cancellationToken.IsCancellationRequested) && (_currentTask == null))
-            {
-                var data = _data;
-                if (data != null)
-                {
-                    return data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
-                }
-                else
-                {
-                    // Reader was closed between the CheckHeaderIsReady and accessing _data - throw closed exception
-                    return Task.FromException<bool>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed()));
-                }
-            }
-            else
-            {
-                // Throw if there is any current task
-                if (_currentTask != null)
-                {
-                    return Task.FromException<bool>(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-                }
-
-                // If user's token is canceled, return a canceled task
-                if (cancellationToken.IsCancellationRequested)
-                {
-                    return Task.FromCanceled<bool>(cancellationToken);
-                }
-
-                // Shortcut - if we have enough data, then run sync
-                try
-                {
-                    if (WillHaveEnoughData(i, headerOnly: true))
-                    {
-#if DEBUG
-                        try
-                        {
-                            _stateObj._shouldHaveEnoughData = true;
-#endif
-                            ReadColumnHeader(i);
-                            return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
-#if DEBUG
-                        }
-                        finally
-                        {
-                            _stateObj._shouldHaveEnoughData = false;
-                        }
-#endif
-                    }
-                }
-                catch (Exception ex)
-                {
-                    if (!ADP.IsCatchableExceptionType(ex))
-                    {
-                        throw;
-                    }
-                    return Task.FromException<bool>(ex);
-                }
-
-                // Setup and check for pending task
-                TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
-                Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
-                if (original != null)
-                {
-                    source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-                    return source.Task;
-                }
-
-                // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
-                if (_cancelAsyncOnCloseToken.IsCancellationRequested)
-                {
-                    source.SetCanceled();
-                    _currentTask = null;
-                    return source.Task;
-                }
-
-                // Setup cancellations
-                IDisposable registration = null;
-                if (cancellationToken.CanBeCanceled)
-                {
-                    registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), _command);
-                }
-
-                // Setup async
-                PrepareAsyncInvocation(useSnapshot: true);
-
-                // Setup the retryable function
-                Func<Task, Task<bool>> moreFunc = null;
-                moreFunc = (t) =>
-                {
-                    if (t != null)
-                    {
-                        PrepareForAsyncContinuation();
-                    }
-
-                    if (TryReadColumnHeader(i))
-                    {
-                        return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
-                    }
-                    else
-                    {
-                        return ContinueRetryable(moreFunc);
-                    }
-                };
-
-                // Go!
-                return InvokeRetryable(moreFunc, source, registration);
-            }
-        }
-
-        public override Task<T> GetFieldValueAsync<T>(int i, CancellationToken cancellationToken)
-        {
-            try
-            {
-                CheckDataIsReady(columnIndex: i);
-
-                // Shortcut - if there are no issues and the data is already read, then just return the value
-                if ((!IsCommandBehavior(CommandBehavior.SequentialAccess)) && (_sharedState._nextColumnDataToRead > i) && (!cancellationToken.IsCancellationRequested) && (_currentTask == null))
-                {
-                    var data = _data;
-                    var metaData = _metaData;
-                    if ((data != null) && (metaData != null))
-                    {
-                        return Task.FromResult<T>(GetFieldValueFromSqlBufferInternal<T>(data[i], metaData[i]));
-                    }
-                    else
-                    {
-                        // Reader was closed between the CheckDataIsReady and accessing _data\_metaData - throw closed exception
-                        return Task.FromException<T>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed()));
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                if (!ADP.IsCatchableExceptionType(ex))
-                {
-                    throw;
-                }
-                return Task.FromException<T>(ex);
-            }
-
-            // Throw if there is any current task
-            if (_currentTask != null)
-            {
-                return Task.FromException<T>(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-            }
-
-            // If user's token is canceled, return a canceled task
-            if (cancellationToken.IsCancellationRequested)
-            {
-                return Task.FromCanceled<T>(cancellationToken);
-            }
-
-            // Shortcut - if we have enough data, then run sync
-            try
-            {
-                if (WillHaveEnoughData(i))
-                {
-#if DEBUG
-                    try
-                    {
-                        _stateObj._shouldHaveEnoughData = true;
-#endif
-                        return Task.FromResult(GetFieldValueInternal<T>(i));
-#if DEBUG
-                    }
-                    finally
-                    {
-                        _stateObj._shouldHaveEnoughData = false;
-                    }
-#endif
-                }
-            }
-            catch (Exception ex)
-            {
-                if (!ADP.IsCatchableExceptionType(ex))
-                {
-                    throw;
-                }
-                return Task.FromException<T>(ex);
-            }
-
-            // Setup and check for pending task
-            TaskCompletionSource<T> source = new TaskCompletionSource<T>();
-            Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
-            if (original != null)
-            {
-                source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-                return source.Task;
-            }
-
-            // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
-            if (_cancelAsyncOnCloseToken.IsCancellationRequested)
-            {
-                source.SetCanceled();
-                _currentTask = null;
-                return source.Task;
-            }
-
-            // Setup cancellations
-            IDisposable registration = null;
-            if (cancellationToken.CanBeCanceled)
-            {
-                registration = cancellationToken.Register(s => ((SqlCommand)s).CancelIgnoreFailure(), _command);
-            }
-
-            // Setup async
-            PrepareAsyncInvocation(useSnapshot: true);
-
-            // Setup the retryable function
-            Func<Task, Task<T>> moreFunc = null;
-            moreFunc = (t) =>
-            {
-                if (t != null)
-                {
-                    PrepareForAsyncContinuation();
-                }
-
-                if (TryReadColumn(i, setTimeout: false))
-                {
-                    return Task.FromResult<T>(GetFieldValueFromSqlBufferInternal<T>(_data[i], _metaData[i]));
-                }
-                else
-                {
-                    return ContinueRetryable(moreFunc);
-                }
-            };
-
-            // Go!
-            return InvokeRetryable(moreFunc, source, registration);
-        }
-
-#if DEBUG
-
-        internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait)
-        {
-            var stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
-            }
-        }
-
-        internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait)
-        {
-            var stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
-            }
-        }
-
-#endif
-
-        private class Snapshot
-        {
-            public bool _dataReady;
-            public bool _haltRead;
-            public bool _metaDataConsumed;
-            public bool _browseModeInfoConsumed;
-            public bool _hasRows;
-            public ALTROWSTATUS _altRowStatus;
-            public int _nextColumnDataToRead;
-            public int _nextColumnHeaderToRead;
-            public long _columnDataBytesRead;
-            public long _columnDataBytesRemaining;
-
-            public _SqlMetaDataSet _metadata;
-            public _SqlMetaDataSetCollection _altMetaDataSetCollection;
-            public MultiPartTableName[] _tableNames;
-
-            public SqlSequentialStream _currentStream;
-            public SqlSequentialTextReader _currentTextReader;
-        }
-
-        private Task<T> ContinueRetryable<T>(Func<Task, Task<T>> moreFunc)
-        {
-            // _networkPacketTaskSource could be null if the connection was closed
-            // while an async invocation was outstanding.
-            TaskCompletionSource<object> completionSource = _stateObj._networkPacketTaskSource;
-            if (_cancelAsyncOnCloseToken.IsCancellationRequested || completionSource == null)
-            {
-                // Cancellation requested due to datareader being closed
-                return Task.FromException<T>(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
-            }
-            else
-            {
-                return completionSource.Task.ContinueWith((retryTask) =>
-                {
-                    if (retryTask.IsFaulted)
-                    {
-                        // Somehow the network task faulted - return the exception
-                        return Task.FromException<T>(retryTask.Exception.InnerException);
-                    }
-                    else if (!_cancelAsyncOnCloseToken.IsCancellationRequested)
-                    {
-                        TdsParserStateObject stateObj = _stateObj;
-                        if (stateObj != null)
-                        {
-                            // protect continuations against concurrent
-                            // close and cancel
-                            lock (stateObj)
-                            {
-                                if (_stateObj != null)
-                                { // reader not closed while we waited for the lock
-                                    if (retryTask.IsCanceled)
-                                    {
-                                        if (_parser != null)
-                                        {
-                                            _parser.State = TdsParserState.Broken; // We failed to respond to attention, we have to quit!
-                                            _parser.Connection.BreakConnection();
-                                            _parser.ThrowExceptionAndWarning(_stateObj);
-                                        }
-                                    }
-                                    else
-                                    {
-                                        if (!IsClosed)
-                                        {
-                                            try
-                                            {
-                                                return moreFunc(retryTask);
-                                            }
-                                            catch (Exception)
-                                            {
-                                                CleanupAfterAsyncInvocation();
-                                                throw;
-                                            }
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    }
-                    // if stateObj is null, or we closed the connection or the connection was already closed,
-                    // then mark this operation as cancelled.
-                    return Task.FromException<T>(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
-                }, TaskScheduler.Default).Unwrap();
-            }
-        }
-
-        private Task<T> InvokeRetryable<T>(Func<Task, Task<T>> moreFunc, TaskCompletionSource<T> source, IDisposable objectToDispose = null)
-        {
-            try
-            {
-                Task<T> task;
-                try
-                {
-                    task = moreFunc(null);
-                }
-                catch (Exception ex)
-                {
-                    task = Task.FromException<T>(ex);
-                }
-
-                if (task.IsCompleted)
-                {
-                    CompleteRetryable(task, source, objectToDispose);
-                }
-                else
-                {
-                    task.ContinueWith((t) => CompleteRetryable(t, source, objectToDispose), TaskScheduler.Default);
-                }
-            }
-            catch (AggregateException e)
-            {
-                source.TrySetException(e.InnerException);
-            }
-            catch (Exception e)
-            {
-                source.TrySetException(e);
-            }
-
-            // Fall through for exceptions\completing async
-            return source.Task;
-        }
-
-        private void CompleteRetryable<T>(Task<T> task, TaskCompletionSource<T> source, IDisposable objectToDispose)
-        {
-            if (objectToDispose != null)
-            {
-                objectToDispose.Dispose();
-            }
-
-            // If something has forced us to switch to SyncOverAsync mode while in an async task then we need to guarantee that we do the cleanup
-            // This avoids us replaying non-replayable data (such as DONE or ENV_CHANGE tokens)
-            var stateObj = _stateObj;
-            bool ignoreCloseToken = ((stateObj != null) && (stateObj._syncOverAsync));
-            CleanupAfterAsyncInvocation(ignoreCloseToken);
-
-            Task current = Interlocked.CompareExchange(ref _currentTask, null, source.Task);
-            Debug.Assert(current == source.Task, "Should not be able to change the _currentTask while an asynchronous operation is pending");
-
-            if (task.IsFaulted)
-            {
-                Exception e = task.Exception.InnerException;
-                source.TrySetException(e);
-            }
-            else if (task.IsCanceled)
-            {
-                source.TrySetCanceled();
-            }
-            else
-            {
-                source.TrySetResult(task.Result);
-            }
-        }
-
-        private void PrepareAsyncInvocation(bool useSnapshot)
-        {
-            // if there is already a snapshot, then the previous async command
-            // completed with exception or cancellation.  We need to continue
-            // with the old snapshot.
-            if (useSnapshot)
-            {
-                Debug.Assert(!_stateObj._asyncReadWithoutSnapshot, "Can't prepare async invocation with snapshot if doing async without snapshots");
-
-                if (_snapshot == null)
-                {
-                    _snapshot = new Snapshot
-                    {
-                        _dataReady = _sharedState._dataReady,
-                        _haltRead = _haltRead,
-                        _metaDataConsumed = _metaDataConsumed,
-                        _browseModeInfoConsumed = _browseModeInfoConsumed,
-                        _hasRows = _hasRows,
-                        _altRowStatus = _altRowStatus,
-                        _nextColumnDataToRead = _sharedState._nextColumnDataToRead,
-                        _nextColumnHeaderToRead = _sharedState._nextColumnHeaderToRead,
-                        _columnDataBytesRead = _columnDataBytesRead,
-                        _columnDataBytesRemaining = _sharedState._columnDataBytesRemaining,
-
-                        // _metadata and _altaMetaDataSetCollection must be Cloned
-                        // before they are updated
-                        _metadata = _metaData,
-                        _altMetaDataSetCollection = _altMetaDataSetCollection,
-                        _tableNames = _tableNames,
-
-                        _currentStream = _currentStream,
-                        _currentTextReader = _currentTextReader,
-                    };
-
-                    _stateObj.SetSnapshot();
-                }
-            }
-            else
-            {
-                Debug.Assert(_snapshot == null, "Can prepare async invocation without snapshot if there is currently a snapshot");
-                _stateObj._asyncReadWithoutSnapshot = true;
-            }
-
-            _stateObj._syncOverAsync = false;
-            _stateObj._executionContext = ExecutionContext.Capture();
-        }
-
-        private void CleanupAfterAsyncInvocation(bool ignoreCloseToken = false)
-        {
-            var stateObj = _stateObj;
-            if (stateObj != null)
-            {
-                // If close requested cancellation and we have a snapshot, then it will deal with cleaning up
-                // NOTE: There are some cases where we wish to ignore the close token, such as when we've read some data that is not replayable (e.g. DONE or ENV_CHANGE token)
-                if ((ignoreCloseToken) || (!_cancelAsyncOnCloseToken.IsCancellationRequested) || (stateObj._asyncReadWithoutSnapshot))
-                {
-                    // Prevent race condition between the DataReader being closed (e.g. when another MARS thread has an error)
-                    lock (stateObj)
-                    {
-                        if (_stateObj != null)
-                        { // reader not closed while we waited for the lock
-                            CleanupAfterAsyncInvocationInternal(_stateObj);
-                            Debug.Assert(_snapshot == null && !_stateObj._asyncReadWithoutSnapshot, "Snapshot not null or async without snapshot still enabled after cleaning async state");
-                        }
-                    }
-                }
-            }
-        }
-
-        // This function is called directly if calling function already closed the reader, so _stateObj is null,
-        // in other cases parameterless version should be called
-        private void CleanupAfterAsyncInvocationInternal(TdsParserStateObject stateObj, bool resetNetworkPacketTaskSource = true)
-        {
-            if (resetNetworkPacketTaskSource)
-            {
-                stateObj._networkPacketTaskSource = null;
-            }
-            stateObj.ResetSnapshot();
-            stateObj._syncOverAsync = true;
-            stateObj._executionContext = null;
-            stateObj._asyncReadWithoutSnapshot = false;
-#if DEBUG
-            stateObj._permitReplayStackTraceToDiffer = false;
-#endif
-
-            // We are setting this to null inside the if-statement because stateObj==null means that the reader hasn't been initialized or has been closed (either way _snapshot should already be null)
-            _snapshot = null;
-        }
-
-        private void PrepareForAsyncContinuation()
-        {
-            Debug.Assert(((_snapshot != null) || (_stateObj._asyncReadWithoutSnapshot)), "Can not prepare for an async continuation if no async if setup");
-            if (_snapshot != null)
-            {
-                _sharedState._dataReady = _snapshot._dataReady;
-                _haltRead = _snapshot._haltRead;
-                _metaDataConsumed = _snapshot._metaDataConsumed;
-                _browseModeInfoConsumed = _snapshot._browseModeInfoConsumed;
-                _hasRows = _snapshot._hasRows;
-                _altRowStatus = _snapshot._altRowStatus;
-                _sharedState._nextColumnDataToRead = _snapshot._nextColumnDataToRead;
-                _sharedState._nextColumnHeaderToRead = _snapshot._nextColumnHeaderToRead;
-                _columnDataBytesRead = _snapshot._columnDataBytesRead;
-                _sharedState._columnDataBytesRemaining = _snapshot._columnDataBytesRemaining;
-
-                _metaData = _snapshot._metadata;
-                _altMetaDataSetCollection = _snapshot._altMetaDataSetCollection;
-                _tableNames = _snapshot._tableNames;
-
-                _currentStream = _snapshot._currentStream;
-                _currentTextReader = _snapshot._currentTextReader;
-
-                _stateObj.PrepareReplaySnapshot();
-            }
-
-            _stateObj._executionContext = ExecutionContext.Capture();
-        }
-
-        private void SwitchToAsyncWithoutSnapshot()
-        {
-            Debug.Assert(_snapshot != null, "Should currently have a snapshot");
-            Debug.Assert(_stateObj != null && !_stateObj._asyncReadWithoutSnapshot, "Already in async without snapshot");
-
-            _snapshot = null;
-            _stateObj.ResetSnapshot();
-            _stateObj._asyncReadWithoutSnapshot = true;
-        }
-
-        public ReadOnlyCollection<DbColumn> GetColumnSchema()
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-                if (null == _metaData || null == _metaData.dbColumnSchema)
-                {
-                    if (null != this.MetaData)
-                    {
-
-                        _metaData.dbColumnSchema = BuildColumnSchema();
-                        Debug.Assert(null != _metaData.dbColumnSchema, "No schema information yet!");
-                        // filter table?
-                    }
-                }
-                if (null != _metaData)
-                {
-                    return _metaData.dbColumnSchema;
-                }
-                return s_emptySchema;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        private ReadOnlyCollection<DbColumn> BuildColumnSchema()
-        {
-            _SqlMetaDataSet md = MetaData;
-            DbColumn[] columnSchema = new DbColumn[md.Length];
-            for (int i = 0; i < md.Length; i++)
-            {
-                _SqlMetaData col = md[i];
-                SqlDbColumn dbColumn = new SqlDbColumn(md[i]);
-
-                if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType)
-                {
-                    dbColumn.SqlNumericScale = MetaType.MetaNVarChar.Scale;
-                }
-                else if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale)
-                {
-                    dbColumn.SqlNumericScale = col.scale;
-                }
-                else
-                {
-                    dbColumn.SqlNumericScale = col.metaType.Scale;
-                }
-
-                if (_browseModeInfoConsumed)
-                {
-                    dbColumn.SqlIsAliased = col.IsDifferentName;
-                    dbColumn.SqlIsKey = col.IsKey;
-                    dbColumn.SqlIsHidden = col.IsHidden;
-                    dbColumn.SqlIsExpression = col.IsExpression;
-                }
-
-                dbColumn.SqlDataType = GetFieldTypeInternal(col);
-
-                dbColumn.SqlDataTypeName = GetDataTypeNameInternal(col);
-
-                columnSchema[i] = dbColumn;
-            }
-
-            return new ReadOnlyCollection<DbColumn>(columnSchema);
-        }
-    }// SqlDataReader
-}// namespace
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDbColumn.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDbColumn.cs
deleted file mode 100644 (file)
index 9a2ded3..0000000
+++ /dev/null
@@ -1,116 +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.Data.Common;
-
-namespace System.Data.SqlClient
-{
-    internal class SqlDbColumn : DbColumn
-    {
-        private readonly _SqlMetaData _metadata;
-
-        internal SqlDbColumn(_SqlMetaData md)
-        {
-            _metadata = md;
-            Populate();
-        }
-
-        private void Populate()
-        {
-            AllowDBNull = _metadata.IsNullable;
-            BaseCatalogName = _metadata.catalogName;
-            BaseColumnName = _metadata.baseColumn;
-            BaseSchemaName = _metadata.schemaName;
-            BaseServerName = _metadata.serverName;
-            BaseTableName = _metadata.tableName;
-            ColumnName = _metadata.column;
-            ColumnOrdinal = _metadata.ordinal;
-            ColumnSize = (_metadata.metaType.IsSizeInCharacters && (_metadata.length != 0x7fffffff)) ? (_metadata.length / 2) : _metadata.length;
-            IsAutoIncrement = _metadata.IsIdentity;
-            IsIdentity = _metadata.IsIdentity;
-            IsLong = _metadata.metaType.IsLong;
-
-            if (SqlDbType.Timestamp == _metadata.type)
-            {
-                IsUnique = true;
-            }
-            else
-            {
-                IsUnique = false;
-            }
-
-            if (TdsEnums.UNKNOWN_PRECISION_SCALE != _metadata.precision)
-            {
-                NumericPrecision = _metadata.precision;
-            }
-            else
-            {
-                NumericPrecision = _metadata.metaType.Precision;
-            }
-
-            IsReadOnly = _metadata.IsReadOnly;
-
-            UdtAssemblyQualifiedName = _metadata.udt?.AssemblyQualifiedName;
-
-        }
-
-        internal bool? SqlIsAliased
-        {
-            set
-            {
-                IsAliased = value;
-            }
-        }
-
-        internal bool? SqlIsKey
-        {
-            set
-            {
-                IsKey = value;
-            }
-        }
-
-        internal bool? SqlIsHidden
-        {
-            set
-            {
-                IsHidden = value;
-            }
-        }
-
-        internal bool? SqlIsExpression
-        {
-            set
-            {
-                IsExpression = value;
-            }
-        }
-
-        internal Type SqlDataType
-        {
-            set
-            {
-                DataType = value;
-            }
-        }
-
-        internal string SqlDataTypeName
-        {
-            set
-            {
-                DataTypeName = value;
-            }
-        }
-
-        internal int? SqlNumericScale
-        {
-            set
-            {
-                NumericScale = value;
-            }
-        }
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.NetCoreApp.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.NetCoreApp.cs
deleted file mode 100644 (file)
index b3eebc9..0000000
+++ /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.Transactions;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class SqlDelegatedTransaction : IPromotableSinglePhaseNotification
-    {
-        // Get the server-side Global Transaction Id from the PromotedDTCToken
-        // Skip first 4 bytes since they contain the version
-        private Guid GetGlobalTxnIdentifierFromToken() => new Guid(new ReadOnlySpan<byte>(_connection.PromotedDTCToken, _globalTransactionsTokenVersionSizeInBytes, 16));
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.NetStandard.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.NetStandard.cs
deleted file mode 100644 (file)
index 47a226c..0000000
+++ /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.Transactions;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class SqlDelegatedTransaction : IPromotableSinglePhaseNotification
-    {
-        // Get the server-side Global Transaction Id from the PromotedDTCToken
-        // Skip first 4 bytes since they contain the version
-        private Guid GetGlobalTxnIdentifierFromToken()
-        {
-            byte[] txnGuid = new byte[16];
-            Array.Copy(_connection.PromotedDTCToken, _globalTransactionsTokenVersionSizeInBytes, // Skip the version
-                txnGuid, 0, txnGuid.Length);
-            return new Guid(txnGuid);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.cs
deleted file mode 100644 (file)
index c66aa4f..0000000
+++ /dev/null
@@ -1,449 +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.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-using System.Threading;
-using System.Transactions;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class SqlDelegatedTransaction : IPromotableSinglePhaseNotification
-    {
-        private static int _objectTypeCount;
-        private readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
-        private const int _globalTransactionsTokenVersionSizeInBytes = 4; // the size of the version in the PromotedDTCToken for Global Transactions
-        internal int ObjectID
-        {
-            get
-            {
-                return _objectID;
-            }
-        }
-
-        // WARNING!!! Multithreaded object!
-        // Locking strategy: Any potentailly-multithreaded operation must first lock the associated connection, then
-        //  validate this object's active state.  Locked activities should ONLY include Sql-transaction state altering activities
-        //  or notifications of same. Updates to the connection's association with the transaction or to the connection pool
-        //  may be initiated here AFTER the connection lock is released, but should NOT fall under this class's locking strategy.
-
-        private SqlInternalConnection _connection;            // the internal connection that is the root of the transaction
-        private readonly IsolationLevel _isolationLevel;        // the IsolationLevel of the transaction we delegated to the server
-        private SqlInternalTransaction _internalTransaction;   // the SQL Server transaction we're delegating to
-
-        private readonly Transaction _atomicTransaction;
-
-        private bool _active;                // Is the transaction active?
-
-        internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx)
-        {
-            Debug.Assert(null != connection, "null connection?");
-            _connection = connection;
-            _atomicTransaction = tx;
-            _active = false;
-            Transactions.IsolationLevel systxIsolationLevel = (Transactions.IsolationLevel)tx.IsolationLevel;
-
-            // We need to map the System.Transactions IsolationLevel to the one
-            // that System.Data uses and communicates to SqlServer.  We could
-            // arguably do that in Initialize when the transaction is delegated,
-            // however it is better to do this before we actually begin the process
-            // of delegation, in case System.Transactions adds another isolation
-            // level we don't know about -- we can throw the exception at a better
-            // place.
-            _isolationLevel = systxIsolationLevel switch
-            {
-                Transactions.IsolationLevel.ReadCommitted => IsolationLevel.ReadCommitted,
-                Transactions.IsolationLevel.ReadUncommitted => IsolationLevel.ReadUncommitted,
-                Transactions.IsolationLevel.RepeatableRead => IsolationLevel.RepeatableRead,
-                Transactions.IsolationLevel.Serializable => IsolationLevel.Serializable,
-                Transactions.IsolationLevel.Snapshot => IsolationLevel.Snapshot,
-                _ => throw SQL.UnknownSysTxIsolationLevel(systxIsolationLevel),
-            };
-        }
-
-        internal Transaction Transaction
-        {
-            get { return _atomicTransaction; }
-        }
-
-        public void Initialize()
-        {
-            // if we get here, then we know for certain that we're the delegated
-            // transaction.
-            SqlInternalConnection connection = _connection;
-            SqlConnection usersConnection = connection.Connection;
-
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try
-            {
-                if (connection.IsEnlistedInTransaction)
-                { // defect first
-                    connection.EnlistNull();
-                }
-
-                _internalTransaction = new SqlInternalTransaction(connection, TransactionType.Delegated, null);
-
-                connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true);
-
-                // Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw.
-                if (null == connection.CurrentTransaction)
-                {
-                    connection.DoomThisConnection();
-                    throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure);
-                }
-
-                _active = true;
-            }
-            catch (System.OutOfMemoryException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.StackOverflowException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.Threading.ThreadAbortException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-        }
-
-        internal bool IsActive
-        {
-            get
-            {
-                return _active;
-            }
-        }
-
-        public byte[] Promote()
-        {
-            // Operations that might be affected by multi-threaded use MUST be done inside the lock.
-            //  Don't read values off of the connection outside the lock unless it doesn't really matter
-            //  from an operational standpoint (i.e. logging connection's ObjectID should be fine,
-            //  but the PromotedDTCToken can change over calls. so that must be protected).
-            SqlInternalConnection connection = GetValidConnection();
-
-            Exception promoteException;
-            byte[] returnValue = null;
-            SqlConnection usersConnection = connection.Connection;
-
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try
-            {
-                lock (connection)
-                {
-                    try
-                    {
-                        // Now that we've acquired the lock, make sure we still have valid state for this operation.
-                        ValidateActiveOnConnection(connection);
-
-                        connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Promote, null, IsolationLevel.Unspecified, _internalTransaction, true);
-                        returnValue = _connection.PromotedDTCToken;
-
-                        // For Global Transactions, we need to set the Transaction Id since we use a Non-MSDTC Promoter type.
-                        if (_connection.IsGlobalTransaction)
-                        {
-                            if (SysTxForGlobalTransactions.SetDistributedTransactionIdentifier == null)
-                            {
-                                throw SQL.UnsupportedSysTxForGlobalTransactions();
-                            }
-
-                            if (!_connection.IsGlobalTransactionsEnabledForServer)
-                            {
-                                throw SQL.GlobalTransactionsNotEnabled();
-                            }
-
-                            SysTxForGlobalTransactions.SetDistributedTransactionIdentifier.Invoke(_atomicTransaction, new object[] { this, GetGlobalTxnIdentifierFromToken() });
-                        }
-
-                        promoteException = null;
-                    }
-                    catch (SqlException e)
-                    {
-                        promoteException = e;
-
-                        // Doom the connection, to make sure that the transaction is
-                        // eventually rolled back.
-                        // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
-                        connection.DoomThisConnection();
-                    }
-                    catch (InvalidOperationException e)
-                    {
-                        promoteException = e;
-                        connection.DoomThisConnection();
-                    }
-                }
-            }
-            catch (System.OutOfMemoryException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.StackOverflowException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.Threading.ThreadAbortException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-
-            if (promoteException != null)
-            {
-                throw SQL.PromotionFailed(promoteException);
-            }
-
-            return returnValue;
-        }
-
-        // Called by transaction to initiate abort sequence
-        public void Rollback(SinglePhaseEnlistment enlistment)
-        {
-            Debug.Assert(null != enlistment, "null enlistment?");
-
-            SqlInternalConnection connection = GetValidConnection();
-            SqlConnection usersConnection = connection.Connection;
-
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try
-            {
-                lock (connection)
-                {
-                    try
-                    {
-                        // Now that we've acquired the lock, make sure we still have valid state for this operation.
-                        ValidateActiveOnConnection(connection);
-                        _active = false; // set to inactive first, doesn't matter how the execute completes, this transaction is done.
-                        _connection = null;  // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
-
-                        // If we haven't already rolled back (or aborted) then tell the SQL Server to roll back
-                        if (!_internalTransaction.IsAborted)
-                        {
-                            connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, null, IsolationLevel.Unspecified, _internalTransaction, true);
-                        }
-                    }
-                    catch (SqlException)
-                    {
-                        // Doom the connection, to make sure that the transaction is
-                        // eventually rolled back.
-                        // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
-                        connection.DoomThisConnection();
-
-                        // Unlike SinglePhaseCommit, a rollback is a rollback, regardless
-                        // of how it happens, so SysTx won't throw an exception, and we
-                        // don't want to throw an exception either, because SysTx isn't
-                        // handling it and it may create a fail fast scenario. In the end,
-                        // there is no way for us to communicate to the consumer that this
-                        // failed for more serious reasons than usual.
-                        //
-                        // This is a bit like "should you throw if Close fails", however,
-                        // it only matters when you really need to know.  In that case,
-                        // we have the tracing that we're doing to fallback on for the
-                        // investigation.
-                    }
-                    catch (InvalidOperationException)
-                    {
-                        connection.DoomThisConnection();
-                    }
-                }
-
-                // it doesn't matter whether the rollback succeeded or not, we presume
-                // that the transaction is aborted, because it will be eventually.
-                connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
-                enlistment.Aborted();
-            }
-            catch (System.OutOfMemoryException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.StackOverflowException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.Threading.ThreadAbortException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-        }
-
-        // Called by the transaction to initiate commit sequence
-        public void SinglePhaseCommit(SinglePhaseEnlistment enlistment)
-        {
-            Debug.Assert(null != enlistment, "null enlistment?");
-
-            SqlInternalConnection connection = GetValidConnection();
-            SqlConnection usersConnection = connection.Connection;
-
-            RuntimeHelpers.PrepareConstrainedRegions();
-            try
-            {
-                // If the connection is dooomed, we can be certain that the
-                // transaction will eventually be rolled back, and we shouldn't
-                // attempt to commit it.
-                if (connection.IsConnectionDoomed)
-                {
-                    lock (connection)
-                    {
-                        _active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
-                        _connection = null;
-                    }
-
-                    enlistment.Aborted(SQL.ConnectionDoomed());
-                }
-                else
-                {
-                    Exception commitException;
-                    lock (connection)
-                    {
-                        try
-                        {
-                            // Now that we've acquired the lock, make sure we still have valid state for this operation.
-                            ValidateActiveOnConnection(connection);
-
-                            _active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
-                            _connection = null;   // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
-
-                            connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, _internalTransaction, true);
-                            commitException = null;
-                        }
-                        catch (SqlException e)
-                        {
-                            commitException = e;
-
-                            // Doom the connection, to make sure that the transaction is
-                            // eventually rolled back.
-                            // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
-                            connection.DoomThisConnection();
-                        }
-                        catch (InvalidOperationException e)
-                        {
-                            commitException = e;
-                            connection.DoomThisConnection();
-                        }
-                    }
-                    if (commitException != null)
-                    {
-                        // connection.ExecuteTransaction failed with exception
-                        if (_internalTransaction.IsCommitted)
-                        {
-                            // Even though we got an exception, the transaction
-                            // was committed by the server.
-                            enlistment.Committed();
-                        }
-                        else if (_internalTransaction.IsAborted)
-                        {
-                            // The transaction was aborted, report that to
-                            // SysTx.
-                            enlistment.Aborted(commitException);
-                        }
-                        else
-                        {
-                            // The transaction is still active, we cannot
-                            // know the state of the transaction.
-                            enlistment.InDoubt(commitException);
-                        }
-
-                        // We eat the exception.  This is called on the SysTx
-                        // thread, not the applications thread.  If we don't
-                        // eat the exception an UnhandledException will occur,
-                        // causing the process to FailFast.
-                    }
-
-                    connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
-                    if (commitException == null)
-                    {
-                        // connection.ExecuteTransaction succeeded
-                        enlistment.Committed();
-                    }
-                }
-            }
-            catch (System.OutOfMemoryException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.StackOverflowException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-            catch (System.Threading.ThreadAbortException e)
-            {
-                usersConnection.Abort(e);
-                throw;
-            }
-        }
-
-        // Event notification that transaction ended. This comes from the subscription to the Transaction's
-        //  ended event via the internal connection. If it occurs without a prior Rollback or SinglePhaseCommit call,
-        //  it indicates the transaction was ended externally (generally that one of the DTC participants aborted
-        //  the transaction).
-        internal void TransactionEnded(Transaction transaction)
-        {
-            SqlInternalConnection connection = _connection;
-
-            if (connection != null)
-            {
-                lock (connection)
-                {
-                    if (_atomicTransaction.Equals(transaction))
-                    {
-                        // No need to validate active on connection, this operation can be called on completed transactions
-                        _active = false;
-                        _connection = null;
-                    }
-                }
-            }
-        }
-
-        // Check for connection validity
-        private SqlInternalConnection GetValidConnection()
-        {
-            SqlInternalConnection connection = _connection;
-            if (null == connection)
-            {
-                throw ADP.ObjectDisposed(this);
-            }
-
-            return connection;
-        }
-
-        // Dooms connection and throws and error if not a valid, active, delegated transaction for the given
-        //  connection. Designed to be called AFTER a lock is placed on the connection, otherwise a normal return
-        //  may not be trusted.
-        private void ValidateActiveOnConnection(SqlInternalConnection connection)
-        {
-            bool valid = _active && (connection == _connection) && (connection.DelegatedTransaction == this);
-
-            if (!valid)
-            {
-                // Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance)
-                //  Doom anything remotely involved.
-                if (null != connection)
-                {
-                    connection.DoomThisConnection();
-                }
-                if (connection != _connection && null != _connection)
-                {
-                    _connection.DoomThisConnection();
-                }
-
-                throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner);  //TODO: Create a new code
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependency.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependency.cs
deleted file mode 100644 (file)
index a96496a..0000000
+++ /dev/null
@@ -1,970 +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.Generic;
-using System.Data.Common;
-using System.Data.ProviderBase;
-using System.Data.Sql;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading;
-using System.Xml;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlDependency
-    {
-        // Private class encapsulating the user/identity information - either SQL Auth username or Windows identity.
-        internal class IdentityUserNamePair
-        {
-            private readonly DbConnectionPoolIdentity _identity;
-            private readonly string _userName;
-
-            internal IdentityUserNamePair(DbConnectionPoolIdentity identity, string userName)
-            {
-                Debug.Assert((identity == null && userName != null) ||
-                              (identity != null && userName == null), "Unexpected arguments!");
-                _identity = identity;
-                _userName = userName;
-            }
-
-            internal DbConnectionPoolIdentity Identity => _identity;
-
-            internal string UserName => _userName;
-
-            public override bool Equals(object value)
-            {
-                IdentityUserNamePair temp = (IdentityUserNamePair)value;
-
-                bool result = false;
-
-                if (null == temp)
-                { // If passed value null - false.
-                    result = false;
-                }
-                else if (this == temp)
-                { // If instances equal - true.
-                    result = true;
-                }
-                else
-                {
-                    if (_identity != null)
-                    {
-                        if (_identity.Equals(temp._identity))
-                        {
-                            result = true;
-                        }
-                    }
-                    else if (_userName == temp._userName)
-                    {
-                        result = true;
-                    }
-                }
-
-                return result;
-            }
-
-            public override int GetHashCode()
-            {
-                int hashValue = 0;
-
-                if (null != _identity)
-                {
-                    hashValue = _identity.GetHashCode();
-                }
-                else
-                {
-                    hashValue = _userName.GetHashCode();
-                }
-
-                return hashValue;
-            }
-        }
-
-        // Private class encapsulating the database, service info and hash logic.
-        private class DatabaseServicePair
-        {
-            private readonly string _database;
-            private readonly string _service; // Store the value, but don't use for equality or hashcode!
-
-            internal DatabaseServicePair(string database, string service)
-            {
-                Debug.Assert(database != null, "Unexpected argument!");
-                _database = database;
-                _service = service;
-            }
-
-            internal string Database => _database;
-
-            internal string Service => _service;
-
-            public override bool Equals(object value)
-            {
-                DatabaseServicePair temp = (DatabaseServicePair)value;
-
-                bool result = false;
-
-                if (null == temp)
-                { // If passed value null - false.
-                    result = false;
-                }
-                else if (this == temp)
-                { // If instances equal - true.
-                    result = true;
-                }
-                else if (_database == temp._database)
-                {
-                    result = true;
-                }
-
-                return result;
-            }
-
-            public override int GetHashCode()
-            {
-                return _database.GetHashCode();
-            }
-        }
-
-        // Private class encapsulating the event and it's registered execution context.
-        internal class EventContextPair
-        {
-            private readonly OnChangeEventHandler _eventHandler;
-            private readonly ExecutionContext _context;
-            private readonly SqlDependency _dependency;
-            private SqlNotificationEventArgs _args;
-
-            private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeCallback);
-
-            internal EventContextPair(OnChangeEventHandler eventHandler, SqlDependency dependency)
-            {
-                Debug.Assert(eventHandler != null && dependency != null, "Unexpected arguments!");
-                _eventHandler = eventHandler;
-                _context = ExecutionContext.Capture();
-                _dependency = dependency;
-            }
-
-            public override bool Equals(object value)
-            {
-                EventContextPair temp = (EventContextPair)value;
-
-                bool result = false;
-
-                if (null == temp)
-                { // If passed value null - false.
-                    result = false;
-                }
-                else if (this == temp)
-                { // If instances equal - true.
-                    result = true;
-                }
-                else
-                {
-                    if (_eventHandler == temp._eventHandler)
-                    { // Handler for same delegates are reference equivalent.
-                        result = true;
-                    }
-                }
-
-                return result;
-            }
-
-            public override int GetHashCode()
-            {
-                return _eventHandler.GetHashCode();
-            }
-
-            internal void Invoke(SqlNotificationEventArgs args)
-            {
-                _args = args;
-                ExecutionContext.Run(_context, s_contextCallback, this);
-            }
-
-            private static void InvokeCallback(object eventContextPair)
-            {
-                EventContextPair pair = (EventContextPair)eventContextPair;
-                pair._eventHandler(pair._dependency, (SqlNotificationEventArgs)pair._args);
-            }
-        }
-
-        // Instance members
-
-        // SqlNotificationRequest required state members
-
-        // Only used for SqlDependency.Id.
-        private readonly string _id = Guid.NewGuid().ToString() + ";" + s_appDomainKey;
-        private readonly string _options; // Concat of service & db, in the form "service=x;local database=y".
-        private readonly int _timeout;
-
-        // Various SqlDependency required members
-        private bool _dependencyFired = false;
-        // We are required to implement our own event collection to preserve ExecutionContext on callback.
-        private List<EventContextPair> _eventList = new List<EventContextPair>();
-        private readonly object _eventHandlerLock = new object(); // Lock for event serialization.
-        // Track the time that this dependency should time out. If the server didn't send a change
-        // notification or a time-out before this point then the client will perform a client-side
-        // timeout.
-        private DateTime _expirationTime = DateTime.MaxValue;
-        // Used for invalidation of dependencies based on which servers they rely upon.
-        // It's possible we will over invalidate if unexpected server failure occurs (but not server down).
-        private readonly List<string> _serverList = new List<string>();
-
-        // Static members
-
-        private static readonly object s_startStopLock = new object();
-        private static readonly string s_appDomainKey = Guid.NewGuid().ToString();
-        // Hashtable containing all information to match from a server, user, database triple to the service started for that
-        // triple.  For each server, there can be N users.  For each user, there can be N databases.  For each server, user,
-        // database, there can only be one service.
-        private static readonly Dictionary<string, Dictionary<IdentityUserNamePair, List<DatabaseServicePair>>> s_serverUserHash =
-                   new Dictionary<string, Dictionary<IdentityUserNamePair, List<DatabaseServicePair>>>(StringComparer.OrdinalIgnoreCase);
-        private static SqlDependencyProcessDispatcher s_processDispatcher = null;
-
-        // Constructors
-
-        public SqlDependency() : this(null, null, SQL.SqlDependencyTimeoutDefault)
-        {
-        }
-
-        public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependencyTimeoutDefault)
-        {
-        }
-
-        public SqlDependency(SqlCommand command, string options, int timeout)
-        {
-            if (timeout < 0)
-            {
-                throw SQL.InvalidSqlDependencyTimeout(nameof(timeout));
-            }
-            _timeout = timeout;
-
-            if (null != options)
-            { // Ignore null value - will force to default.
-                _options = options;
-            }
-
-            AddCommandInternal(command);
-            SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddDependencyEntry(this); // Add dep to hashtable with Id.
-        }
-
-        // Public Properties
-
-        public bool HasChanges => _dependencyFired;
-
-        public string Id => _id;
-
-        // Internal Properties
-
-        internal static string AppDomainKey => s_appDomainKey;
-
-        internal DateTime ExpirationTime => _expirationTime;
-
-        internal string Options => _options;
-
-        internal static SqlDependencyProcessDispatcher ProcessDispatcher => s_processDispatcher;
-
-        internal int Timeout => _timeout;
-
-        // Events
-
-        public event OnChangeEventHandler OnChange
-        {
-            // EventHandlers to be fired when dependency is notified.
-            add
-            {
-                if (null != value)
-                {
-                    SqlNotificationEventArgs sqlNotificationEvent = null;
-
-                    lock (_eventHandlerLock)
-                    {
-                        if (_dependencyFired)
-                        { // If fired, fire the new event immediately.
-                            sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client);
-                        }
-                        else
-                        {
-                            EventContextPair pair = new EventContextPair(value, this);
-                            if (!_eventList.Contains(pair))
-                            {
-                                _eventList.Add(pair);
-                            }
-                            else
-                            {
-                                throw SQL.SqlDependencyEventNoDuplicate();
-                            }
-                        }
-                    }
-
-                    if (null != sqlNotificationEvent)
-                    { // Delay firing the event until outside of lock.
-                        value(this, sqlNotificationEvent);
-                    }
-                }
-            }
-            remove
-            {
-                if (null != value)
-                {
-                    EventContextPair pair = new EventContextPair(value, this);
-                    lock (_eventHandlerLock)
-                    {
-                        int index = _eventList.IndexOf(pair);
-                        if (0 <= index)
-                        {
-                            _eventList.RemoveAt(index);
-                        }
-                    }
-                }
-            }
-        }
-
-        // Public Methods
-
-        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.
-            if (command == null)
-            {
-                throw ADP.ArgumentNull(nameof(command));
-            }
-
-            AddCommandInternal(command);
-        }
-
-        // Static Methods - public & internal
-
-        // Static Start/Stop methods
-
-        public static bool Start(string connectionString)
-        {
-            return Start(connectionString, null, true);
-        }
-
-        public static bool Start(string connectionString, string queue)
-        {
-            return Start(connectionString, queue, false);
-        }
-
-        internal static bool Start(string connectionString, string queue, bool useDefaults)
-        {
-            if (string.IsNullOrEmpty(connectionString))
-            {
-                if (null == connectionString)
-                {
-                    throw ADP.ArgumentNull(nameof(connectionString));
-                }
-                else
-                {
-                    throw ADP.Argument(nameof(connectionString));
-                }
-            }
-
-            if (!useDefaults && string.IsNullOrEmpty(queue))
-            { // If specified but null or empty, use defaults.
-                useDefaults = true;
-                queue = null; // Force to null - for proper hashtable comparison for default case.
-            }
-
-            // End duplicate Start/Stop logic.
-
-            bool errorOccurred = false;
-            bool result = false;
-
-            lock (s_startStopLock)
-            {
-                try
-                {
-                    if (null == s_processDispatcher)
-                    { // Ensure _processDispatcher reference is present - inside lock.
-                        s_processDispatcher = SqlDependencyProcessDispatcher.SingletonProcessDispatcher;
-                    }
-
-                    if (useDefaults)
-                    { // Default listener.
-                        string server = null;
-                        DbConnectionPoolIdentity identity = null;
-                        string user = null;
-                        string database = null;
-                        string service = null;
-                        bool appDomainStart = false;
-
-                        RuntimeHelpers.PrepareConstrainedRegions();
-                        try
-                        { // CER to ensure that if Start succeeds we add to hash completing setup.
-                            // Start using process wide default service/queue & database from connection string.
-                            result = s_processDispatcher.StartWithDefault(
-                                connectionString,
-                                out server,
-                                out identity,
-                                out user,
-                                out database,
-                                ref service,
-                                    s_appDomainKey,
-                                    SqlDependencyPerAppDomainDispatcher.SingletonInstance,
-                                out errorOccurred,
-                                out appDomainStart);
-                        }
-                        finally
-                        {
-                            if (appDomainStart && !errorOccurred)
-                            { // If success, add to hashtable.
-                                IdentityUserNamePair identityUser = new IdentityUserNamePair(identity, user);
-                                DatabaseServicePair databaseService = new DatabaseServicePair(database, service);
-                                if (!AddToServerUserHash(server, identityUser, databaseService))
-                                {
-                                    try
-                                    {
-                                        Stop(connectionString, queue, useDefaults, true);
-                                    }
-                                    catch (Exception e)
-                                    { // Discard stop failure!
-                                        if (!ADP.IsCatchableExceptionType(e))
-                                        {
-                                            throw;
-                                        }
-
-                                        ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
-                                    }
-                                    throw SQL.SqlDependencyDuplicateStart();
-                                }
-                            }
-                        }
-                    }
-                    else
-                    { // Start with specified service/queue & database.
-                        result = s_processDispatcher.Start(
-                            connectionString,
-                            queue,
-                            s_appDomainKey,
-                            SqlDependencyPerAppDomainDispatcher.SingletonInstance);
-                        // No need to call AddToServerDatabaseHash since if not using default queue user is required
-                        // to provide options themselves.
-                    }
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableExceptionType(e))
-                    {
-                        throw;
-                    }
-
-                    ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
-
-                    throw;
-                }
-            }
-
-            return result;
-        }
-
-        public static bool Stop(string connectionString)
-        {
-            return Stop(connectionString, null, true, false);
-        }
-
-        public static bool Stop(string connectionString, string queue)
-        {
-            return Stop(connectionString, queue, false, false);
-        }
-
-        internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed)
-        {
-            if (string.IsNullOrEmpty(connectionString))
-            {
-                if (null == connectionString)
-                {
-                    throw ADP.ArgumentNull(nameof(connectionString));
-                }
-                else
-                {
-                    throw ADP.Argument(nameof(connectionString));
-                }
-            }
-
-            if (!useDefaults && string.IsNullOrEmpty(queue))
-            { // If specified but null or empty, use defaults.
-                useDefaults = true;
-                queue = null; // Force to null - for proper hashtable comparison for default case.
-            }
-
-            // End duplicate Start/Stop logic.
-
-            bool result = false;
-
-            lock (s_startStopLock)
-            {
-                if (null != s_processDispatcher)
-                { // If _processDispatcher null, no Start has been called.
-                    try
-                    {
-                        string server = null;
-                        DbConnectionPoolIdentity identity = null;
-                        string user = null;
-                        string database = null;
-                        string service = null;
-
-                        if (useDefaults)
-                        {
-                            bool appDomainStop = false;
-
-                            RuntimeHelpers.PrepareConstrainedRegions();
-                            try
-                            { // CER to ensure that if Stop succeeds we remove from hash completing teardown.
-                                // Start using process wide default service/queue & database from connection string.
-                                result = s_processDispatcher.Stop(
-                                    connectionString,
-                                    out server,
-                                    out identity,
-                                    out user,
-                                    out database,
-                                    ref service,
-                                        s_appDomainKey,
-                                    out appDomainStop);
-                            }
-                            finally
-                            {
-                                if (appDomainStop && !startFailed)
-                                { // If success, remove from hashtable.
-                                    Debug.Assert(!string.IsNullOrEmpty(server) && !string.IsNullOrEmpty(database), "Server or Database null/Empty upon successfull Stop()!");
-                                    IdentityUserNamePair identityUser = new IdentityUserNamePair(identity, user);
-                                    DatabaseServicePair databaseService = new DatabaseServicePair(database, service);
-                                    RemoveFromServerUserHash(server, identityUser, databaseService);
-                                }
-                            }
-                        }
-                        else
-                        {
-                            result = s_processDispatcher.Stop(
-                                connectionString,
-                                out server,
-                                out identity,
-                                out user,
-                                out database,
-                                ref queue,
-                                    s_appDomainKey,
-                                out bool ignored);
-                            // No need to call RemoveFromServerDatabaseHash since if not using default queue user is required
-                            // to provide options themselves.
-                        }
-                    }
-                    catch (Exception e)
-                    {
-                        if (!ADP.IsCatchableExceptionType(e))
-                        {
-                            throw;
-                        }
-
-                        ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
-                    }
-                }
-            }
-            return result;
-        }
-
-        // General static utility functions
-
-        private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService)
-        {
-            bool result = false;
-
-            lock (s_serverUserHash)
-            {
-                Dictionary<IdentityUserNamePair, List<DatabaseServicePair>> identityDatabaseHash;
-
-                if (!s_serverUserHash.ContainsKey(server))
-                {
-                    identityDatabaseHash = new Dictionary<IdentityUserNamePair, List<DatabaseServicePair>>();
-                    s_serverUserHash.Add(server, identityDatabaseHash);
-                }
-                else
-                {
-                    identityDatabaseHash = s_serverUserHash[server];
-                }
-
-                List<DatabaseServicePair> databaseServiceList;
-
-                if (!identityDatabaseHash.ContainsKey(identityUser))
-                {
-                    databaseServiceList = new List<DatabaseServicePair>();
-                    identityDatabaseHash.Add(identityUser, databaseServiceList);
-                }
-                else
-                {
-                    databaseServiceList = identityDatabaseHash[identityUser];
-                }
-
-                if (!databaseServiceList.Contains(databaseService))
-                {
-                    databaseServiceList.Add(databaseService);
-                    result = true;
-                }
-            }
-
-            return result;
-        }
-
-        private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService)
-        {
-            lock (s_serverUserHash)
-            {
-                Dictionary<IdentityUserNamePair, List<DatabaseServicePair>> identityDatabaseHash;
-
-                if (s_serverUserHash.ContainsKey(server))
-                {
-                    identityDatabaseHash = s_serverUserHash[server];
-
-                    List<DatabaseServicePair> databaseServiceList;
-
-                    if (identityDatabaseHash.ContainsKey(identityUser))
-                    {
-                        databaseServiceList = identityDatabaseHash[identityUser];
-
-                        int index = databaseServiceList.IndexOf(databaseService);
-                        if (index >= 0)
-                        {
-                            databaseServiceList.RemoveAt(index);
-
-                            if (databaseServiceList.Count == 0)
-                            {
-                                identityDatabaseHash.Remove(identityUser);
-
-                                if (identityDatabaseHash.Count == 0)
-                                {
-                                    s_serverUserHash.Remove(server);
-                                }
-                            }
-                        }
-                        else
-                        {
-                            Debug.Fail("Unexpected state - hash did not contain database!");
-                        }
-                    }
-                    else
-                    {
-                        Debug.Fail("Unexpected state - hash did not contain user!");
-                    }
-                }
-                else
-                {
-                    Debug.Fail("Unexpected state - hash did not contain server!");
-                }
-            }
-        }
-
-        internal static string GetDefaultComposedOptions(string server, string failoverServer, IdentityUserNamePair identityUser, string database)
-        {
-            // 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.
-            string result;
-
-            lock (s_serverUserHash)
-            {
-                if (!s_serverUserHash.ContainsKey(server))
-                {
-                    if (0 == s_serverUserHash.Count)
-                    { // Special error for no calls to start.
-                        throw SQL.SqlDepDefaultOptionsButNoStart();
-                    }
-                    else if (!string.IsNullOrEmpty(failoverServer) && s_serverUserHash.ContainsKey(failoverServer))
-                    {
-                        server = failoverServer;
-                    }
-                    else
-                    {
-                        throw SQL.SqlDependencyNoMatchingServerStart();
-                    }
-                }
-
-                Dictionary<IdentityUserNamePair, List<DatabaseServicePair>> identityDatabaseHash = s_serverUserHash[server];
-
-                List<DatabaseServicePair> databaseList = null;
-
-                if (!identityDatabaseHash.ContainsKey(identityUser))
-                {
-                    if (identityDatabaseHash.Count > 1)
-                    {
-                        throw SQL.SqlDependencyNoMatchingServerStart();
-                    }
-                    else
-                    {
-                        // Since only one user, - use that.
-                        // Foreach - but only one value present.
-                        foreach (KeyValuePair<IdentityUserNamePair, List<DatabaseServicePair>> entry in identityDatabaseHash)
-                        {
-                            databaseList = entry.Value;
-                            break; // Only iterate once.
-                        }
-                    }
-                }
-                else
-                {
-                    databaseList = identityDatabaseHash[identityUser];
-                }
-
-                DatabaseServicePair pair = new DatabaseServicePair(database, null);
-                DatabaseServicePair resultingPair = null;
-                int index = databaseList.IndexOf(pair);
-                if (index != -1)
-                { // Exact match found, use it.
-                    resultingPair = databaseList[index];
-                }
-
-                if (null != resultingPair)
-                { // Exact database match.
-                    database = FixupServiceOrDatabaseName(resultingPair.Database); // Fixup in place.
-                    string quotedService = FixupServiceOrDatabaseName(resultingPair.Service);
-                    result = "Service=" + quotedService + ";Local Database=" + database;
-                }
-                else
-                { // No exact database match found.
-                    if (databaseList.Count == 1)
-                    { // If only one database for this server/user, use it.
-                        object[] temp = databaseList.ToArray(); // Must copy, no other choice but foreach.
-                        resultingPair = (DatabaseServicePair)temp[0];
-                        Debug.Assert(temp.Length == 1, "If databaseList.Count==1, why does copied array have length other than 1?");
-                        string quotedDatabase = FixupServiceOrDatabaseName(resultingPair.Database);
-                        string quotedService = FixupServiceOrDatabaseName(resultingPair.Service);
-                        result = "Service=" + quotedService + ";Local Database=" + quotedDatabase;
-                    }
-                    else
-                    { // More than one database for given server, ambiguous - fail the default case!
-                        throw SQL.SqlDependencyNoMatchingServerDatabaseStart();
-                    }
-                }
-            }
-
-            Debug.Assert(!string.IsNullOrEmpty(result), "GetDefaultComposedOptions should never return null or empty string!");
-            return result;
-        }
-
-        // Internal Methods
-
-        // Called by SqlCommand upon execution of a SqlNotificationRequest class created by this dependency.  We
-        // use this list for a reverse lookup based on server.
-        internal void AddToServerList(string server)
-        {
-            lock (_serverList)
-            {
-                int index = _serverList.BinarySearch(server, StringComparer.OrdinalIgnoreCase);
-                if (0 > index)
-                { // If less than 0, item was not found in list.
-                    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);
-
-                }
-            }
-        }
-
-        internal bool ContainsServer(string server)
-        {
-            lock (_serverList)
-            {
-                return _serverList.Contains(server);
-            }
-        }
-
-        internal string ComputeHashAndAddToDispatcher(SqlCommand command)
-        {
-            // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values.
-            // This string will then be mapped to unique notification ID (new GUID).  We add the guid and the hash to the app domain
-            // dispatcher to be able to map back to the dependency that needs to be fired for a notification of this
-            // command.
-
-            // Add Connection string to prevent redundant notifications when same command is running against different databases or SQL servers
-            string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command
-
-            string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map.
-            return idString;
-        }
-
-        internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source)
-        {
-            List<EventContextPair> eventList = null;
-
-            lock (_eventHandlerLock)
-            {
-                if (_dependencyFired &&
-                    SqlNotificationInfo.AlreadyChanged != info &&
-                    SqlNotificationSource.Client != source)
-                {
-
-                    if (ExpirationTime >= DateTime.UtcNow)
-                    {
-                        Debug.Fail("Received notification twice - we should never enter this state!");
-                    }
-                }
-                else
-                {
-                    // It is the invalidators responsibility to remove this dependency from the app domain static hash.
-                    _dependencyFired = true;
-                    eventList = _eventList;
-                    _eventList = new List<EventContextPair>(); // Since we are firing the events, null so we do not fire again.
-                }
-            }
-
-            if (eventList != null)
-            {
-                foreach (EventContextPair pair in eventList)
-                {
-                    pair.Invoke(new SqlNotificationEventArgs(type, info, source));
-                }
-            }
-        }
-
-        // This method is used by SqlCommand.
-        internal void StartTimer(SqlNotificationRequest notificationRequest)
-        {
-            if (_expirationTime == DateTime.MaxValue)
-            {
-                int seconds = SQL.SqlDependencyServerTimeout;
-                if (0 != _timeout)
-                {
-                    seconds = _timeout;
-                }
-                if (notificationRequest != null && notificationRequest.Timeout < seconds && notificationRequest.Timeout != 0)
-                {
-                    seconds = notificationRequest.Timeout;
-                }
-
-                // We use UTC to check if SqlDependency is expired, need to use it here as well.
-                _expirationTime = DateTime.UtcNow.AddSeconds(seconds);
-                SqlDependencyPerAppDomainDispatcher.SingletonInstance.StartTimer(this);
-            }
-        }
-
-        // Private Methods
-
-        private void AddCommandInternal(SqlCommand cmd)
-        {
-            if (cmd != null)
-            {
-                if (cmd.Notification != null)
-                {
-                    // Fail if cmd has notification that is not already associated with this dependency.
-                    if (cmd._sqlDep == null || cmd._sqlDep != this)
-                    {
-                        throw SQL.SqlCommandHasExistingSqlNotificationRequest();
-                    }
-                }
-                else
-                {
-                    bool needToInvalidate = false;
-
-                    lock (_eventHandlerLock)
-                    {
-                        if (!_dependencyFired)
-                        {
-                            cmd.Notification = new SqlNotificationRequest()
-                            {
-                                Timeout = _timeout
-                            };
-
-                            // Add the command - A dependancy should always map to a set of commands which haven't fired.
-                            if (null != _options)
-                            { // Assign options if user provided.
-                                cmd.Notification.Options = _options;
-                            }
-
-                            cmd._sqlDep = this;
-                        }
-                        else
-                        {
-                            // We should never be able to enter this state, since if we've fired our event list is cleared
-                            // and the event method will immediately fire if a new event is added.  So, we should never have
-                            // an event to fire in the event list once we've fired.
-                            Debug.Assert(0 == _eventList.Count, "How can we have an event at this point?");
-                            if (0 == _eventList.Count)
-                            { // Keep logic just in case.
-                                needToInvalidate = true; // Delay invalidation until outside of lock.
-                            }
-                        }
-                    }
-
-                    if (needToInvalidate)
-                    {
-                        Invalidate(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client);
-                    }
-                }
-            }
-        }
-
-        private string ComputeCommandHash(string connectionString, SqlCommand command)
-        {
-            // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values.
-            // This string will then be mapped to the notification ID.
-
-            // All types should properly support a .ToString for the values except
-            // byte[], char[], and XmlReader.
-
-            StringBuilder builder = new StringBuilder();
-
-            // add the Connection string and the Command text
-            builder.AppendFormat("{0};{1}", connectionString, command.CommandText);
-
-            // append params
-            for (int i = 0; i < command.Parameters.Count; i++)
-            {
-                object value = command.Parameters[i].Value;
-
-                if (value == null || value == DBNull.Value)
-                {
-                    builder.Append("; NULL");
-                }
-                else
-                {
-                    Type type = value.GetType();
-
-                    if (type == typeof(byte[]))
-                    {
-                        builder.Append(";");
-                        byte[] temp = (byte[])value;
-                        for (int j = 0; j < temp.Length; j++)
-                        {
-                            builder.Append(temp[j].ToString("x2", CultureInfo.InvariantCulture));
-                        }
-                    }
-                    else if (type == typeof(char[]))
-                    {
-                        builder.Append((char[])value);
-                    }
-                    else if (type == typeof(XmlReader))
-                    {
-                        builder.Append(";");
-                        // Cannot .ToString XmlReader - just allocate GUID.
-                        // This means if XmlReader is used, we will not reuse IDs.
-                        builder.Append(Guid.NewGuid().ToString());
-                    }
-                    else
-                    {
-                        builder.Append(";");
-                        builder.Append(value.ToString());
-                    }
-                }
-            }
-
-            string result = builder.ToString();
-
-            return result;
-        }
-
-        // Basic copy of function in SqlConnection.cs for ChangeDatabase and similar functionality.  Since this will
-        // only be used for default service and database provided by server, we do not need to worry about an already
-        // quoted value.
-        internal static string FixupServiceOrDatabaseName(string name)
-        {
-            if (!string.IsNullOrEmpty(name))
-            {
-                return "\"" + name.Replace("\"", "\"\"") + "\"";
-            }
-            else
-            {
-                return name;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyListener.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyListener.cs
deleted file mode 100644 (file)
index c75b88e..0000000
+++ /dev/null
@@ -1,1468 +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.Data;
-using System.Data.Common;
-using System.Data.ProviderBase;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Runtime.Versioning;
-using System.Threading;
-using System.Xml;
-
-// This class is the process wide dependency dispatcher.  It contains all connection listeners for the entire process and
-// receives notifications on those connections to dispatch to the corresponding AppDomain dispatcher to notify the
-// appropriate dependencies.
-
-internal class SqlDependencyProcessDispatcher : MarshalByRefObject
-{
-    // Class to contain/store all relevant information about a connection that waits on the SSB queue.
-    private class SqlConnectionContainer
-    {
-        private readonly SqlConnection _con;
-        private readonly SqlCommand _com;
-        private readonly SqlParameter _conversationGuidParam;
-        private readonly SqlParameter _timeoutParam;
-        private readonly SqlConnectionContainerHashHelper _hashHelper;
-        private readonly string _queue;
-        private readonly string _receiveQuery;
-        private string _beginConversationQuery;
-        private string _endConversationQuery;
-        private string _concatQuery;
-        private readonly int _defaultWaitforTimeout = 60000; // Waitfor(Receive) timeout (milleseconds)
-        private readonly string _escapedQueueName;
-        private readonly string _sprocName;
-        private string _dialogHandle;
-        private readonly string _cachedServer;
-        private string _cachedDatabase;
-        private volatile bool _errorState = false;
-        private volatile bool _stop = false; // Can probably simplify this slightly - one bool instead of two.
-        private volatile bool _stopped = false;
-        private volatile bool _serviceQueueCreated = false;
-        private int _startCount = 0;     // Each container class is called once per Start() - we refCount
-                                         // to track when we can dispose.
-        private Timer _retryTimer = null;
-        private readonly Dictionary<string, int> _appDomainKeyHash = null;  // AppDomainKey->Open RefCount
-
-        // Constructor
-
-        internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults)
-        {
-            bool setupCompleted = false;
-            try
-            {
-                _hashHelper = hashHelper;
-                string guid = null;
-
-                // If default, queue name is not present on hashHelper at this point - so we need to
-                // generate one and complete initialization.
-                if (useDefaults)
-                {
-                    guid = Guid.NewGuid().ToString();
-                    _queue = SQL.SqlNotificationServiceDefault + "-" + guid;
-                    _hashHelper.ConnectionStringBuilder.ApplicationName = _queue; // Used by cleanup sproc.
-                }
-                else
-                {
-                    _queue = _hashHelper.Queue;
-                }
-
-                // Always use ConnectionStringBuilder since in default case it is different from the
-                // connection string used in the hashHelper.
-                _con = new SqlConnection(_hashHelper.ConnectionStringBuilder.ConnectionString); // Create connection and open.
-                _con.Open();
-
-                _cachedServer = _con.DataSource;
-
-                _escapedQueueName = SqlConnection.FixupDatabaseTransactionName(_queue); // Properly escape to prevent SQL Injection.
-                _appDomainKeyHash = new Dictionary<string, int>(); // Dictionary stores the Start/Stop refcount per AppDomain for this container.
-                _com = new SqlCommand()
-                {
-                    Connection = _con,
-                    // Determine if broker is enabled on current database.
-                    CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()"
-                };
-
-                if (!(bool)_com.ExecuteScalar())
-                {
-                    throw SQL.SqlDependencyDatabaseBrokerDisabled();
-                }
-
-                _conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier);
-                _timeoutParam = new SqlParameter("@p2", SqlDbType.Int)
-                {
-                    Value = 0 // Timeout set to 0 for initial sync query.
-                };
-                _com.Parameters.Add(_timeoutParam);
-
-                setupCompleted = true;
-                // connection with the server has been setup - from this point use TearDownAndDispose() in case of error
-
-                // Create standard query.
-                _receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + _escapedQueueName + "), TIMEOUT @p2;";
-
-                // Create queue, service, sync query, and async query on user thread to ensure proper
-                // init prior to return.
-
-                if (useDefaults)
-                { // Only create if user did not specify service & database.
-                    _sprocName = SqlConnection.FixupDatabaseTransactionName(SQL.SqlNotificationStoredProcedureDefault + "-" + guid);
-                    CreateQueueAndService(false); // Fail if we cannot create service, queue, etc.
-                }
-                else
-                {
-                    // Continue query setup.
-                    _com.CommandText = _receiveQuery;
-                    _endConversationQuery = "END CONVERSATION @p1; ";
-                    _concatQuery = _endConversationQuery + _receiveQuery;
-                }
-
-                IncrementStartCount(appDomainKey, out bool ignored);
-                // Query synchronously once to ensure everything is working correctly.
-                // We want the exception to occur on start to immediately inform caller.
-                SynchronouslyQueryServiceBrokerQueue();
-                _timeoutParam.Value = _defaultWaitforTimeout; // Sync successful, extend timeout to 60 seconds.
-                AsynchronouslyQueryServiceBrokerQueue();
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-
-                ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
-                if (setupCompleted)
-                {
-                    // Be sure to drop service & queue.  This may fail if create service & queue failed.
-                    // This method will not drop unless we created or service & queue ref-count is 0.
-                    TearDownAndDispose();
-                }
-                else
-                {
-                    // connection has not been fully setup yet - cannot use TearDownAndDispose();
-                    // we have to dispose the command and the connection to avoid connection leaks (until GC collects them).
-                    if (_com != null)
-                    {
-                        _com.Dispose();
-                        _com = null;
-                    }
-                    if (_con != null)
-                    {
-                        _con.Dispose();
-                        _con = null;
-                    }
-
-                }
-                throw;
-            }
-        }
-
-        // Properties
-
-        internal string Database
-        {
-            get
-            {
-                if (_cachedDatabase == null)
-                {
-                    _cachedDatabase = _con.Database;
-                }
-                return _cachedDatabase;
-            }
-        }
-
-        internal SqlConnectionContainerHashHelper HashHelper => _hashHelper;
-
-        internal bool InErrorState => _errorState;
-
-        internal string Queue => _queue;
-
-        internal string Server => _cachedServer;
-
-        // Methods
-
-        // This function is called by a ThreadPool thread as a result of an AppDomain calling
-        // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload.
-        internal bool AppDomainUnload(string appDomainKey)
-        {
-            Debug.Assert(!string.IsNullOrEmpty(appDomainKey), "Unexpected empty appDomainKey!");
-
-            // Dictionary used to track how many times start has been called per app domain.
-            // For each decrement, subtract from count, and delete if we reach 0.
-            lock (_appDomainKeyHash)
-            {
-                if (_appDomainKeyHash.ContainsKey(appDomainKey))
-                { // Do nothing if AppDomain did not call Start!
-                    int value = _appDomainKeyHash[appDomainKey];
-                    Debug.Assert(value > 0, "Why is value 0 or less?");
-
-                    bool ignored = false;
-                    while (value > 0)
-                    {
-                        Debug.Assert(!_stopped, "We should not yet be stopped!");
-                        Stop(appDomainKey, out ignored); // Stop will decrement value and remove if necessary from _appDomainKeyHash.
-                        value--;
-                    }
-
-                    // Stop will remove key when decremented to 0 for this AppDomain, which should now be the case.
-                    Debug.Assert(0 == value, "We did not reach 0 at end of loop in AppDomainUnload!");
-                    Debug.Assert(!_appDomainKeyHash.ContainsKey(appDomainKey), "Key not removed after AppDomainUnload!");
-                }
-            }
-
-            return _stopped;
-        }
-
-        private void AsynchronouslyQueryServiceBrokerQueue()
-        {
-            AsyncCallback callback = new AsyncCallback(AsyncResultCallback);
-            _com.BeginExecuteReader(callback, null, CommandBehavior.Default); // NO LOCK NEEDED
-        }
-
-        private void AsyncResultCallback(IAsyncResult asyncResult)
-        {
-            try
-            {
-                using (SqlDataReader reader = _com.EndExecuteReader(asyncResult))
-                {
-                    ProcessNotificationResults(reader);
-                }
-
-                // Successful completion of query - no errors.
-                if (!_stop)
-                {
-                    AsynchronouslyQueryServiceBrokerQueue(); // Requeue...
-                }
-                else
-                {
-                    TearDownAndDispose();
-                }
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    // Let the waiting thread detect the error and exit (otherwise, the Stop call loops forever)
-                    _errorState = true;
-                    throw;
-                }
-
-                if (!_stop)
-                { // Only assert if not in cancel path.
-                    ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
-                }
-
-                // Failure - likely due to cancelled command.  Check _stop state.
-                if (_stop)
-                {
-                    TearDownAndDispose();
-                }
-                else
-                {
-                    _errorState = true;
-                    Restart(null); // Error code path.  Will Invalidate based on server if 1st retry fails.
-                }
-            }
-        }
-
-        private void CreateQueueAndService(bool restart)
-        {
-            SqlCommand com = new SqlCommand()
-            {
-                Connection = _con
-            };
-            SqlTransaction trans = null;
-
-            try
-            {
-                trans = _con.BeginTransaction(); // Since we cannot batch proc creation, start transaction.
-                com.Transaction = trans;
-
-                string nameLiteral = SqlServerEscapeHelper.MakeStringLiteral(_queue);
-
-                com.CommandText =
-                        "CREATE PROCEDURE " + _sprocName + " AS"
-                        + " BEGIN"
-                            + " BEGIN TRANSACTION;"
-                            + " RECEIVE TOP(0) conversation_handle FROM " + _escapedQueueName + ";"
-                            + " IF (SELECT COUNT(*) FROM " + _escapedQueueName + " WHERE message_type_name = 'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer') > 0"
-                            + " BEGIN"
-                                + " if ((SELECT COUNT(*) FROM sys.services WHERE name = " + nameLiteral + ") > 0)"
-                                + "   DROP SERVICE " + _escapedQueueName + ";"
-                                + " if (OBJECT_ID(" + nameLiteral + ", 'SQ') IS NOT NULL)"
-                                + "   DROP QUEUE " + _escapedQueueName + ";"
-                                + " DROP PROCEDURE " + _sprocName + ";" // Don't need conditional because this is self
-                            + " END"
-                            + " COMMIT TRANSACTION;"
-                        + " END";
-
-                if (!restart)
-                {
-                    com.ExecuteNonQuery();
-                }
-                else
-                { // Upon restart, be resilient to the user dropping queue, service, or procedure.
-                    try
-                    {
-                        com.ExecuteNonQuery(); // Cannot add 'IF OBJECT_ID' to create procedure query - wrap and discard failure.
-                    }
-                    catch (Exception e)
-                    {
-                        if (!ADP.IsCatchableExceptionType(e))
-                        {
-                            throw;
-                        }
-                        ADP.TraceExceptionWithoutRethrow(e);
-
-                        try
-                        { // Since the failure will result in a rollback, rollback our object.
-                            if (null != trans)
-                            {
-                                trans.Rollback();
-                                trans = null;
-                            }
-                        }
-                        catch (Exception f)
-                        {
-                            if (!ADP.IsCatchableExceptionType(f))
-                            {
-                                throw;
-                            }
-                            ADP.TraceExceptionWithoutRethrow(f); // Discard failure, but trace for now.
-                        }
-                    }
-
-                    if (null == trans)
-                    { // Create a new transaction for next operations.
-                        trans = _con.BeginTransaction();
-                        com.Transaction = trans;
-                    }
-                }
-
-
-                com.CommandText =
-                         "IF OBJECT_ID(" + nameLiteral + ", 'SQ') IS NULL"
-                            + " BEGIN"
-                            + " CREATE QUEUE " + _escapedQueueName + " WITH ACTIVATION (PROCEDURE_NAME=" + _sprocName + ", MAX_QUEUE_READERS=1, EXECUTE AS OWNER);"
-                            + " END;"
-                      + " IF (SELECT COUNT(*) FROM sys.services WHERE NAME=" + nameLiteral + ") = 0"
-                            + " BEGIN"
-                            + " CREATE SERVICE " + _escapedQueueName + " ON QUEUE " + _escapedQueueName + " ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);"
-                         + " IF (SELECT COUNT(*) FROM sys.database_principals WHERE name='sql_dependency_subscriber' AND type='R') <> 0"
-                              + " BEGIN"
-                              + " GRANT SEND ON SERVICE::" + _escapedQueueName + " TO sql_dependency_subscriber;"
-                              + " END; "
-                            + " END;"
-                      + " BEGIN DIALOG @dialog_handle FROM SERVICE " + _escapedQueueName + " TO SERVICE " + nameLiteral;
-
-                SqlParameter param = new SqlParameter()
-                {
-                    ParameterName = "@dialog_handle",
-                    DbType = DbType.Guid,
-                    Direction = ParameterDirection.Output
-                };
-                com.Parameters.Add(param);
-                com.ExecuteNonQuery();
-
-                // Finish setting up queries and state.  For re-start, we need to ensure we begin a new dialog above and reset
-                // our queries to use the new dialogHandle.
-                _dialogHandle = ((Guid)param.Value).ToString();
-                _beginConversationQuery = "BEGIN CONVERSATION TIMER ('" + _dialogHandle + "') TIMEOUT = 120; " + _receiveQuery;
-                _com.CommandText = _beginConversationQuery;
-                _endConversationQuery = "END CONVERSATION @p1; ";
-                _concatQuery = _endConversationQuery + _com.CommandText;
-
-                trans.Commit();
-                trans = null;
-                _serviceQueueCreated = true;
-            }
-            finally
-            {
-                if (null != trans)
-                {
-                    try
-                    {
-                        trans.Rollback();
-                        trans = null;
-                    }
-                    catch (Exception e)
-                    {
-                        if (!ADP.IsCatchableExceptionType(e))
-                        {
-                            throw;
-                        }
-                        ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
-                    }
-                }
-            }
-        }
-
-        internal void IncrementStartCount(string appDomainKey, out bool appDomainStart)
-        {
-            appDomainStart = false; // Reset out param.
-            Interlocked.Increment(ref _startCount); // Add to refCount.
-
-            // 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.
-            lock (_appDomainKeyHash)
-            {
-                if (_appDomainKeyHash.ContainsKey(appDomainKey))
-                {
-                    _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1;
-                }
-                else
-                {
-                    _appDomainKeyHash[appDomainKey] = 1;
-                    appDomainStart = true;
-                }
-            }
-        }
-
-        private void ProcessNotificationResults(SqlDataReader reader)
-        {
-            Guid handle = Guid.Empty; // Conversation_handle.  Always close this!
-            try
-            {
-                if (!_stop)
-                {
-                    while (reader.Read())
-                    {
-                        string msgType = reader.GetString(0);
-                        handle = reader.GetGuid(1);
-
-                        // Only process QueryNotification messages.
-                        if (string.Equals(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase))
-                        {
-                            SqlXml payload = reader.GetSqlXml(2);
-                            if (null != payload)
-                            {
-                                SqlNotification notification = SqlNotificationParser.ProcessMessage(payload);
-                                if (null != notification)
-                                {
-                                    string key = notification.Key;
-                                    int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash"
-
-                                    if (index >= 0)
-                                    { // Ensure ';' present.
-                                        string appDomainKey = key.Substring(0, index);
-                                        SqlDependencyPerAppDomainDispatcher dispatcher;
-                                        lock (s_staticInstance._sqlDependencyPerAppDomainDispatchers)
-                                        {
-                                            dispatcher = s_staticInstance._sqlDependencyPerAppDomainDispatchers[appDomainKey];
-                                        }
-                                        if (null != dispatcher)
-                                        {
-                                            try
-                                            {
-                                                dispatcher.InvalidateCommandID(notification); // CROSS APP-DOMAIN CALL!
-                                            }
-                                            catch (Exception e)
-                                            {
-                                                if (!ADP.IsCatchableExceptionType(e))
-                                                {
-                                                    throw;
-                                                }
-                                                ADP.TraceExceptionWithoutRethrow(e); // Discard failure.  User event could throw exception.
-                                            }
-                                        }
-                                        else
-                                        {
-                                            Debug.Fail("Received notification but do not have an associated PerAppDomainDispatcher!");
-                                        }
-                                    }
-                                    else
-                                    {
-                                        Debug.Fail("Unexpected ID format received!");
-                                    }
-                                }
-                                else
-                                {
-                                    Debug.Fail("Null notification returned from ProcessMessage!");
-                                }
-                            }
-                            else
-                            {
-                                Debug.Fail("Null payload for QN notification type!");
-                            }
-                        }
-                        else
-                        {
-                            handle = Guid.Empty;
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                // Since we do not want to make a separate round trip just for the end conversation call, we need to
-                // batch it with the next command.
-                if (handle == Guid.Empty)
-                { // This should only happen if failure occurred, or if non-QN format received.
-                    _com.CommandText = _beginConversationQuery ?? _receiveQuery; // If we're doing the initial query, we won't have a conversation Guid to begin yet.
-                    if (_com.Parameters.Count > 1)
-                    { // Remove conversation param since next execute is only query.
-                        _com.Parameters.Remove(_conversationGuidParam);
-                    }
-                    Debug.Assert(_com.Parameters.Count == 1, "Unexpected number of parameters!");
-                }
-                else
-                {
-                    _com.CommandText = _concatQuery; // END query + WAITFOR RECEIVE query.
-                    _conversationGuidParam.Value = handle; // Set value for conversation handle.
-                    if (_com.Parameters.Count == 1)
-                    { // Add parameter if previous execute was only query.
-                        _com.Parameters.Add(_conversationGuidParam);
-                    }
-                    Debug.Assert(_com.Parameters.Count == 2, "Unexpected number of parameters!");
-                }
-            }
-        }
-
-        private void Restart(object unused)
-        { // Unused arg required by TimerCallback.
-            try
-            {
-                lock (this)
-                {
-                    if (!_stop)
-                    { // Only execute if we are still in running state.
-                        try
-                        {
-                            _con.Close();
-                        }
-                        catch (Exception e)
-                        {
-                            if (!ADP.IsCatchableExceptionType(e))
-                            {
-                                throw;
-                            }
-                            ADP.TraceExceptionWithoutRethrow(e); // Discard close failure, if it occurs.  Only trace it.
-                        }
-                    }
-                }
-
-                // Rather than one long lock - take lock 3 times for shorter periods.
-
-                lock (this)
-                {
-                    if (!_stop)
-                    {
-                        _con.Open();
-                    }
-                }
-
-                lock (this)
-                {
-                    if (!_stop)
-                    {
-                        if (_serviceQueueCreated)
-                        {
-                            bool failure = false;
-
-                            try
-                            {
-                                CreateQueueAndService(true); // Ensure service, queue, etc is present, if we created it.
-                            }
-                            catch (Exception e)
-                            {
-                                if (!ADP.IsCatchableExceptionType(e))
-                                {
-                                    throw;
-                                }
-                                ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
-                                failure = true;
-                            }
-
-                            if (failure)
-                            {
-                                // If we failed to re-created queue, service, sproc - invalidate!
-                                s_staticInstance.Invalidate(Server,
-                                                           new SqlNotification(SqlNotificationInfo.Error,
-                                                                               SqlNotificationSource.Client,
-                                                                               SqlNotificationType.Change,
-                                                                               null));
-
-                            }
-                        }
-                    }
-                }
-
-                lock (this)
-                {
-                    if (!_stop)
-                    {
-                        _timeoutParam.Value = 0; // Reset timeout to zero - we do not want to block.
-                        SynchronouslyQueryServiceBrokerQueue();
-                        // If the above succeeds, we are back in success case - requeue for async call.
-                        _timeoutParam.Value = _defaultWaitforTimeout; // If success, reset to default for re-queue.
-                        AsynchronouslyQueryServiceBrokerQueue();
-                        _errorState = false;
-                        Timer retryTimer = _retryTimer;
-                        if (retryTimer != null)
-                        {
-                            _retryTimer = null;
-                            retryTimer.Dispose();
-                        }
-                    }
-                }
-
-                if (_stop)
-                {
-                    TearDownAndDispose(); // Function will lock(this).
-                }
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-                ADP.TraceExceptionWithoutRethrow(e);
-
-                try
-                {
-                    // If unexpected query or connection failure, invalidate all dependencies against this server.
-                    // We may over-notify if only some of the connections to a particular database were affected,
-                    // but this should not be frequent enough to be a concern.
-                    // NOTE - we invalidate after failure first occurs and then retry fails.  We will then continue
-                    // to invalidate every time the retry fails.
-                    s_staticInstance.Invalidate(Server,
-                                               new SqlNotification(SqlNotificationInfo.Error,
-                                                                   SqlNotificationSource.Client,
-                                                                   SqlNotificationType.Change,
-                                                                   null));
-                }
-                catch (Exception f)
-                {
-                    if (!ADP.IsCatchableExceptionType(f))
-                    {
-                        throw;
-                    }
-                    ADP.TraceExceptionWithoutRethrow(f); // Discard exception from Invalidate.  User events can throw.
-                }
-
-                try
-                {
-                    _con.Close();
-                }
-                catch (Exception f)
-                {
-                    if (!ADP.IsCatchableExceptionType(f))
-                    {
-                        throw;
-                    }
-                    ADP.TraceExceptionWithoutRethrow(f); // Discard close failure, if it occurs.  Only trace it.
-                }
-
-                if (!_stop)
-                {
-                    // Create a timer to callback in one minute, retrying the call to Restart().
-                    _retryTimer = new Timer(new TimerCallback(Restart), null, _defaultWaitforTimeout, Timeout.Infinite);
-                    // We will retry this indefinitely, until success - or Stop();
-                }
-            }
-        }
-
-        internal bool Stop(string appDomainKey, out bool appDomainStop)
-        {
-            appDomainStop = false;
-
-            // Dictionary used to track how many times start has been called per app domain.
-            // For each decrement, subtract from count, and delete if we reach 0.
-
-            if (null != appDomainKey)
-            {
-                // If null, then this was called from SqlDependencyProcessDispatcher, we ignore appDomainKeyHash.
-                lock (_appDomainKeyHash)
-                {
-                    if (_appDomainKeyHash.ContainsKey(appDomainKey))
-                    { // Do nothing if AppDomain did not call Start!
-                        int value = _appDomainKeyHash[appDomainKey];
-
-                        Debug.Assert(value > 0, "Unexpected count for appDomainKey");
-
-                        if (value > 0)
-                        {
-                            _appDomainKeyHash[appDomainKey] = value - 1;
-                        }
-                        else
-                        {
-                            Debug.Fail("Unexpected AppDomainKey count in Stop()");
-                        }
-
-                        if (1 == value)
-                        { // Remove from dictionary if pre-decrement count was one.
-                            _appDomainKeyHash.Remove(appDomainKey);
-                            appDomainStop = true;
-                        }
-                    }
-                    else
-                    {
-                        Debug.Fail("Unexpected state on Stop() - no AppDomainKey entry in hashtable!");
-                    }
-                }
-            }
-
-            Debug.Assert(_startCount > 0, "About to decrement _startCount less than 0!");
-            int result = Interlocked.Decrement(ref _startCount);
-
-            if (0 == result)
-            { // If we've reached refCount 0, destroy.
-                // Lock to ensure Cancel() complete prior to other thread calling TearDown.
-                lock (this)
-                {
-                    try
-                    {
-                        // Race condition with executing thread - will throw if connection is closed due to failure.
-                        // Rather than fighting the race condition, just call it and discard any potential failure.
-                        _com.Cancel(); // Cancel the pending command.  No-op if connection closed.
-                    }
-                    catch (Exception e)
-                    {
-                        if (!ADP.IsCatchableExceptionType(e))
-                        {
-                            throw;
-                        }
-                        ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
-                    }
-                    _stop = true;
-                }
-
-                // Wait until stopped and service & queue are dropped.
-                Stopwatch retryStopwatch = Stopwatch.StartNew();
-                while (true)
-                {
-                    lock (this)
-                    {
-                        if (_stopped)
-                        {
-                            break;
-                        }
-
-                        // If we are in error state (_errorState is true), force a tear down.
-                        // Likewise, if we have exceeded the maximum retry period (30 seconds) waiting for cleanup, force a tear down.
-                        // In rare cases during app domain unload, the async cleanup performed by AsyncResultCallback
-                        // may fail to execute TearDownAndDispose, leaving this method in an infinite loop.
-                        // To avoid the infinite loop, we force the cleanup here after 30 seconds.  Since we have reached
-                        // refcount of 0, either this method call or the thread running AsyncResultCallback is responsible for calling
-                        // TearDownAndDispose when transitioning to the _stopped state.  Failing to call TearDownAndDispose means we leak
-                        // the service broker objects created by this SqlDependency instance, so we make a best effort here to call
-                        // TearDownAndDispose in the maximum retry period case as well as in the _errorState case.
-                        if (_errorState || retryStopwatch.Elapsed.Seconds >= 30)
-                        {
-                            Timer retryTimer = _retryTimer;
-                            _retryTimer = null;
-                            if (retryTimer != null)
-                            {
-                                retryTimer.Dispose(); // Dispose timer - stop retry loop!
-                            }
-                            TearDownAndDispose(); // Will not hit server unless connection open!
-                            break;
-                        }
-                    }
-
-                    // Yield the thread since the stop has not yet completed.
-                    // To avoid CPU spikes while waiting, yield and wait for at least one millisecond
-                    Thread.Sleep(1);
-                }
-            }
-
-            Debug.Assert(0 <= _startCount, "Invalid start count state");
-
-            return _stopped;
-        }
-
-        private void SynchronouslyQueryServiceBrokerQueue()
-        {
-            using (SqlDataReader reader = _com.ExecuteReader())
-            {
-                ProcessNotificationResults(reader);
-            }
-        }
-
-        [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")]
-        private void TearDownAndDispose()
-        {
-            lock (this)
-            { // Lock to ensure Stop() (with Cancel()) complete prior to TearDown.
-                try
-                {
-                    // Only execute if connection is still up and open.
-                    if (ConnectionState.Closed != _con.State && ConnectionState.Broken != _con.State)
-                    {
-                        if (_com.Parameters.Count > 1)
-                        { // Need to close dialog before completing.
-                            // In the normal case, the "End Conversation" query is executed before a
-                            // receive query and upon return we will clear the state.  However, unless
-                            // a non notification query result is returned, we will not clear it.  That
-                            // means a query is generally always executing with an "end conversation" on
-                            // the wire.  Rather than synchronize for success of the other "end conversation",
-                            // simply re-execute.
-                            try
-                            {
-                                _com.CommandText = _endConversationQuery;
-                                _com.Parameters.Remove(_timeoutParam);
-                                _com.ExecuteNonQuery();
-                            }
-                            catch (Exception e)
-                            {
-                                if (!ADP.IsCatchableExceptionType(e))
-                                {
-                                    throw;
-                                }
-                                ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
-                            }
-                        }
-
-                        if (_serviceQueueCreated && !_errorState)
-                        {
-                            /*
-                                BEGIN TRANSACTION;
-                                DROP SERVICE "+_escapedQueueName+";
-                                DROP QUEUE "+_escapedQueueName+";
-                                DROP PROCEDURE "+_sprocName+";
-                                COMMIT TRANSACTION;
-                            */
-                            _com.CommandText = "BEGIN TRANSACTION; DROP SERVICE " + _escapedQueueName + "; DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; COMMIT TRANSACTION;";
-                            try
-                            {
-                                _com.ExecuteNonQuery();
-                            }
-                            catch (Exception e)
-                            {
-                                if (!ADP.IsCatchableExceptionType(e))
-                                {
-                                    throw;
-                                }
-                                ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    _stopped = true;
-                    _con.Dispose(); // Close and dispose connection.
-                }
-            }
-        }
-    }
-
-    // Private class encapsulating the notification payload parsing logic.
-
-    private class SqlNotificationParser
-    {
-        [Flags]
-        private enum MessageAttributes
-        {
-            None = 0,
-            Type = 1,
-            Source = 2,
-            Info = 4,
-            All = Type + Source + Info,
-        }
-
-        // node names in the payload
-        private const string RootNode = "QueryNotification";
-        private const string MessageNode = "Message";
-
-        // attribute names (on the QueryNotification element)
-        private const string InfoAttribute = "info";
-        private const string SourceAttribute = "source";
-        private const string TypeAttribute = "type";
-
-        internal static SqlNotification ProcessMessage(SqlXml xmlMessage)
-        {
-            using (XmlReader xmlReader = xmlMessage.CreateReader())
-            {
-                MessageAttributes messageAttributes = MessageAttributes.None;
-
-                SqlNotificationType type = SqlNotificationType.Unknown;
-                SqlNotificationInfo info = SqlNotificationInfo.Unknown;
-                SqlNotificationSource source = SqlNotificationSource.Unknown;
-
-                string key = string.Empty;
-
-                // Move to main node, expecting "QueryNotification".
-                xmlReader.Read();
-                if ((XmlNodeType.Element == xmlReader.NodeType) &&
-                     (RootNode == xmlReader.LocalName) &&
-                     (3 <= xmlReader.AttributeCount))
-                {
-                    // Loop until we've processed all the attributes.
-                    while ((MessageAttributes.All != messageAttributes) && (xmlReader.MoveToNextAttribute()))
-                    {
-                        try
-                        {
-                            switch (xmlReader.LocalName)
-                            {
-                                case TypeAttribute:
-                                    try
-                                    {
-                                        SqlNotificationType temp = (SqlNotificationType)Enum.Parse(typeof(SqlNotificationType), xmlReader.Value, true);
-                                        if (Enum.IsDefined(typeof(SqlNotificationType), temp))
-                                        {
-                                            type = temp;
-                                        }
-                                    }
-                                    catch (Exception e)
-                                    {
-                                        if (!ADP.IsCatchableExceptionType(e))
-                                        {
-                                            throw;
-                                        }
-                                        ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
-                                    }
-                                    messageAttributes |= MessageAttributes.Type;
-                                    break;
-                                case SourceAttribute:
-                                    try
-                                    {
-                                        SqlNotificationSource temp = (SqlNotificationSource)Enum.Parse(typeof(SqlNotificationSource), xmlReader.Value, true);
-                                        if (Enum.IsDefined(typeof(SqlNotificationSource), temp))
-                                        {
-                                            source = temp;
-                                        }
-                                    }
-                                    catch (Exception e)
-                                    {
-                                        if (!ADP.IsCatchableExceptionType(e))
-                                        {
-                                            throw;
-                                        }
-                                        ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
-                                    }
-                                    messageAttributes |= MessageAttributes.Source;
-                                    break;
-                                case InfoAttribute:
-                                    try
-                                    {
-                                        string value = xmlReader.Value;
-                                        // 3 of the server info values do not match client values - map.
-                                        switch (value)
-                                        {
-                                            case "set options":
-                                                info = SqlNotificationInfo.Options;
-                                                break;
-                                            case "previous invalid":
-                                                info = SqlNotificationInfo.PreviousFire;
-                                                break;
-                                            case "query template limit":
-                                                info = SqlNotificationInfo.TemplateLimit;
-                                                break;
-                                            default:
-                                                SqlNotificationInfo temp = (SqlNotificationInfo)Enum.Parse(typeof(SqlNotificationInfo), value, true);
-                                                if (Enum.IsDefined(typeof(SqlNotificationInfo), temp))
-                                                {
-                                                    info = temp;
-                                                }
-                                                break;
-                                        }
-                                    }
-                                    catch (Exception e)
-                                    {
-                                        if (!ADP.IsCatchableExceptionType(e))
-                                        {
-                                            throw;
-                                        }
-                                        ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
-                                    }
-                                    messageAttributes |= MessageAttributes.Info;
-                                    break;
-                                default:
-                                    break;
-                            }
-                        }
-                        catch (ArgumentException e)
-                        {
-                            ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace.
-                            return null;
-                        }
-                    }
-
-                    if (MessageAttributes.All != messageAttributes)
-                    {
-                        return null;
-                    }
-
-                    // Proceed to the "Message" node.
-                    if (!xmlReader.Read())
-                    {
-                        return null;
-                    }
-
-                    // Verify state after Read().
-                    if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase)))
-                    {
-                        return null;
-                    }
-
-                    // Proceed to the Text Node.
-                    if (!xmlReader.Read())
-                    {
-                        return null;
-                    }
-
-                    // Verify state after Read().
-                    if (xmlReader.NodeType != XmlNodeType.Text)
-                    {
-                        return null;
-                    }
-
-                    // Create a new XmlTextReader on the Message node value.
-                    using (XmlTextReader xmlMessageReader = new XmlTextReader(xmlReader.Value, XmlNodeType.Element, null))
-                    {
-                        // Proceed to the Text Node.
-                        if (!xmlMessageReader.Read())
-                        {
-                            return null;
-                        }
-
-                        if (xmlMessageReader.NodeType == XmlNodeType.Text)
-                        {
-                            key = xmlMessageReader.Value;
-                            xmlMessageReader.Close();
-                        }
-                        else
-                        {
-                            return null;
-                        }
-                    }
-
-                    return new SqlNotification(info, source, type, key);
-                }
-                else
-                {
-                    return null; // failure
-                }
-            }
-        }
-    }
-
-    // Private class encapsulating the SqlConnectionContainer hash logic.
-
-    private class SqlConnectionContainerHashHelper
-    {
-        // For default, queue is computed in SqlConnectionContainer constructor, so queue will be empty and
-        // connection string will not include app name based on queue.  As a result, the connection string
-        // builder will always contain up to date info, but _connectionString and _queue will not.
-
-        // As a result, we will not use _connectionStringBuilder as part of Equals or GetHashCode.
-
-        private readonly DbConnectionPoolIdentity _identity;
-        private readonly string _connectionString;
-        private readonly string _queue;
-        private readonly SqlConnectionStringBuilder _connectionStringBuilder; // Not to be used for comparison!
-
-        internal SqlConnectionContainerHashHelper(DbConnectionPoolIdentity identity, string connectionString,
-                                                  string queue, SqlConnectionStringBuilder connectionStringBuilder)
-        {
-            _identity = identity;
-            _connectionString = connectionString;
-            _queue = queue;
-            _connectionStringBuilder = connectionStringBuilder;
-        }
-
-        // Not to be used for comparison!
-        internal SqlConnectionStringBuilder ConnectionStringBuilder => _connectionStringBuilder;
-
-        internal DbConnectionPoolIdentity Identity => _identity;
-
-        internal string Queue => _queue;
-
-        public override bool Equals(object value)
-        {
-            SqlConnectionContainerHashHelper temp = (SqlConnectionContainerHashHelper)value;
-
-            bool result = false;
-
-            // Ignore SqlConnectionStringBuilder, since it is present largely for debug purposes.
-
-            if (null == temp)
-            { // If passed value null - false.
-                result = false;
-            }
-            else if (this == temp)
-            { // If instances equal - true.
-                result = true;
-            }
-            else
-            {
-                if ((_identity != null && temp._identity == null) || // If XOR of null identities false - false.
-                     (_identity == null && temp._identity != null))
-                {
-                    result = false;
-                }
-                else if (_identity == null && temp._identity == null)
-                {
-                    if (temp._connectionString == _connectionString &&
-                        string.Equals(temp._queue, _queue, StringComparison.OrdinalIgnoreCase))
-                    {
-                        result = true;
-                    }
-                    else
-                    {
-                        result = false;
-                    }
-                }
-                else
-                {
-                    if (temp._identity.Equals(_identity) &&
-                        temp._connectionString == _connectionString &&
-                        string.Equals(temp._queue, _queue, StringComparison.OrdinalIgnoreCase))
-                    {
-                        result = true;
-                    }
-                    else
-                    {
-                        result = false;
-                    }
-                }
-            }
-
-            return result;
-        }
-
-        public override int GetHashCode()
-        {
-            int hashValue = 0;
-
-            if (null != _identity)
-            {
-                hashValue = _identity.GetHashCode();
-            }
-
-            if (null != _queue)
-            {
-                hashValue = unchecked(_connectionString.GetHashCode() + _queue.GetHashCode() + hashValue);
-            }
-            else
-            {
-                hashValue = unchecked(_connectionString.GetHashCode() + hashValue);
-            }
-
-            return hashValue;
-        }
-    }
-
-    // SqlDependencyProcessDispatcher static members
-
-    private static readonly SqlDependencyProcessDispatcher s_staticInstance = new SqlDependencyProcessDispatcher(null);
-
-    // Dictionaries used as maps.
-    private readonly Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer> _connectionContainers;                 // NT_ID+ConStr+Service->Container
-    private readonly Dictionary<string, SqlDependencyPerAppDomainDispatcher> _sqlDependencyPerAppDomainDispatchers; // AppDomainKey->Callback
-
-    // Constructors
-
-    // Private constructor - only called by public constructor for static initialization.
-    private SqlDependencyProcessDispatcher(object dummyVariable)
-    {
-        Debug.Assert(null == s_staticInstance, "Real constructor called with static instance already created!");
-
-        _connectionContainers = new Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer>();
-        _sqlDependencyPerAppDomainDispatchers = new Dictionary<string, SqlDependencyPerAppDomainDispatcher>();
-    }
-
-    // Constructor is only called by remoting.
-    // Required to be public, even on internal class, for Remoting infrastructure.
-    public SqlDependencyProcessDispatcher()
-    {
-        // Empty constructor and object - dummy to obtain singleton.
-    }
-
-    // Properties
-
-    internal static SqlDependencyProcessDispatcher SingletonProcessDispatcher => s_staticInstance;
-
-    // Various private methods
-
-    private static SqlConnectionContainerHashHelper GetHashHelper(
-        string connectionString,
-        out SqlConnectionStringBuilder connectionStringBuilder,
-        out DbConnectionPoolIdentity identity,
-        out string user,
-            string queue)
-    {
-        // Force certain connection string properties to be used by SqlDependencyProcessDispatcher.
-        // This logic is done here to enable us to have the complete connection string now to be used
-        // for tracing as we flow through the logic.
-        connectionStringBuilder = new SqlConnectionStringBuilder(connectionString)
-        {
-            Pooling = false,
-            Enlist = false,
-            ConnectRetryCount = 0
-        };
-        if (null != queue)
-        { // User provided!
-            connectionStringBuilder.ApplicationName = queue; // ApplicationName will be set to queue name.
-        }
-
-        if (connectionStringBuilder.IntegratedSecurity)
-        {
-            // Use existing identity infrastructure for error cases and proper hash value.
-            identity = DbConnectionPoolIdentity.GetCurrent();
-            user = null;
-        }
-        else
-        {
-            identity = null;
-            user = connectionStringBuilder.UserID;
-        }
-
-        return new SqlConnectionContainerHashHelper(identity, connectionStringBuilder.ConnectionString,
-                                                    queue, connectionStringBuilder);
-    }
-
-    // Needed for remoting to prevent lifetime issues and default GC cleanup.
-    public override object InitializeLifetimeService()
-    {
-        return null;
-    }
-
-    private void Invalidate(string server, SqlNotification sqlNotification)
-    {
-        Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
-        lock (_sqlDependencyPerAppDomainDispatchers)
-        {
-
-            foreach (KeyValuePair<string, SqlDependencyPerAppDomainDispatcher> entry in _sqlDependencyPerAppDomainDispatchers)
-            {
-                SqlDependencyPerAppDomainDispatcher perAppDomainDispatcher = entry.Value;
-                try
-                {
-                    perAppDomainDispatcher.InvalidateServer(server, sqlNotification);
-                }
-                catch (Exception f)
-                {
-                    // Since we are looping over dependency dispatchers, do not allow one Invalidate
-                    // that results in a throw prevent us from invalidating all dependencies
-                    // related to this server.
-                    // NOTE - SqlDependencyPerAppDomainDispatcher already wraps individual dependency invalidates
-                    // with try/catch, but we should be careful and do the same here.
-                    if (!ADP.IsCatchableExceptionType(f))
-                    {
-                        throw;
-                    }
-                    ADP.TraceExceptionWithoutRethrow(f); // Discard failure, but trace.
-                }
-            }
-        }
-    }
-
-    // Clean-up method initiated by other AppDomain.Unloads
-
-    // Individual AppDomains upon AppDomain.UnloadEvent will call this method.
-    internal void QueueAppDomainUnloading(string appDomainKey)
-    {
-        ThreadPool.QueueUserWorkItem(new WaitCallback(AppDomainUnloading), appDomainKey);
-    }
-
-    // This method is only called by queued work-items from the method above.
-    private void AppDomainUnloading(object state)
-    {
-        string appDomainKey = (string)state;
-
-        Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
-        lock (_connectionContainers)
-        {
-            List<SqlConnectionContainerHashHelper> containersToRemove = new List<SqlConnectionContainerHashHelper>();
-
-            foreach (KeyValuePair<SqlConnectionContainerHashHelper, SqlConnectionContainer> entry in _connectionContainers)
-            {
-                SqlConnectionContainer container = entry.Value;
-                if (container.AppDomainUnload(appDomainKey))
-                { // Perhaps wrap in try catch.
-                    containersToRemove.Add(container.HashHelper);
-                }
-            }
-
-            foreach (SqlConnectionContainerHashHelper hashHelper in containersToRemove)
-            {
-                _connectionContainers.Remove(hashHelper);
-            }
-        }
-
-        lock (_sqlDependencyPerAppDomainDispatchers)
-        { // Remove from global Dictionary.
-            _sqlDependencyPerAppDomainDispatchers.Remove(appDomainKey);
-        }
-    }
-
-    // -------------
-    // Start methods
-    // -------------
-
-    internal bool StartWithDefault(
-        string connectionString,
-        out string server,
-        out DbConnectionPoolIdentity identity,
-        out string user,
-        out string database,
-        ref string service,
-            string appDomainKey,
-            SqlDependencyPerAppDomainDispatcher dispatcher,
-        out bool errorOccurred,
-        out bool appDomainStart)
-    {
-        Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
-        return Start(
-            connectionString,
-            out server,
-            out identity,
-            out user,
-            out database,
-            ref service,
-                appDomainKey,
-                dispatcher,
-            out errorOccurred,
-            out appDomainStart,
-                true);
-    }
-
-    internal bool Start(
-        string connectionString,
-        string queue,
-        string appDomainKey,
-        SqlDependencyPerAppDomainDispatcher dispatcher)
-    {
-        Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
-        return Start(
-            connectionString,
-            out string dummyValue1,
-            out DbConnectionPoolIdentity dummyValue3,
-            out dummyValue1,
-            out dummyValue1,
-            ref queue,
-                appDomainKey,
-                dispatcher,
-            out bool dummyValue2,
-            out dummyValue2,
-                false);
-    }
-
-    private bool Start(
-        string connectionString,
-        out string server,
-        out DbConnectionPoolIdentity identity,
-        out string user,
-        out string database,
-        ref string queueService,
-            string appDomainKey,
-            SqlDependencyPerAppDomainDispatcher dispatcher,
-        out bool errorOccurred,
-        out bool appDomainStart,
-            bool useDefaults)
-    {
-        Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
-        server = null;  // Reset out params.
-        identity = null;
-        user = null;
-        database = null;
-        errorOccurred = false;
-        appDomainStart = false;
-
-        lock (_sqlDependencyPerAppDomainDispatchers)
-        {
-            if (!_sqlDependencyPerAppDomainDispatchers.ContainsKey(appDomainKey))
-            {
-                _sqlDependencyPerAppDomainDispatchers[appDomainKey] = dispatcher;
-            }
-        }
-
-        SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString,
-                                                            out SqlConnectionStringBuilder connectionStringBuilder,
-                                                            out identity,
-                                                            out user,
-                                                                queueService);
-
-        bool started = false;
-
-        SqlConnectionContainer container = null;
-        lock (_connectionContainers)
-        {
-            if (!_connectionContainers.ContainsKey(hashHelper))
-            {
-                container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults);
-                _connectionContainers.Add(hashHelper, container);
-                started = true;
-                appDomainStart = true;
-            }
-            else
-            {
-                container = _connectionContainers[hashHelper];
-                if (container.InErrorState)
-                {
-                    errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start().
-                }
-                else
-                {
-                    container.IncrementStartCount(appDomainKey, out appDomainStart);
-                }
-            }
-        }
-
-        if (useDefaults && !errorOccurred)
-        { // Return server, database, and queue for use by SqlDependency.
-            server = container.Server;
-            database = container.Database;
-            queueService = container.Queue;
-        }
-
-        return started;
-    }
-
-    // Stop methods
-
-    internal bool Stop(
-        string connectionString,
-        out string server,
-        out DbConnectionPoolIdentity identity,
-        out string user,
-        out string database,
-        ref string queueService,
-            string appDomainKey,
-        out bool appDomainStop)
-    {
-        Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
-        server = null;  // Reset out param.
-        identity = null;
-        user = null;
-        database = null;
-        appDomainStop = false;
-
-        SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString,
-                                                          out SqlConnectionStringBuilder connectionStringBuilder,
-                                                          out identity,
-                                                          out user,
-                                                              queueService);
-
-        bool stopped = false;
-
-        lock (_connectionContainers)
-        {
-            if (_connectionContainers.ContainsKey(hashHelper))
-            {
-                SqlConnectionContainer container = _connectionContainers[hashHelper];
-                server = container.Server;   // Return server, database, and queue info for use by calling SqlDependency.
-                database = container.Database;
-                queueService = container.Queue;
-
-                if (container.Stop(appDomainKey, out appDomainStop))
-                {
-                    // Stop can be blocking if refCount == 0 on container.
-                    stopped = true;
-                    _connectionContainers.Remove(hashHelper); // Remove from collection.
-                }
-            }
-        }
-
-        return stopped;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyUtils.AppDomain.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyUtils.AppDomain.cs
deleted file mode 100644 (file)
index 96fb06f..0000000
+++ /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.
-
-namespace System.Data.SqlClient
-{
-    // these members were moved to a separate file in order
-    // to be able to skip them on platforms where AppDomain members are not supported
-    // for example, some mobile profiles on mono
-    internal partial class SqlDependencyPerAppDomainDispatcher
-    {
-        private void SubscribeToAppDomainUnload()
-        {
-            // If rude abort - we'll leak.  This is acceptable for now.
-            AppDomain.CurrentDomain.DomainUnload += new EventHandler(UnloadEventHandler);
-        }
-
-        private void UnloadEventHandler(object sender, EventArgs e)
-        {
-            // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete
-            // stopping of all start calls in this AppDomain.  For containers shared among various AppDomains,
-            // this will just be a ref-count subtract.  For non-shared containers, we will close the container
-            // and clean-up.
-            var dispatcher = SqlDependency.ProcessDispatcher;
-            dispatcher?.QueueAppDomainUnloading(SqlDependency.AppDomainKey);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyUtils.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlDependencyUtils.cs
deleted file mode 100644 (file)
index 4124c3c..0000000
+++ /dev/null
@@ -1,497 +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.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Threading;
-
-namespace System.Data.SqlClient
-{
-    // This is a singleton instance per AppDomain that acts as the notification dispatcher for
-    // that AppDomain.  It receives calls from the SqlDependencyProcessDispatcher with an ID or a server name
-    // to invalidate matching dependencies in the given AppDomain.
-
-    internal partial class SqlDependencyPerAppDomainDispatcher : MarshalByRefObject
-    {
-        // Instance members
-
-        internal static readonly SqlDependencyPerAppDomainDispatcher
-                 SingletonInstance = new SqlDependencyPerAppDomainDispatcher(); // singleton object
-
-        internal object _instanceLock = new object();
-
-        // Dependency ID -> Dependency hashtable.  1 -> 1 mapping.
-        // 1) Used for ASP.NET to map from ID to dependency.
-        // 2) Used to enumerate dependencies to invalidate based on server.
-        private readonly Dictionary<string, SqlDependency> _dependencyIdToDependencyHash;
-
-        // holds dependencies list per notification and the command hash from which this notification was generated
-        // command hash is needed to remove its entry from _commandHashToNotificationId when the notification is removed
-        private sealed class DependencyList : List<SqlDependency>
-        {
-            public readonly string CommandHash;
-
-            internal DependencyList(string commandHash)
-            {
-                CommandHash = commandHash;
-            }
-        }
-
-        // notificationId -> Dependencies hashtable:  1 -> N mapping.  notificationId == appDomainKey + commandHash.
-        // More than one dependency can be using the same command hash values resulting in a hash to the same value.
-        // We use this to cache mapping between command to dependencies such that we may reduce the notification
-        // resource effect on SQL Server.  The Guid identifier is sent to the server during notification enlistment,
-        // and returned during the notification event.  Dependencies look up existing Guids, if one exists, to ensure
-        // they are re-using notification ids.
-        private readonly Dictionary<string, DependencyList> _notificationIdToDependenciesHash;
-
-        // CommandHash value -> notificationId associated with it:  1->1 mapping. This map is used to quickly find if we need to create
-        // new notification or hookup into existing one.
-        // CommandHash is built from connection string, command text and parameters
-        private readonly Dictionary<string, string> _commandHashToNotificationId;
-
-        // TIMEOUT LOGIC DESCRIPTION
-        //
-        // Every time we add a dependency we compute the next, earlier timeout.
-        //
-        // We setup a timer to get a callback every 15 seconds. In the call back:
-        // - If there are no active dependencies, we just return.
-        // - If there are dependencies but none of them timed-out (compared to the "next timeout"),
-        //   we just return.
-        // - Otherwise we Invalidate() those that timed-out.
-        //
-        // So the client-generated timeouts have a granularity of 15 seconds. This allows
-        // for a simple and low-resource-consumption implementation.
-        //
-        // LOCKS: don't update _nextTimeout outside of the _dependencyHash.SyncRoot lock.
-
-        private bool _sqlDependencyTimeOutTimerStarted = false;
-        // Next timeout for any of the dependencies in the dependency table.
-        private DateTime _nextTimeout;
-        // Timer to periodically check the dependencies in the table and see if anyone needs
-        // a timeout.  We'll enable this only on demand.
-        private readonly Timer _timeoutTimer;
-
-        private SqlDependencyPerAppDomainDispatcher()
-        {
-            _dependencyIdToDependencyHash = new Dictionary<string, SqlDependency>();
-            _notificationIdToDependenciesHash = new Dictionary<string, DependencyList>();
-            _commandHashToNotificationId = new Dictionary<string, string>();
-
-            _timeoutTimer = ADP.UnsafeCreateTimer(
-                new TimerCallback(TimeoutTimerCallback),
-                null,
-                Timeout.Infinite,
-                Timeout.Infinite);
-
-            SubscribeToAppDomainUnload();
-        }
-
-        //  When remoted across appdomains, MarshalByRefObject links by default time out if there is no activity
-        //  within a few minutes.  Add this override to prevent marshaled links from timing out.
-        public override object InitializeLifetimeService()
-        {
-            return null;
-        }
-
-        // Methods for dependency hash manipulation and firing.
-
-        // This method is called upon SqlDependency constructor.
-        internal void AddDependencyEntry(SqlDependency dep)
-        {
-            lock (_instanceLock)
-            {
-                _dependencyIdToDependencyHash.Add(dep.Id, dep);
-            }
-        }
-
-        // This method is called upon Execute of a command associated with a SqlDependency object.
-        internal string AddCommandEntry(string commandHash, SqlDependency dep)
-        {
-            string notificationId = string.Empty;
-            lock (_instanceLock)
-            {
-                if (_dependencyIdToDependencyHash.ContainsKey(dep.Id))
-                {
-                    // check if we already have notification associated with given command hash
-                    if (_commandHashToNotificationId.TryGetValue(commandHash, out notificationId))
-                    {
-                        // we have one or more SqlDependency instances with same command hash
-
-                        DependencyList dependencyList = null;
-                        if (!_notificationIdToDependenciesHash.TryGetValue(notificationId, out dependencyList))
-                        {
-                            // this should not happen since _commandHashToNotificationId and _notificationIdToDependenciesHash are always
-                            // updated together
-                            Debug.Fail("_commandHashToNotificationId has entries that were removed from _notificationIdToDependenciesHash. Remember to keep them in sync");
-                            throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyCommandHashIsNotAssociatedWithNotification);
-                        }
-
-                        // join the new dependency to the list
-                        if (!dependencyList.Contains(dep))
-                        {
-                            dependencyList.Add(dep);
-                        }
-                    }
-                    else
-                    {
-                        // we did not find notification ID with the same app domain and command hash, create a new one
-                        // use unique guid to avoid duplicate IDs
-                        // prepend app domain ID to the key - SqlConnectionContainer::ProcessNotificationResults (SqlDependencyListener.cs)
-                        // uses this app domain ID to route the message back to the app domain in which this SqlDependency was created
-                        notificationId = string.Format(System.Globalization.CultureInfo.InvariantCulture,
-                            "{0};{1}",
-                            SqlDependency.AppDomainKey, // must be first
-                            Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture)
-                            );
-
-                        DependencyList dependencyList = new DependencyList(commandHash);
-                        dependencyList.Add(dep);
-
-                        // map command hash to notification we just created to reuse it for the next client
-                        _commandHashToNotificationId.Add(commandHash, notificationId);
-                        _notificationIdToDependenciesHash.Add(notificationId, dependencyList);
-                    }
-
-                    Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!");
-                }
-            }
-
-            return notificationId;
-        }
-
-        // This method is called by the ProcessDispatcher upon a notification for this AppDomain.
-        internal void InvalidateCommandID(SqlNotification sqlNotification)
-        {
-            List<SqlDependency> dependencyList = null;
-
-            lock (_instanceLock)
-            {
-                dependencyList = LookupCommandEntryWithRemove(sqlNotification.Key);
-
-                if (null != dependencyList)
-                {
-                    foreach (SqlDependency dependency in dependencyList)
-                    {
-                        // Ensure we remove from process static app domain hash for dependency initiated invalidates.
-                        LookupDependencyEntryWithRemove(dependency.Id);
-
-                        // Completely remove Dependency from commandToDependenciesHash.
-                        RemoveDependencyFromCommandToDependenciesHash(dependency);
-                    }
-                }
-            }
-
-            if (null != dependencyList)
-            {
-                // After removal from hashtables, invalidate.
-                foreach (SqlDependency dependency in dependencyList)
-                {
-                    try
-                    {
-                        dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source);
-                    }
-                    catch (Exception e)
-                    {
-                        // Since we are looping over dependencies, do not allow one Invalidate
-                        // that results in a throw prevent us from invalidating all dependencies
-                        // related to this server.
-                        if (!ADP.IsCatchableExceptionType(e))
-                        {
-                            throw;
-                        }
-                        ADP.TraceExceptionWithoutRethrow(e);
-                    }
-                }
-            }
-        }
-
-        // This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher.
-        internal void InvalidateServer(string server, SqlNotification sqlNotification)
-        {
-            List<SqlDependency> dependencies = new List<SqlDependency>();
-
-            lock (_instanceLock)
-            { // Copy inside of lock, but invalidate outside of lock.
-                foreach (KeyValuePair<string, SqlDependency> entry in _dependencyIdToDependencyHash)
-                {
-                    SqlDependency dependency = entry.Value;
-                    if (dependency.ContainsServer(server))
-                    {
-                        dependencies.Add(dependency);
-                    }
-                }
-
-                foreach (SqlDependency dependency in dependencies)
-                { // Iterate over resulting list removing from our hashes.
-                    // Ensure we remove from process static app domain hash for dependency initiated invalidates.
-                    LookupDependencyEntryWithRemove(dependency.Id);
-
-                    // Completely remove Dependency from commandToDependenciesHash.
-                    RemoveDependencyFromCommandToDependenciesHash(dependency);
-                }
-            }
-
-            foreach (SqlDependency dependency in dependencies)
-            { // Iterate and invalidate.
-                try
-                {
-                    dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source);
-                }
-                catch (Exception e)
-                {
-                    // Since we are looping over dependencies, do not allow one Invalidate
-                    // that results in a throw prevent us from invalidating all dependencies
-                    // related to this server.
-                    if (!ADP.IsCatchableExceptionType(e))
-                    {
-                        throw;
-                    }
-                    ADP.TraceExceptionWithoutRethrow(e);
-                }
-            }
-        }
-
-        // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency.
-        internal SqlDependency LookupDependencyEntry(string id)
-        {
-            if (null == id)
-            {
-                throw ADP.ArgumentNull(nameof(id));
-            }
-            if (string.IsNullOrEmpty(id))
-            {
-                throw SQL.SqlDependencyIdMismatch();
-            }
-
-            SqlDependency entry = null;
-
-            lock (_instanceLock)
-            {
-                if (_dependencyIdToDependencyHash.ContainsKey(id))
-                {
-                    entry = _dependencyIdToDependencyHash[id];
-                }
-            }
-
-            return entry;
-        }
-
-        // Remove the dependency from the hashtable with the passed id.
-        private void LookupDependencyEntryWithRemove(string id)
-        {
-            lock (_instanceLock)
-            {
-                if (_dependencyIdToDependencyHash.ContainsKey(id))
-                {
-                    _dependencyIdToDependencyHash.Remove(id);
-
-                    // if there are no more dependencies then we can dispose the timer.
-                    if (0 == _dependencyIdToDependencyHash.Count)
-                    {
-                        _timeoutTimer.Change(Timeout.Infinite, Timeout.Infinite);
-                        _sqlDependencyTimeOutTimerStarted = false;
-                    }
-                }
-            }
-        }
-
-        // Find and return arraylist, and remove passed hash value.
-        private List<SqlDependency> LookupCommandEntryWithRemove(string notificationId)
-        {
-            DependencyList entry = null;
-
-            lock (_instanceLock)
-            {
-                if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry))
-                {
-                    // update the tables
-                    _notificationIdToDependenciesHash.Remove(notificationId);
-                    // Cleanup the map between the command hash and associated notification ID
-                    _commandHashToNotificationId.Remove(entry.CommandHash);
-                }
-
-                Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!");
-            }
-
-            return entry; // DependencyList inherits from List<SqlDependency>
-        }
-
-        // Remove from commandToDependenciesHash all references to the passed dependency.
-        private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency)
-        {
-            lock (_instanceLock)
-            {
-                List<string> notificationIdsToRemove = new List<string>();
-                List<string> commandHashesToRemove = new List<string>();
-
-                foreach (KeyValuePair<string, DependencyList> entry in _notificationIdToDependenciesHash)
-                {
-                    DependencyList dependencies = entry.Value;
-                    if (dependencies.Remove(dependency))
-                    {
-                        if (dependencies.Count == 0)
-                        {
-                            // this dependency was the last associated with this notification ID, remove the entry
-                            // note: cannot do it inside foreach over dictionary
-                            notificationIdsToRemove.Add(entry.Key);
-                            commandHashesToRemove.Add(entry.Value.CommandHash);
-                        }
-                    }
-
-                    // same SqlDependency can be associated with more than one command, so we have to continue till the end...
-                }
-
-                Debug.Assert(commandHashesToRemove.Count == notificationIdsToRemove.Count, "maps should be kept in sync");
-                for (int i = 0; i < notificationIdsToRemove.Count; i++)
-                {
-                    // cleanup the entry outside of foreach
-                    _notificationIdToDependenciesHash.Remove(notificationIdsToRemove[i]);
-                    // Cleanup the map between the command hash and associated notification ID
-                    _commandHashToNotificationId.Remove(commandHashesToRemove[i]);
-                }
-
-                Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!");
-            }
-        }
-
-        // Methods for Timer maintenance and firing.
-
-        internal void StartTimer(SqlDependency dep)
-        {
-            // If this dependency expires sooner than the current next timeout, change
-            // the timeout and enable timer callback as needed.  Note that we change _nextTimeout
-            // only inside the hashtable syncroot.
-            lock (_instanceLock)
-            {
-                // Enable the timer if needed (disable when empty, enable on the first addition).
-                if (!_sqlDependencyTimeOutTimerStarted)
-                {
-                    _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */);
-
-                    // Save this as the earlier timeout to come.
-                    _nextTimeout = dep.ExpirationTime;
-                    _sqlDependencyTimeOutTimerStarted = true;
-                }
-                else if (_nextTimeout > dep.ExpirationTime)
-                {
-                    // Save this as the earlier timeout to come.
-                    _nextTimeout = dep.ExpirationTime;
-                }
-            }
-        }
-
-        private static void TimeoutTimerCallback(object state)
-        {
-            SqlDependency[] dependencies;
-
-            // Only take the lock for checking whether there is work to do
-            // if we do have work, we'll copy the hashtable and scan it after releasing
-            // the lock.
-            lock (SingletonInstance._instanceLock)
-            {
-                if (0 == SingletonInstance._dependencyIdToDependencyHash.Count)
-                {
-                    // Nothing to check.
-                    return;
-                }
-                if (SingletonInstance._nextTimeout > DateTime.UtcNow)
-                {
-                    // No dependency timed-out yet.
-                    return;
-                }
-
-                // If at least one dependency timed-out do a scan of the table.
-                // NOTE: we could keep a shadow table sorted by expiration time, but
-                // given the number of typical simultaneously alive dependencies it's
-                // probably not worth the optimization.
-                dependencies = new SqlDependency[SingletonInstance._dependencyIdToDependencyHash.Count];
-                SingletonInstance._dependencyIdToDependencyHash.Values.CopyTo(dependencies, 0);
-            }
-
-            // Scan the active dependencies if needed.
-            DateTime now = DateTime.UtcNow;
-            DateTime newNextTimeout = DateTime.MaxValue;
-
-            for (int i = 0; i < dependencies.Length; i++)
-            {
-                // If expired fire the change notification.
-                if (dependencies[i].ExpirationTime <= now)
-                {
-                    try
-                    {
-                        // This invokes user-code which may throw exceptions.
-                        // NOTE: this is intentionally outside of the lock, we don't want
-                        // to invoke user-code while holding an internal lock.
-                        dependencies[i].Invalidate(SqlNotificationType.Change, SqlNotificationInfo.Error, SqlNotificationSource.Timeout);
-                    }
-                    catch (Exception e)
-                    {
-                        if (!ADP.IsCatchableExceptionType(e))
-                        {
-                            throw;
-                        }
-
-                        // This is an exception in user code, and we're in a thread-pool thread
-                        // without user's code up in the stack, no much we can do other than
-                        // eating the exception.
-                        ADP.TraceExceptionWithoutRethrow(e);
-                    }
-                }
-                else
-                {
-                    if (dependencies[i].ExpirationTime < newNextTimeout)
-                    {
-                        newNextTimeout = dependencies[i].ExpirationTime; // Track the next earlier timeout.
-                    }
-                    dependencies[i] = null; // Null means "don't remove it from the hashtable" in the loop below.
-                }
-            }
-
-            // Remove timed-out dependencies from the hashtable.
-            lock (SingletonInstance._instanceLock)
-            {
-                for (int i = 0; i < dependencies.Length; i++)
-                {
-                    if (null != dependencies[i])
-                    {
-                        SingletonInstance._dependencyIdToDependencyHash.Remove(dependencies[i].Id);
-                    }
-                }
-                if (newNextTimeout < SingletonInstance._nextTimeout)
-                {
-                    SingletonInstance._nextTimeout = newNextTimeout; // We're inside the lock so ok to update.
-                }
-            }
-        }
-    }
-
-    // Simple class used to encapsulate all data in a notification.
-    internal class SqlNotification : MarshalByRefObject
-    {
-        // This class could be Serializable rather than MBR...
-
-        private readonly SqlNotificationInfo _info;
-        private readonly SqlNotificationSource _source;
-        private readonly SqlNotificationType _type;
-        private readonly string _key;
-
-        internal SqlNotification(SqlNotificationInfo info, SqlNotificationSource source, SqlNotificationType type, string key)
-        {
-            _info = info;
-            _source = source;
-            _type = type;
-            _key = key;
-        }
-
-        internal SqlNotificationInfo Info => _info;
-
-        internal string Key => _key;
-
-        internal SqlNotificationSource Source => _source;
-
-        internal SqlNotificationType Type => _type;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlEnums.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlEnums.cs
deleted file mode 100644 (file)
index 8203ab2..0000000
+++ /dev/null
@@ -1,900 +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.Generic;
-using System.Data.Common;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Globalization;
-using System.Xml;
-using System.IO;
-
-using MSS = Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class MetaType
-    {
-        internal readonly Type ClassType;   // com+ type
-        internal readonly Type SqlType;
-
-        internal readonly int FixedLength; // fixed length size in bytes (-1 for variable)
-        internal readonly bool IsFixed;     // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length
-        internal readonly bool IsLong;      // true if long
-        internal readonly bool IsPlp;       // Column is Partially Length Prefixed (MAX)
-        internal readonly byte Precision;   // maximum precision for numeric types
-        internal readonly byte Scale;
-        internal readonly byte TDSType;
-        internal readonly byte NullableType;
-
-        internal readonly string TypeName;    // string name of this type
-        internal readonly SqlDbType SqlDbType;
-        internal readonly DbType DbType;
-
-        //  holds count of property bytes expected for a SQLVariant structure
-        internal readonly byte PropBytes;
-
-
-        // pre-computed fields
-        internal readonly bool IsAnsiType;
-        internal readonly bool IsBinType;
-        internal readonly bool IsCharType;
-        internal readonly bool IsNCharType;
-        internal readonly bool IsSizeInCharacters;
-        internal readonly bool IsNewKatmaiType;
-        internal readonly bool IsVarTime;
-
-        internal readonly bool Is70Supported;
-        internal readonly bool Is80Supported;
-        internal readonly bool Is90Supported;
-        internal readonly bool Is100Supported;
-
-        public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes)
-        {
-            this.Precision = precision;
-            this.Scale = scale;
-            this.FixedLength = fixedLength;
-            this.IsFixed = isFixed;
-            this.IsLong = isLong;
-            this.IsPlp = isPlp;
-
-            this.TDSType = tdsType;
-            this.NullableType = nullableTdsType;
-            this.TypeName = typeName;
-            this.SqlDbType = sqldbType;
-            this.DbType = dbType;
-
-            this.ClassType = classType;
-            this.SqlType = sqlType;
-            this.PropBytes = propBytes;
-
-            IsAnsiType = _IsAnsiType(sqldbType);
-            IsBinType = _IsBinType(sqldbType);
-            IsCharType = _IsCharType(sqldbType);
-            IsNCharType = _IsNCharType(sqldbType);
-            IsSizeInCharacters = _IsSizeInCharacters(sqldbType);
-            IsNewKatmaiType = _IsNewKatmaiType(sqldbType);
-            IsVarTime = _IsVarTime(sqldbType);
-
-            Is70Supported = _Is70Supported(SqlDbType);
-            Is80Supported = _Is80Supported(SqlDbType);
-            Is90Supported = _Is90Supported(SqlDbType);
-            Is100Supported = _Is100Supported(SqlDbType);
-        }
-
-        // properties should be inlined so there should be no perf penalty for using these accessor functions
-        public int TypeId
-        {             // partial length prefixed (xml, nvarchar(max),...)
-            get { return 0; }
-        }
-
-        private static bool _IsAnsiType(SqlDbType type)
-        {
-            return (type == SqlDbType.Char ||
-                   type == SqlDbType.VarChar ||
-                   type == SqlDbType.Text);
-        }
-
-        // is this type size expressed as count of characters or bytes?
-        private static bool _IsSizeInCharacters(SqlDbType type)
-        {
-            return (type == SqlDbType.NChar ||
-                   type == SqlDbType.NVarChar ||
-                   type == SqlDbType.Xml ||
-                   type == SqlDbType.NText);
-        }
-
-        private static bool _IsCharType(SqlDbType type)
-        {
-            return (type == SqlDbType.NChar ||
-                   type == SqlDbType.NVarChar ||
-                   type == SqlDbType.NText ||
-                   type == SqlDbType.Char ||
-                   type == SqlDbType.VarChar ||
-                   type == SqlDbType.Text ||
-                   type == SqlDbType.Xml);
-        }
-
-        private static bool _IsNCharType(SqlDbType type)
-        {
-            return (type == SqlDbType.NChar ||
-                   type == SqlDbType.NVarChar ||
-                   type == SqlDbType.NText ||
-                   type == SqlDbType.Xml);
-        }
-
-        private static bool _IsBinType(SqlDbType type)
-        {
-            return (type == SqlDbType.Image ||
-                   type == SqlDbType.Binary ||
-                   type == SqlDbType.VarBinary ||
-                   type == SqlDbType.Timestamp ||
-                   type == SqlDbType.Udt ||
-                   (int)type == 24 /*SqlSmallVarBinary*/);
-        }
-
-        private static bool _Is70Supported(SqlDbType type)
-        {
-            return ((type != SqlDbType.BigInt) && ((int)type > 0) &&
-                   ((int)type <= (int)SqlDbType.VarChar));
-        }
-
-        private static bool _Is80Supported(SqlDbType type)
-        {
-            return ((int)type >= 0 &&
-                ((int)type <= (int)SqlDbType.Variant));
-        }
-
-        private static bool _Is90Supported(SqlDbType type)
-        {
-            return _Is80Supported(type) ||
-                    SqlDbType.Xml == type ||
-                    SqlDbType.Udt == type;
-        }
-
-        private static bool _Is100Supported(SqlDbType type)
-        {
-            return _Is90Supported(type) ||
-                    SqlDbType.Date == type ||
-                    SqlDbType.Time == type ||
-                    SqlDbType.DateTime2 == type ||
-                    SqlDbType.DateTimeOffset == type;
-        }
-
-        private static bool _IsNewKatmaiType(SqlDbType type)
-        {
-            return SqlDbType.Structured == type;
-        }
-
-        internal static bool _IsVarTime(SqlDbType type)
-        {
-            return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset);
-        }
-
-        //
-        // map SqlDbType to MetaType class
-        //
-        internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued)
-        { // WebData 113289
-            switch (target)
-            {
-                case SqlDbType.BigInt: return s_metaBigInt;
-                case SqlDbType.Binary: return s_metaBinary;
-                case SqlDbType.Bit: return s_metaBit;
-                case SqlDbType.Char: return s_metaChar;
-                case SqlDbType.DateTime: return s_metaDateTime;
-                case SqlDbType.Decimal: return MetaDecimal;
-                case SqlDbType.Float: return s_metaFloat;
-                case SqlDbType.Image: return MetaImage;
-                case SqlDbType.Int: return s_metaInt;
-                case SqlDbType.Money: return s_metaMoney;
-                case SqlDbType.NChar: return s_metaNChar;
-                case SqlDbType.NText: return MetaNText;
-                case SqlDbType.NVarChar: return MetaNVarChar;
-                case SqlDbType.Real: return s_metaReal;
-                case SqlDbType.UniqueIdentifier: return s_metaUniqueId;
-                case SqlDbType.SmallDateTime: return s_metaSmallDateTime;
-                case SqlDbType.SmallInt: return s_metaSmallInt;
-                case SqlDbType.SmallMoney: return s_metaSmallMoney;
-                case SqlDbType.Text: return MetaText;
-                case SqlDbType.Timestamp: return s_metaTimestamp;
-                case SqlDbType.TinyInt: return s_metaTinyInt;
-                case SqlDbType.VarBinary: return MetaVarBinary;
-                case SqlDbType.VarChar: return s_metaVarChar;
-                case SqlDbType.Variant: return s_metaVariant;
-                case (SqlDbType)TdsEnums.SmallVarBinary: return s_metaSmallVarBinary;
-                case SqlDbType.Xml: return MetaXml;
-                case SqlDbType.Udt: return MetaUdt;
-                case SqlDbType.Structured:
-                    if (isMultiValued)
-                    {
-                        return s_metaTable;
-                    }
-                    else
-                    {
-                        return s_metaSUDT;
-                    }
-                case SqlDbType.Date: return s_metaDate;
-                case SqlDbType.Time: return MetaTime;
-                case SqlDbType.DateTime2: return s_metaDateTime2;
-                case SqlDbType.DateTimeOffset: return MetaDateTimeOffset;
-                default: throw SQL.InvalidSqlDbType(target);
-            }
-        }
-
-        //
-        // map DbType to MetaType class
-        //
-        internal static MetaType GetMetaTypeFromDbType(DbType target)
-        {
-            // if we can't map it, we need to throw
-            switch (target)
-            {
-                case DbType.AnsiString: return s_metaVarChar;
-                case DbType.AnsiStringFixedLength: return s_metaChar;
-                case DbType.Binary: return MetaVarBinary;
-                case DbType.Byte: return s_metaTinyInt;
-                case DbType.Boolean: return s_metaBit;
-                case DbType.Currency: return s_metaMoney;
-                case DbType.Date:
-                case DbType.DateTime: return s_metaDateTime;
-                case DbType.Decimal: return MetaDecimal;
-                case DbType.Double: return s_metaFloat;
-                case DbType.Guid: return s_metaUniqueId;
-                case DbType.Int16: return s_metaSmallInt;
-                case DbType.Int32: return s_metaInt;
-                case DbType.Int64: return s_metaBigInt;
-                case DbType.Object: return s_metaVariant;
-                case DbType.Single: return s_metaReal;
-                case DbType.String: return MetaNVarChar;
-                case DbType.StringFixedLength: return s_metaNChar;
-                case DbType.Time: return s_metaDateTime;
-                case DbType.Xml: return MetaXml;
-                case DbType.DateTime2: return s_metaDateTime2;
-                case DbType.DateTimeOffset: return MetaDateTimeOffset;
-                case DbType.SByte:                  // unsupported
-                case DbType.UInt16:
-                case DbType.UInt32:
-                case DbType.UInt64:
-                case DbType.VarNumeric:
-                default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out
-            }
-        }
-
-        internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt)
-        {
-            // if we can't map it, we need to throw
-            switch (mt.SqlDbType)
-            {
-                case SqlDbType.VarBinary:
-                case SqlDbType.Binary:
-                    return MetaMaxVarBinary;
-                case SqlDbType.VarChar:
-                case SqlDbType.Char:
-                    return MetaMaxVarChar;
-                case SqlDbType.NVarChar:
-                case SqlDbType.NChar:
-                    return MetaMaxNVarChar;
-                case SqlDbType.Udt:
-                    return s_metaMaxUdt;
-                default:
-                    return mt;
-            }
-        }
-
-        //
-        // map COM+ Type to MetaType class
-        //
-        internal static MetaType GetMetaTypeFromType(Type dataType)
-        {
-            return GetMetaTypeFromValue(dataType, null, false, true);
-        }
-
-        internal static MetaType GetMetaTypeFromValue(object value, bool streamAllowed = true)
-        {
-            return GetMetaTypeFromValue(value.GetType(), value, true, streamAllowed);
-        }
-
-        private static MetaType GetMetaTypeFromValue(Type dataType, object value, bool inferLen, bool streamAllowed)
-        {
-            switch (Type.GetTypeCode(dataType))
-            {
-                case TypeCode.Empty:
-                    throw ADP.InvalidDataType(TypeCode.Empty);
-                case TypeCode.Object:
-                    if (dataType == typeof(byte[]))
-                    {
-                        // Must not default to image if inferLen is false
-                        if (!inferLen || ((byte[])value).Length <= TdsEnums.TYPE_SIZE_LIMIT)
-                        {
-                            return MetaVarBinary;
-                        }
-                        else
-                        {
-                            return MetaImage;
-                        }
-                    }
-                    else if (dataType == typeof(System.Guid))
-                    {
-                        return s_metaUniqueId;
-                    }
-                    else if (dataType == typeof(object))
-                    {
-                        return s_metaVariant;
-                    } // check sql types now
-                    else if (dataType == typeof(SqlBinary))
-                        return MetaVarBinary;
-                    else if (dataType == typeof(SqlBoolean))
-                        return s_metaBit;
-                    else if (dataType == typeof(SqlByte))
-                        return s_metaTinyInt;
-                    else if (dataType == typeof(SqlBytes))
-                        return MetaVarBinary;
-                    else if (dataType == typeof(SqlChars))
-                        return MetaNVarChar;
-                    else if (dataType == typeof(SqlDateTime))
-                        return s_metaDateTime;
-                    else if (dataType == typeof(SqlDouble))
-                        return s_metaFloat;
-                    else if (dataType == typeof(SqlGuid))
-                        return s_metaUniqueId;
-                    else if (dataType == typeof(SqlInt16))
-                        return s_metaSmallInt;
-                    else if (dataType == typeof(SqlInt32))
-                        return s_metaInt;
-                    else if (dataType == typeof(SqlInt64))
-                        return s_metaBigInt;
-                    else if (dataType == typeof(SqlMoney))
-                        return s_metaMoney;
-                    else if (dataType == typeof(SqlDecimal))
-                        return MetaDecimal;
-                    else if (dataType == typeof(SqlSingle))
-                        return s_metaReal;
-                    else if (dataType == typeof(SqlXml))
-                        return MetaXml;
-                    else if (dataType == typeof(SqlString))
-                    {
-                        return ((inferLen && !((SqlString)value).IsNull)
-                            ? PromoteStringType(((SqlString)value).Value)
-                            : MetaNVarChar);
-                    }
-                    else if (dataType == typeof(IEnumerable<DbDataRecord>) || dataType == typeof(DataTable))
-                    {
-                        return s_metaTable;
-                    }
-                    else if (dataType == typeof(TimeSpan))
-                    {
-                        return MetaTime;
-                    }
-                    else if (dataType == typeof(DateTimeOffset))
-                    {
-                        return MetaDateTimeOffset;
-                    }
-                    else
-                    {
-                        // UDT ?
-                        SqlUdtInfo attribs = SqlUdtInfo.TryGetFromType(dataType);
-                        if (attribs != null)
-                        {
-                            return MetaUdt;
-                        }
-                        if (streamAllowed)
-                        {
-                            // Derived from Stream ?
-                            if (typeof(Stream).IsAssignableFrom(dataType))
-                            {
-                                return MetaVarBinary;
-                            }
-                            // Derived from TextReader ?
-                            else if (typeof(TextReader).IsAssignableFrom(dataType))
-                            {
-                                return MetaNVarChar;
-                            }
-                            // Derived from XmlReader ?
-                            else if (typeof(System.Xml.XmlReader).IsAssignableFrom(dataType))
-                            {
-                                return MetaXml;
-                            }
-                        }
-                    }
-                    throw ADP.UnknownDataType(dataType);
-
-                case TypeCode.DBNull:
-                    throw ADP.InvalidDataType(TypeCode.DBNull);
-                case TypeCode.Boolean:
-                    return s_metaBit;
-                case TypeCode.Char:
-                    throw ADP.InvalidDataType(TypeCode.Char);
-                case TypeCode.SByte:
-                    throw ADP.InvalidDataType(TypeCode.SByte);
-                case TypeCode.Byte:
-                    return s_metaTinyInt;
-                case TypeCode.Int16:
-                    return s_metaSmallInt;
-                case TypeCode.UInt16:
-                    throw ADP.InvalidDataType(TypeCode.UInt16);
-                case TypeCode.Int32:
-                    return s_metaInt;
-                case TypeCode.UInt32:
-                    throw ADP.InvalidDataType(TypeCode.UInt32);
-                case TypeCode.Int64:
-                    return s_metaBigInt;
-                case TypeCode.UInt64:
-                    throw ADP.InvalidDataType(TypeCode.UInt64);
-                case TypeCode.Single:
-                    return s_metaReal;
-                case TypeCode.Double:
-                    return s_metaFloat;
-                case TypeCode.Decimal:
-                    return MetaDecimal;
-                case TypeCode.DateTime:
-                    return s_metaDateTime;
-                case TypeCode.String:
-                    return (inferLen ? PromoteStringType((string)value) : MetaNVarChar);
-                default:
-                    throw ADP.UnknownDataTypeCode(dataType, Type.GetTypeCode(dataType));
-            }
-        }
-
-        internal static object GetNullSqlValue(Type sqlType)
-        {
-            if (sqlType == typeof(SqlSingle)) return SqlSingle.Null;
-            else if (sqlType == typeof(SqlString)) return SqlString.Null;
-            else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null;
-            else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null;
-            else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null;
-            else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null;
-            else if (sqlType == typeof(SqlByte)) return SqlByte.Null;
-            else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null;
-            else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null;
-            else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null;
-            else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null;
-            else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null;
-            else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null;
-            else if (sqlType == typeof(SqlXml)) return SqlXml.Null;
-            else if (sqlType == typeof(object)) return DBNull.Value;
-            else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value;
-            else if (sqlType == typeof(DataTable)) return DBNull.Value;
-            else if (sqlType == typeof(DateTime)) return DBNull.Value;
-            else if (sqlType == typeof(TimeSpan)) return DBNull.Value;
-            else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value;
-            else
-            {
-                Debug.Fail("Unknown SqlType!");
-                return DBNull.Value;
-            }
-        }
-
-        internal static MetaType PromoteStringType(string s)
-        {
-            int len = s.Length;
-
-            if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT)
-            {
-                return s_metaVarChar; // try as var char since we can send a 8K characters
-            }
-            return MetaNVarChar; // send 4k chars, but send as unicode
-        }
-
-        internal static object GetComValueFromSqlVariant(object sqlVal)
-        {
-            object comVal = null;
-
-            if (ADP.IsNull(sqlVal))
-                return comVal;
-
-            if (sqlVal is SqlSingle)
-                comVal = ((SqlSingle)sqlVal).Value;
-            else if (sqlVal is SqlString)
-                comVal = ((SqlString)sqlVal).Value;
-            else if (sqlVal is SqlDouble)
-                comVal = ((SqlDouble)sqlVal).Value;
-            else if (sqlVal is SqlBinary)
-                comVal = ((SqlBinary)sqlVal).Value;
-            else if (sqlVal is SqlGuid)
-                comVal = ((SqlGuid)sqlVal).Value;
-            else if (sqlVal is SqlBoolean)
-                comVal = ((SqlBoolean)sqlVal).Value;
-            else if (sqlVal is SqlByte)
-                comVal = ((SqlByte)sqlVal).Value;
-            else if (sqlVal is SqlInt16)
-                comVal = ((SqlInt16)sqlVal).Value;
-            else if (sqlVal is SqlInt32)
-                comVal = ((SqlInt32)sqlVal).Value;
-            else if (sqlVal is SqlInt64)
-                comVal = ((SqlInt64)sqlVal).Value;
-            else if (sqlVal is SqlDecimal)
-                comVal = ((SqlDecimal)sqlVal).Value;
-            else if (sqlVal is SqlDateTime)
-                comVal = ((SqlDateTime)sqlVal).Value;
-            else if (sqlVal is SqlMoney)
-                comVal = ((SqlMoney)sqlVal).Value;
-            else if (sqlVal is SqlXml)
-                comVal = ((SqlXml)sqlVal).Value;
-            else
-            {
-                AssertIsUserDefinedTypeInstance(sqlVal, "unknown SqlType class stored in sqlVal");
-            }
-
-
-            return comVal;
-        }
-
-        /// <summary>
-        /// Assert that the supplied object is an instance of a SQL User-Defined Type (UDT).
-        /// </summary>
-        /// <param name="sqlValue">Object instance to be tested.</param>
-        /// <remarks>
-        /// This method is only compiled with debug builds, and it a helper method for the GetComValueFromSqlVariant method defined in this class.
-        ///
-        /// The presence of the SqlUserDefinedTypeAttribute on the object's type
-        /// is used to determine if the object is a UDT instance (if present it is a UDT, else it is not).
-        /// </remarks>
-        /// <exception cref="NullReferenceException">
-        /// If sqlValue is null.  Callers must ensure the object is non-null.
-        /// </exception>
-        [Conditional("DEBUG")]
-        private static void AssertIsUserDefinedTypeInstance(object sqlValue, string failedAssertMessage)
-        {
-            Type type = sqlValue.GetType();
-            Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[] attributes = (Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[])type.GetCustomAttributes(typeof(Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute), true);
-
-            Debug.Assert(attributes.Length > 0, failedAssertMessage);
-        }
-
-        // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2.
-        //          With these types the values should be used directly as CLR types instead of being converted to a SqlValue
-        internal static object GetSqlValueFromComVariant(object comVal)
-        {
-            object sqlVal = null;
-            if ((null != comVal) && (DBNull.Value != comVal))
-            {
-                if (comVal is float)
-                    sqlVal = new SqlSingle((float)comVal);
-                else if (comVal is string)
-                    sqlVal = new SqlString((string)comVal);
-                else if (comVal is double)
-                    sqlVal = new SqlDouble((double)comVal);
-                else if (comVal is byte[])
-                    sqlVal = new SqlBinary((byte[])comVal);
-                else if (comVal is char)
-                    sqlVal = new SqlString(((char)comVal).ToString());
-                else if (comVal is char[])
-                    sqlVal = new SqlChars((char[])comVal);
-                else if (comVal is System.Guid)
-                    sqlVal = new SqlGuid((Guid)comVal);
-                else if (comVal is bool)
-                    sqlVal = new SqlBoolean((bool)comVal);
-                else if (comVal is byte)
-                    sqlVal = new SqlByte((byte)comVal);
-                else if (comVal is short)
-                    sqlVal = new SqlInt16((short)comVal);
-                else if (comVal is int)
-                    sqlVal = new SqlInt32((int)comVal);
-                else if (comVal is long)
-                    sqlVal = new SqlInt64((long)comVal);
-                else if (comVal is decimal)
-                    sqlVal = new SqlDecimal((decimal)comVal);
-                else if (comVal is DateTime)
-                {
-                    // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method.
-                    sqlVal = new SqlDateTime((DateTime)comVal);
-                }
-                else if (comVal is XmlReader)
-                    sqlVal = new SqlXml((XmlReader)comVal);
-                else if (comVal is TimeSpan || comVal is DateTimeOffset)
-                    sqlVal = comVal;
-#if DEBUG
-                else
-                    Debug.Fail("unknown SqlType class stored in sqlVal");
-#endif
-            }
-            return sqlVal;
-        }
-
-        internal static SqlDbType GetSqlDbTypeFromOleDbType(short dbType, string typeName)
-        {
-            // OleDbTypes not supported
-            return SqlDbType.Variant;
-        }
-
-        internal static MetaType GetSqlDataType(int tdsType, uint userType, int length)
-        {
-            switch (tdsType)
-            {
-                case TdsEnums.SQLMONEYN: return ((4 == length) ? s_metaSmallMoney : s_metaMoney);
-                case TdsEnums.SQLDATETIMN: return ((4 == length) ? s_metaSmallDateTime : s_metaDateTime);
-                case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt));
-                case TdsEnums.SQLFLTN: return ((4 == length) ? s_metaReal : s_metaFloat);
-                case TdsEnums.SQLTEXT: return MetaText;
-                case TdsEnums.SQLVARBINARY: return s_metaSmallVarBinary;
-                case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary;
-
-                case TdsEnums.SQLVARCHAR:
-                case TdsEnums.SQLBIGVARCHAR: return s_metaVarChar;
-
-                case TdsEnums.SQLBINARY:
-                case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary);
-
-                case TdsEnums.SQLIMAGE: return MetaImage;
-
-                case TdsEnums.SQLCHAR:
-                case TdsEnums.SQLBIGCHAR: return s_metaChar;
-
-                case TdsEnums.SQLINT1: return s_metaTinyInt;
-
-                case TdsEnums.SQLBIT:
-                case TdsEnums.SQLBITN: return s_metaBit;
-
-                case TdsEnums.SQLINT2: return s_metaSmallInt;
-                case TdsEnums.SQLINT4: return s_metaInt;
-                case TdsEnums.SQLINT8: return s_metaBigInt;
-                case TdsEnums.SQLMONEY: return s_metaMoney;
-                case TdsEnums.SQLDATETIME: return s_metaDateTime;
-                case TdsEnums.SQLFLT8: return s_metaFloat;
-                case TdsEnums.SQLFLT4: return s_metaReal;
-                case TdsEnums.SQLMONEY4: return s_metaSmallMoney;
-                case TdsEnums.SQLDATETIM4: return s_metaSmallDateTime;
-
-                case TdsEnums.SQLDECIMALN:
-                case TdsEnums.SQLNUMERICN: return MetaDecimal;
-
-                case TdsEnums.SQLUNIQUEID: return s_metaUniqueId;
-                case TdsEnums.SQLNCHAR: return s_metaNChar;
-                case TdsEnums.SQLNVARCHAR: return MetaNVarChar;
-                case TdsEnums.SQLNTEXT: return MetaNText;
-                case TdsEnums.SQLVARIANT: return s_metaVariant;
-                case TdsEnums.SQLUDT: return MetaUdt;
-                case TdsEnums.SQLXMLTYPE: return MetaXml;
-                case TdsEnums.SQLTABLE: return s_metaTable;
-                case TdsEnums.SQLDATE: return s_metaDate;
-                case TdsEnums.SQLTIME: return MetaTime;
-                case TdsEnums.SQLDATETIME2: return s_metaDateTime2;
-                case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset;
-
-                case TdsEnums.SQLVOID:
-                default:
-                    Debug.Fail("Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture));
-                    throw SQL.InvalidSqlDbType((SqlDbType)tdsType);
-            }
-        }
-
-        internal static MetaType GetDefaultMetaType()
-        {
-            return MetaNVarChar;
-        }
-
-        // Converts an XmlReader into String
-        internal static string GetStringFromXml(XmlReader xmlreader)
-        {
-            SqlXml sxml = new SqlXml(xmlreader);
-            return sxml.Value;
-        }
-
-        private static readonly MetaType s_metaBigInt = new MetaType
-            (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(long), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0);
-
-        private static readonly MetaType s_metaFloat = new MetaType
-            (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0);
-
-        private static readonly MetaType s_metaReal = new MetaType
-            (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(float), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0);
-
-        // MetaBinary has two bytes of properties for binary and varbinary
-        // 2 byte maxlen
-        private static readonly MetaType s_metaBinary = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2);
-
-        // Syntactic sugar for the user...timestamps are 8-byte fixed length binary columns
-        private static readonly MetaType s_metaTimestamp = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2);
-
-        internal static readonly MetaType MetaVarBinary = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2);
-
-        internal static readonly MetaType MetaMaxVarBinary = new MetaType
-            (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2);
-
-        // We have an internal type for smallvarbinarys stored on TdsEnums. We
-        // store on TdsEnums instead of SqlDbType because we do not want to expose
-        // this type to the user.
-        private static readonly MetaType s_metaSmallVarBinary = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, string.Empty, typeof(byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2);
-
-        internal static readonly MetaType MetaImage = new MetaType
-            (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0);
-
-        private static readonly MetaType s_metaBit = new MetaType
-            (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(bool), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0);
-
-        private static readonly MetaType s_metaTinyInt = new MetaType
-            (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0);
-
-        private static readonly MetaType s_metaSmallInt = new MetaType
-            (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(short), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0);
-
-        private static readonly MetaType s_metaInt = new MetaType
-            (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(int), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0);
-
-        // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar
-        // 5 byte tds collation
-        // 2 byte maxlen
-        private static readonly MetaType s_metaChar = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(string), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7);
-
-        private static readonly MetaType s_metaVarChar = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(string), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7);
-
-        internal static readonly MetaType MetaMaxVarChar = new MetaType
-            (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(string), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7);
-
-        internal static readonly MetaType MetaText = new MetaType
-            (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(string), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0);
-
-        // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar
-        // 5 byte tds collation
-        // 2 byte maxlen
-        private static readonly MetaType s_metaNChar = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(string), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7);
-
-        internal static readonly MetaType MetaNVarChar = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(string), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7);
-
-        internal static readonly MetaType MetaMaxNVarChar = new MetaType
-            (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(string), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7);
-
-        internal static readonly MetaType MetaNText = new MetaType
-            (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(string), typeof(SqlString), SqlDbType.NText, DbType.String, 7);
-
-        // MetaVariant has two bytes of properties for numeric/decimal types
-        // 1 byte precision
-        // 1 byte scale
-        internal static readonly MetaType MetaDecimal = new MetaType
-            (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2);
-
-        internal static readonly MetaType MetaXml = new MetaType
-            (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(string), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0);
-
-        private static readonly MetaType s_metaDateTime = new MetaType
-            (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0);
-
-        private static readonly MetaType s_metaSmallDateTime = new MetaType
-            (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0);
-
-        private static readonly MetaType s_metaMoney = new MetaType
-            (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0);
-
-        private static readonly MetaType s_metaSmallMoney = new MetaType
-            (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0);
-
-        private static readonly MetaType s_metaUniqueId = new MetaType
-            (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0);
-
-        private static readonly MetaType s_metaVariant = new MetaType
-            (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(object), typeof(object), SqlDbType.Variant, DbType.Object, 0);
-
-        internal static readonly MetaType MetaUdt = new MetaType
-            (255, 255, -1, false, false, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(object), typeof(object), SqlDbType.Udt, DbType.Object, 0);
-
-        private static readonly MetaType s_metaMaxUdt = new MetaType
-            (255, 255, -1, false, true, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(object), typeof(object), SqlDbType.Udt, DbType.Object, 0);
-
-        private static readonly MetaType s_metaTable = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0);
-
-        private static readonly MetaType s_metaSUDT = new MetaType
-            (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0);
-
-        private static readonly MetaType s_metaDate = new MetaType
-            (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0);
-
-        internal static readonly MetaType MetaTime = new MetaType
-            (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1);
-
-        private static readonly MetaType s_metaDateTime2 = new MetaType
-            (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1);
-
-        internal static readonly MetaType MetaDateTimeOffset = new MetaType
-            (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1);
-
-        public static TdsDateTime FromDateTime(DateTime dateTime, byte cb)
-        {
-            SqlDateTime sqlDateTime;
-            TdsDateTime tdsDateTime = default;
-
-            Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!");
-
-            if (cb == 8)
-            {
-                sqlDateTime = new SqlDateTime(dateTime);
-                tdsDateTime.time = sqlDateTime.TimeTicks;
-            }
-            else
-            {
-                // note that smalldatetime is days & minutes.
-                // Adding 30 seconds ensures proper roundup if the seconds are >= 30
-                // The AddSeconds function handles eventual carryover
-                sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30));
-                tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute;
-            }
-            tdsDateTime.days = sqlDateTime.DayTicks;
-            return tdsDateTime;
-        }
-
-
-        public static DateTime ToDateTime(int sqlDays, int sqlTime, int length)
-        {
-            if (length == 4)
-            {
-                return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value;
-            }
-            else
-            {
-                Debug.Assert(length == 8, "invalid length for DateTime");
-                return new SqlDateTime(sqlDays, sqlTime).Value;
-            }
-        }
-
-        internal static int GetTimeSizeFromScale(byte scale)
-        {
-            if (scale <= 2)
-                return 3;
-
-            if (scale <= 4)
-                return 4;
-
-            return 5;
-        }
-
-        //
-        // please leave string sorted alphabetically
-        // note that these names should only be used in the context of parameters.  We always send over BIG* and nullable types for SQL Server
-        //
-        private static class MetaTypeName
-        {
-            public const string BIGINT = "bigint";
-            public const string BINARY = "binary";
-            public const string BIT = "bit";
-            public const string CHAR = "char";
-            public const string DATETIME = "datetime";
-            public const string DECIMAL = "decimal";
-            public const string FLOAT = "float";
-            public const string IMAGE = "image";
-            public const string INT = "int";
-            public const string MONEY = "money";
-            public const string NCHAR = "nchar";
-            public const string NTEXT = "ntext";
-            public const string NVARCHAR = "nvarchar";
-            public const string REAL = "real";
-            public const string ROWGUID = "uniqueidentifier";
-            public const string SMALLDATETIME = "smalldatetime";
-            public const string SMALLINT = "smallint";
-            public const string SMALLMONEY = "smallmoney";
-            public const string TEXT = "text";
-            public const string TIMESTAMP = "timestamp";
-            public const string TINYINT = "tinyint";
-            public const string UDT = "udt";
-            public const string VARBINARY = "varbinary";
-            public const string VARCHAR = "varchar";
-            public const string VARIANT = "sql_variant";
-            public const string XML = "xml";
-            public const string TABLE = "table";
-            public const string DATE = "date";
-            public const string TIME = "time";
-            public const string DATETIME2 = "datetime2";
-            public const string DATETIMEOFFSET = "datetimeoffset";
-        }
-    }
-
-    //
-    // note: it is the client's responsibility to know what size date time they are working with
-    //
-    internal struct TdsDateTime
-    {
-        public int days;  // offset in days from 1/1/1900
-        //     private UInt32 time;  // if smalldatetime, this is # of minutes since midnight
-        // otherwise: # of 1/300th of a second since midnight
-        public int time;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlError.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlError.cs
deleted file mode 100644 (file)
index f8f1ce3..0000000
+++ /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.
-
-
-
-//------------------------------------------------------------------------------
-
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlError
-    {
-        private readonly string _source = TdsEnums.SQL_PROVIDER_NAME;
-        private readonly int _number;
-        private readonly byte _state;
-        private readonly byte _errorClass;
-        private readonly string _server;
-        private readonly string _message;
-        private readonly string _procedure;
-        private readonly int _lineNumber;
-        private readonly int _win32ErrorCode;
-        private readonly 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;
-        }
-
-        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;
-        }
-
-        // There is no exception stack included 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 typeof(SqlError).ToString() + ": " + _message; // since this is sealed so we can change GetType to typeof
-        }
-
-        public string Source
-        {
-            get { return _source; }
-        }
-
-        public int Number
-        {
-            get { return _number; }
-        }
-
-        public byte State
-        {
-            get { return _state; }
-        }
-
-        public byte Class
-        {
-            get { return _errorClass; }
-        }
-
-        public string Server
-        {
-            get { return _server; }
-        }
-
-        public string Message
-        {
-            get { return _message; }
-        }
-
-        public string Procedure
-        {
-            get { return _procedure; }
-        }
-
-        public int LineNumber
-        {
-            get { return _lineNumber; }
-        }
-
-        internal int Win32ErrorCode
-        {
-            get { return _win32ErrorCode; }
-        }
-
-        internal Exception Exception
-        {
-            get { return _exception; }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlErrorCollection.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlErrorCollection.cs
deleted file mode 100644 (file)
index 8a06a73..0000000
+++ /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.Collections;
-using System.Collections.Generic;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlErrorCollection : ICollection
-    {
-        // Ideally this would be typed as List<SqlError>, but that would make the non-generic
-        // CopyTo behave differently than the full framework (which uses ArrayList), throwing
-        // ArgumentException instead of the expected InvalidCastException for incompatible types.
-        // Instead, we use List<object>, which makes the non-generic CopyTo behave like
-        // ArrayList.CopyTo.
-        private readonly List<object> _errors = new List<object>();
-
-        internal SqlErrorCollection() { }
-
-        public void CopyTo(Array array, int index) => ((ICollection)_errors).CopyTo(array, index);
-
-        public void CopyTo(SqlError[] array, int index) => _errors.CopyTo(array, index);
-
-        public int Count => _errors.Count;
-
-        object ICollection.SyncRoot => this;
-
-        bool ICollection.IsSynchronized => false;
-
-        public SqlError this[int index] => (SqlError)_errors[index];
-
-        public IEnumerator GetEnumerator() => _errors.GetEnumerator();
-
-        internal void Add(SqlError error) => _errors.Add(error);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlException.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlException.cs
deleted file mode 100644 (file)
index 85ce165..0000000
+++ /dev/null
@@ -1,229 +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.ComponentModel;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.Serialization;
-using System.Text; // StringBuilder
-
-namespace System.Data.SqlClient
-{
-    [Serializable]
-    [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
-    public sealed partial class SqlException : System.Data.Common.DbException
-    {
-        private const string OriginalClientConnectionIdKey = "OriginalClientConnectionId";
-        private const string RoutingDestinationKey = "RoutingDestination";
-        private const int SqlExceptionHResult = unchecked((int)0x80131904);
-
-        private SqlErrorCollection _errors;
-        private Guid _clientConnectionId = Guid.Empty;
-
-        private SqlException(string message, SqlErrorCollection errorCollection, Exception innerException, Guid conId) : base(message, innerException)
-        {
-            HResult = SqlExceptionHResult;
-            _errors = errorCollection;
-            _clientConnectionId = conId;
-        }
-
-        private SqlException(SerializationInfo si, StreamingContext sc) : base(si, sc)
-        {
-            HResult = SqlExceptionHResult;
-            foreach (SerializationEntry siEntry in si)
-            {
-                if ("ClientConnectionId" == siEntry.Name)
-                {
-                    _clientConnectionId = (Guid)siEntry.Value;
-                    break;
-                }
-            }
-        }
-
-        public override void GetObjectData(SerializationInfo si, StreamingContext context)
-        {
-            base.GetObjectData(si, context);
-            si.AddValue("Errors", null); // Not specifying type to enable serialization of null value of non-serializable type
-            si.AddValue("ClientConnectionId", _clientConnectionId, typeof(Guid));
-
-            // Writing sqlerrors to base exception data table
-            for (int i = 0; i < Errors.Count; i++)
-            {
-                string key = "SqlError " + (i + 1);
-                if (Data.Contains(key))
-                {
-                    Data.Remove(key);
-                }
-                Data.Add(key, Errors[i].ToString());
-            }
-        }
-
-        // runtime will call even if private...
-        public SqlErrorCollection Errors
-        {
-            get
-            {
-                if (_errors == null)
-                {
-                    _errors = new SqlErrorCollection();
-                }
-                return _errors;
-            }
-        }
-
-        public Guid ClientConnectionId
-        {
-            get
-            {
-                return _clientConnectionId;
-            }
-        }
-
-
-        public byte Class
-        {
-            get { return Errors.Count > 0 ? this.Errors[0].Class : default; }
-        }
-
-        public int LineNumber
-        {
-            get { return Errors.Count > 0 ? Errors[0].LineNumber : default; }
-        }
-
-        public int Number
-        {
-            get { return Errors.Count > 0 ? Errors[0].Number : default; }
-        }
-
-        public string Procedure
-        {
-            get { return Errors.Count > 0 ? Errors[0].Procedure : default; }
-        }
-
-        public string Server
-        {
-            get { return Errors.Count > 0 ? Errors[0].Server : default; }
-        }
-
-        public byte State
-        {
-            get { return Errors.Count > 0 ? Errors[0].State : default; }
-        }
-
-        public override string Source
-        {
-            get { return Errors.Count > 0 ? Errors[0].Source : default; }
-        }
-
-        public override string ToString()
-        {
-            StringBuilder sb = new StringBuilder(base.ToString());
-            sb.AppendLine();
-            sb.AppendFormat(SQLMessage.ExClientConnectionId(), _clientConnectionId);
-
-            // Append the error number, state and class if the server provided it
-            if (Errors.Count > 0 && Number != 0)
-            {
-                sb.AppendLine();
-                sb.AppendFormat(SQLMessage.ExErrorNumberStateClass(), Number, State, Class);
-            }
-
-            // If routed, include the original client connection id
-            if (Data.Contains(OriginalClientConnectionIdKey))
-            {
-                sb.AppendLine();
-                sb.AppendFormat(SQLMessage.ExOriginalClientConnectionId(), Data[OriginalClientConnectionIdKey]);
-            }
-
-            // If routed, provide the routing destination
-            if (Data.Contains(RoutingDestinationKey))
-            {
-                sb.AppendLine();
-                sb.AppendFormat(SQLMessage.ExRoutingDestination(), Data[RoutingDestinationKey]);
-            }
-
-            return sb.ToString();
-        }
-
-        internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion)
-        {
-            return CreateException(errorCollection, serverVersion, Guid.Empty);
-        }
-
-        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);
-
-            if (internalConnection != null)
-            {
-                if ((internalConnection.OriginalClientConnectionId != Guid.Empty) && (internalConnection.OriginalClientConnectionId != internalConnection.ClientConnectionId))
-                {
-                    exception.Data.Add(OriginalClientConnectionIdKey, internalConnection.OriginalClientConnectionId);
-                }
-
-                if (!string.IsNullOrEmpty(internalConnection.RoutingDestination))
-                {
-                    exception.Data.Add(RoutingDestinationKey, internalConnection.RoutingDestination);
-                }
-            }
-
-            return exception;
-        }
-
-        internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, Guid conId, Exception innerException = null)
-        {
-            Debug.Assert(null != errorCollection && errorCollection.Count > 0, "no errorCollection?");
-
-            StringBuilder message = new StringBuilder();
-            for (int i = 0; i < errorCollection.Count; i++)
-            {
-                if (i > 0)
-                {
-                    message.Append(Environment.NewLine);
-                }
-                message.Append(errorCollection[i].Message);
-            }
-
-            if (innerException == null && errorCollection[0].Win32ErrorCode != 0 && errorCollection[0].Win32ErrorCode != -1)
-            {
-                innerException = new Win32Exception(errorCollection[0].Win32ErrorCode);
-            }
-
-            SqlException exception = new SqlException(message.ToString(), errorCollection, innerException, conId);
-
-            exception.Data.Add("HelpLink.ProdName", "Microsoft SQL Server");
-
-            if (!string.IsNullOrEmpty(serverVersion))
-            {
-                exception.Data.Add("HelpLink.ProdVer", serverVersion);
-            }
-            exception.Data.Add("HelpLink.EvtSrc", "MSSQLServer");
-            exception.Data.Add("HelpLink.EvtID", errorCollection[0].Number.ToString(CultureInfo.InvariantCulture));
-            exception.Data.Add("HelpLink.BaseHelpUrl", "https://go.microsoft.com/fwlink");
-            exception.Data.Add("HelpLink.LinkId", "20476");
-
-            return exception;
-        }
-
-        internal SqlException InternalClone()
-        {
-            SqlException exception = new SqlException(Message, _errors, InnerException, _clientConnectionId);
-            if (this.Data != null)
-                foreach (DictionaryEntry entry in this.Data)
-                    exception.Data.Add(entry.Key, entry.Value);
-            exception._doNotReconnect = this._doNotReconnect;
-            return exception;
-        }
-
-        // Do not serialize this field! It is used to indicate that no reconnection attempts are required
-        internal bool _doNotReconnect = false;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlFileStream.Unsupported.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlFileStream.Unsupported.cs
deleted file mode 100644 (file)
index 4a7cf17..0000000
+++ /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.IO;
-
-namespace System.Data.SqlTypes
-{
-    public sealed partial class SqlFileStream : System.IO.Stream
-    {
-        public SqlFileStream(string path, byte[] transactionContext, FileAccess access)
-        {
-            throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported);
-        }
-
-        public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize)
-        {
-            throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported);
-        }
-
-        public string Name { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } }
-        public byte[] TransactionContext { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } }
-        public override bool CanRead { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } }
-        public override bool CanSeek { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } }
-        public override bool CanWrite { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } }
-        public override long Length { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } }
-        public override long Position { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } set { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } }
-        public override void Flush() { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); }
-        public override int Read(byte[] buffer, int offset, int count) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); }
-        public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); }
-        public override void SetLength(long value) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); }
-        public override void Write(byte[] buffer, int offset, int count) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlFileStream.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlFileStream.Windows.cs
deleted file mode 100644 (file)
index 2afff43..0000000
+++ /dev/null
@@ -1,659 +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.Data.Common;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
-using Microsoft.Win32.SafeHandles;
-using System.Buffers;
-
-namespace System.Data.SqlTypes
-{
-    public sealed partial class SqlFileStream : System.IO.Stream
-    {
-        // NOTE: if we ever unseal this class, be sure to specify the Name, SafeFileHandle, and
-        // TransactionContext accessors as virtual methods. Doing so now on a sealed class
-        // generates a compiler error (CS0549)
-
-        // from System.IO.FileStream implementation
-        // DefaultBufferSize = 4096;
-        // SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
-        // potential exceptions during Close/Finalization. Since System.IO.FileStream will
-        // not allow for a zero byte buffer, we'll create a one byte buffer which, in normal
-        // usage, will not be used and the user buffer will automatically flush directly to
-        // the disk cache. In pathological scenarios where the client is writing a single
-        // byte at a time, we'll explicitly call flush ourselves.
-        internal const int DefaultBufferSize = 1;
-
-        private const ushort IoControlCodeFunctionCode = 2392;
-        private const int ERROR_MR_MID_NOT_FOUND = 317;
-        #region Definitions from devioctl.h
-        private const ushort FILE_DEVICE_FILE_SYSTEM = 0x0009;
-        #endregion
-
-        private System.IO.FileStream _m_fs;
-        private string _m_path;
-        private byte[] _m_txn;
-        private bool _m_disposed;
-        private static readonly byte[] s_eaNameString = new byte[]
-        {
-            (byte)'F', (byte)'i', (byte)'l', (byte)'e', (byte)'s', (byte)'t', (byte)'r', (byte)'e', (byte)'a', (byte)'m', (byte)'_',
-            (byte)'T', (byte)'r', (byte)'a', (byte)'n', (byte)'s', (byte)'a', (byte)'c', (byte)'t', (byte)'i', (byte)'o', (byte)'n', (byte)'_',
-            (byte)'T', (byte)'a', (byte)'g', (byte) '\0'
-        };
-
-        public SqlFileStream(string path, byte[] transactionContext, FileAccess access) :
-            this(path, transactionContext, access, FileOptions.None, 0)
-        { }
-
-        public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize)
-        {
-            //-----------------------------------------------------------------
-            // precondition validation
-
-            if (transactionContext == null)
-                throw ADP.ArgumentNull("transactionContext");
-
-            if (path == null)
-                throw ADP.ArgumentNull("path");
-
-            //-----------------------------------------------------------------
-
-            _m_disposed = false;
-            _m_fs = null;
-
-            OpenSqlFileStream(path, transactionContext, access, options, allocationSize);
-
-            // only set internal state once the file has actually been successfully opened
-            Name = path;
-            TransactionContext = transactionContext;
-        }
-
-        #region destructor/dispose code
-
-        // NOTE: this destructor will only be called only if the Dispose
-        // method is not called by a client, giving the class a chance
-        // to finalize properly (i.e., free unmanaged resources)
-        ~SqlFileStream()
-        {
-            Dispose(false);
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            try
-            {
-                if (!_m_disposed)
-                {
-                    try
-                    {
-                        if (disposing)
-                        {
-                            if (_m_fs != null)
-                            {
-                                _m_fs.Close();
-                                _m_fs = null;
-                            }
-                        }
-                    }
-                    finally
-                    {
-                        _m_disposed = true;
-                    }
-                }
-            }
-            finally
-            {
-                base.Dispose(disposing);
-            }
-        }
-        #endregion
-
-        public string Name
-        {
-            get
-            {
-                // assert that path has been properly processed via GetFullPathInternal
-                // (e.g. m_path hasn't been set directly)
-                AssertPathFormat(_m_path);
-                return _m_path;
-            }
-            private set
-            {
-                // should be validated by callers of this method
-                Debug.Assert(value != null);
-                Debug.Assert(!_m_disposed);
-
-                _m_path = GetFullPathInternal(value);
-            }
-        }
-
-        public byte[] TransactionContext
-        {
-            get
-            {
-                if (_m_txn == null)
-                    return null;
-
-                return (byte[])_m_txn.Clone();
-            }
-            private set
-            {
-                // should be validated by callers of this method
-                Debug.Assert(value != null);
-                Debug.Assert(!_m_disposed);
-
-                _m_txn = (byte[])value.Clone();
-            }
-        }
-
-        #region System.IO.Stream methods
-
-        public override bool CanRead
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.CanRead;
-            }
-        }
-
-        // If CanSeek is false, Position, Seek, Length, and SetLength should throw.
-        public override bool CanSeek
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.CanSeek;
-            }
-        }
-
-        public override bool CanTimeout
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.CanTimeout;
-            }
-        }
-
-        public override bool CanWrite
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.CanWrite;
-            }
-        }
-
-        public override long Length
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.Length;
-            }
-        }
-
-        public override long Position
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.Position;
-            }
-            set
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                _m_fs.Position = value;
-            }
-        }
-
-        public override int ReadTimeout
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.ReadTimeout;
-            }
-            set
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                _m_fs.ReadTimeout = value;
-            }
-        }
-
-        public override int WriteTimeout
-        {
-            get
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                return _m_fs.WriteTimeout;
-            }
-            set
-            {
-                if (_m_disposed)
-                    throw ADP.ObjectDisposed(this);
-
-                _m_fs.WriteTimeout = value;
-            }
-        }
-
-        public override void Flush()
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            _m_fs.Flush();
-        }
-
-        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            return _m_fs.BeginRead(buffer, offset, count, callback, state);
-        }
-
-        public override int EndRead(IAsyncResult asyncResult)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            return _m_fs.EndRead(asyncResult);
-        }
-
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            IAsyncResult asyncResult = _m_fs.BeginWrite(buffer, offset, count, callback, state);
-
-            // SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
-            // potential exceptions during Close/Finalization. Since System.IO.FileStream will
-            // not allow for a zero byte buffer, we'll create a one byte buffer which, in normal
-            // usage, will not be used and the user buffer will automatically flush directly to
-            // the disk cache. In pathological scenarios where the client is writing a single
-            // byte at a time, we'll explicitly call flush ourselves.
-            if (count == 1)
-            {
-                // calling flush here will mimic the internal control flow of System.IO.FileStream
-                _m_fs.Flush();
-            }
-
-            return asyncResult;
-        }
-
-        public override void EndWrite(IAsyncResult asyncResult)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            _m_fs.EndWrite(asyncResult);
-        }
-
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            return _m_fs.Seek(offset, origin);
-        }
-
-        public override void SetLength(long value)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            _m_fs.SetLength(value);
-        }
-
-        public override int Read([In, Out] byte[] buffer, int offset, int count)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            return _m_fs.Read(buffer, offset, count);
-        }
-
-        public override int ReadByte()
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            return _m_fs.ReadByte();
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            _m_fs.Write(buffer, offset, count);
-
-            // SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
-            // potential exceptions during Close/Finalization. Since System.IO.FileStream will
-            // not allow for a zero byte buffer, we'll create a one byte buffer which, in normal
-            // usage, will cause System.IO.FileStream to utilize the user-supplied buffer and
-            // automatically flush the data directly to the disk cache. In pathological scenarios
-            // where the user is writing a single byte at a time, we'll explicitly call flush ourselves.
-            if (count == 1)
-            {
-                // calling flush here will mimic the internal control flow of System.IO.FileStream
-                _m_fs.Flush();
-            }
-        }
-
-        public override void WriteByte(byte value)
-        {
-            if (_m_disposed)
-                throw ADP.ObjectDisposed(this);
-
-            _m_fs.WriteByte(value);
-
-            // SQLBUVSTS# 193123 - disable lazy flushing of written data in order to prevent
-            // potential exceptions during Close/Finalization. Since our internal buffer is
-            // only a single byte in length, the provided user data will always be cached.
-            // As a result, we need to be sure to flush the data to disk ourselves.
-
-            // calling flush here will mimic the internal control flow of System.IO.FileStream
-            _m_fs.Flush();
-        }
-
-        #endregion
-
-        [Conditional("DEBUG")]
-        private static void AssertPathFormat(string path)
-        {
-            Debug.Assert(path != null);
-            Debug.Assert(path == path.Trim());
-            Debug.Assert(path.Length > 0);
-            Debug.Assert(path.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase));
-        }
-
-        private static string GetFullPathInternal(string path)
-        {
-            //-----------------------------------------------------------------
-            // precondition validation should be validated by callers of this method
-            // NOTE: if this method moves elsewhere, this assert should become an actual runtime check
-            // as the implicit assumptions here cannot be relied upon in an inter-class context
-            Debug.Assert(path != null);
-
-            // remove leading and trailing whitespace
-            path = path.Trim();
-            if (path.Length == 0)
-            {
-                throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidPath), "path");
-            }
-
-            // make sure path is not DOS device path
-            if (!path.StartsWith(@"\\") && !System.IO.PathInternal.IsDevice(path.AsSpan()))
-            {
-                throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidPath), "path");
-            }
-
-            // normalize the path
-            path = System.IO.Path.GetFullPath(path);
-
-            // make sure path is a UNC path
-            if (System.IO.PathInternal.IsDeviceUNC(path.AsSpan()))
-            {
-                throw ADP.Argument(SR.GetString(SR.SqlFileStream_PathNotValidDiskResource), "path");
-            }
-
-            return path;
-        }
-
-        private unsafe void OpenSqlFileStream
-            (
-                string sPath,
-                byte[] transactionContext,
-                System.IO.FileAccess access,
-                System.IO.FileOptions options,
-                long allocationSize
-            )
-        {
-            //-----------------------------------------------------------------
-            // precondition validation
-            // these should be checked by any caller of this method
-            // ensure we have validated and normalized the path before
-            Debug.Assert(sPath != null);
-            Debug.Assert(transactionContext != null);
-
-            if (access != System.IO.FileAccess.Read && access != System.IO.FileAccess.Write && access != System.IO.FileAccess.ReadWrite)
-                throw ADP.ArgumentOutOfRange("access");
-
-            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
-            if ((options & ~(System.IO.FileOptions.WriteThrough | System.IO.FileOptions.Asynchronous | System.IO.FileOptions.RandomAccess | System.IO.FileOptions.SequentialScan)) != 0)
-                throw ADP.ArgumentOutOfRange("options");
-
-            //-----------------------------------------------------------------
-            // normalize the provided path
-            // * compress path to remove any occurrences of '.' or '..'
-            // * trim whitespace from the beginning and end of the path
-            // * ensure that the path starts with '\\'
-            // * ensure that the path does not start with '\\.\'
-            sPath = GetFullPathInternal(sPath);
-
-            Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null;
-            Interop.NtDll.DesiredAccess nDesiredAccess = Interop.NtDll.DesiredAccess.FILE_READ_ATTRIBUTES | Interop.NtDll.DesiredAccess.SYNCHRONIZE;
-            Interop.NtDll.CreateOptions dwCreateOptions = 0;
-            Interop.NtDll.CreateDisposition dwCreateDisposition = 0;
-            System.IO.FileShare nShareAccess = System.IO.FileShare.None;
-
-            switch (access)
-            {
-                case System.IO.FileAccess.Read:
-
-                    nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_READ_DATA;
-                    nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
-                    dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OPEN;
-                    break;
-
-                case System.IO.FileAccess.Write:
-                    nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
-                    nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read;
-                    dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
-                    break;
-
-                case System.IO.FileAccess.ReadWrite:
-                default:
-                    // we validate the value of 'access' parameter in the beginning of this method
-                    Debug.Assert(access == System.IO.FileAccess.ReadWrite);
-
-                    nDesiredAccess |= Interop.NtDll.DesiredAccess.FILE_READ_DATA | Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
-                    nShareAccess = System.IO.FileShare.Delete | System.IO.FileShare.Read;
-                    dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
-                    break;
-            }
-
-            if ((options & System.IO.FileOptions.WriteThrough) != 0)
-            {
-                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_WRITE_THROUGH;
-            }
-
-            if ((options & System.IO.FileOptions.Asynchronous) == 0)
-            {
-                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT;
-            }
-
-            if ((options & System.IO.FileOptions.SequentialScan) != 0)
-            {
-                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SEQUENTIAL_ONLY;
-            }
-
-            if ((options & System.IO.FileOptions.RandomAccess) != 0)
-            {
-                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_RANDOM_ACCESS;
-            }
-
-            try
-            {
-                // NOTE: the Name property is intended to reveal the publicly available moniker for the
-                // FILESTREAM attributed column data. We will not surface the internal processing that
-                // takes place to create the mappedPath.
-                string mappedPath = InitializeNtPath(sPath);
-                int retval = 0;
-                Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out uint oldMode);
-
-                try
-                {
-                    if (transactionContext.Length >= ushort.MaxValue)
-                        throw ADP.ArgumentOutOfRange("transactionContext");
-
-                    int headerSize = sizeof(Interop.NtDll.FILE_FULL_EA_INFORMATION);
-                    int fullSize = headerSize + transactionContext.Length + s_eaNameString.Length;
-
-                    byte[] buffer = ArrayPool<byte>.Shared.Rent(fullSize);
-
-                    fixed (byte* b = buffer)
-                    {
-                        Interop.NtDll.FILE_FULL_EA_INFORMATION* ea = (Interop.NtDll.FILE_FULL_EA_INFORMATION*)b;
-                        ea->NextEntryOffset = 0;
-                        ea->Flags = 0;
-                        ea->EaNameLength = (byte)(s_eaNameString.Length - 1); // Length does not include terminating null character.
-                        ea->EaValueLength = (ushort)transactionContext.Length;
-
-                        // We could continue to do pointer math here, chose to use Span for convenience to
-                        // make sure we get the other members in the right place.
-                        Span<byte> data = buffer.AsSpan(headerSize);
-                        s_eaNameString.AsSpan().CopyTo(data);
-                        data = data.Slice(s_eaNameString.Length);
-                        transactionContext.AsSpan().CopyTo(data);
-
-                        (int status, IntPtr handle) = Interop.NtDll.CreateFile(
-                                                                                path: mappedPath.AsSpan(),
-                                                                                rootDirectory: IntPtr.Zero,
-                                                                                createDisposition: dwCreateDisposition,
-                                                                                desiredAccess: nDesiredAccess,
-                                                                                shareAccess: nShareAccess,
-                                                                                fileAttributes: 0,
-                                                                                createOptions: dwCreateOptions,
-                                                                                eaBuffer: b,
-                                                                                eaLength: (uint)fullSize);
-                        retval = status;
-                        hFile = new SafeFileHandle(handle, true);
-                    }
-
-                    ArrayPool<byte>.Shared.Return(buffer);
-                }
-                finally
-                {
-                    Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
-                }
-
-                switch (retval)
-                {
-                    case 0:
-                        break;
-
-                    case Interop.Errors.ERROR_SHARING_VIOLATION:
-                        throw ADP.InvalidOperation(SR.GetString(SR.SqlFileStream_FileAlreadyInTransaction));
-
-                    case Interop.Errors.ERROR_INVALID_PARAMETER:
-                        throw ADP.Argument(SR.GetString(SR.SqlFileStream_InvalidParameter));
-
-                    case Interop.Errors.ERROR_FILE_NOT_FOUND:
-                        {
-                            System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
-                            ADP.TraceExceptionAsReturnValue(e);
-                            throw e;
-                        }
-                    default:
-                        {
-                            uint error = Interop.NtDll.RtlNtStatusToDosError(retval);
-                            if (error == ERROR_MR_MID_NOT_FOUND)
-                            {
-                                // status code could not be mapped to a Win32 error code
-                                error = (uint)retval;
-                            }
-
-                            System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked((int)error));
-                            ADP.TraceExceptionAsReturnValue(e);
-                            throw e;
-                        }
-                }
-
-                if (hFile.IsInvalid)
-                {
-                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE);
-                    ADP.TraceExceptionAsReturnValue(e);
-                    throw e;
-                }
-
-                if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
-                {
-                    hFile.Dispose();
-                    throw ADP.Argument(SR.GetString(SR.SqlFileStream_PathNotValidDiskResource));
-                }
-
-                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
-                // through current data and then append new data to the end, so we need to tell SQL Server to preserve
-                // the existing file contents.
-                if (access == System.IO.FileAccess.ReadWrite)
-                {
-                    uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM,
-                        IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED,
-                        (byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS);
-
-                    if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero))
-                    {
-                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
-                        ADP.TraceExceptionAsReturnValue(e);
-                        throw e;
-                    }
-                }
-
-                // now that we've successfully opened a handle on the path and verified that it is a file,
-                // use the SafeFileHandle to initialize our internal System.IO.FileStream instance
-                System.Diagnostics.Debug.Assert(_m_fs == null);
-                _m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
-            }
-            catch
-            {
-                if (hFile != null && !hFile.IsInvalid)
-                    hFile.Dispose();
-
-                throw;
-            }
-        }
-        // This method exists to ensure that the requested path name is unique so that SMB/DNS is prevented
-        // from collapsing a file open request to a file handle opened previously. In the SQL FILESTREAM case,
-        // this would likely be a file open in another transaction, so this mechanism ensures isolation.
-        private static string InitializeNtPath(string path)
-        {
-            // Ensure we have validated and normalized the path before
-            AssertPathFormat(path);
-            string uniqueId = Guid.NewGuid().ToString("N");
-            return System.IO.PathInternal.IsDeviceUNC(path) ? string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", path.Replace(@"\\.", @"\??"), uniqueId)
-                                                            : string.Format(CultureInfo.InvariantCulture, @"\??\UNC\{0}\{1}", path.Trim('\\'), uniqueId);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInfoMessageEvent.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInfoMessageEvent.cs
deleted file mode 100644 (file)
index 42e770d..0000000
+++ /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.
-
-
-
-//------------------------------------------------------------------------------
-
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlInfoMessageEventArgs : System.EventArgs
-    {
-        private readonly SqlException _exception;
-
-        internal SqlInfoMessageEventArgs(SqlException exception)
-        {
-            _exception = exception;
-        }
-
-        public SqlErrorCollection Errors
-        {
-            get { return _exception.Errors; }
-        }
-
-        private bool ShouldSerializeErrors()
-        {
-            return (null != _exception) && (0 < _exception.Errors.Count);
-        }
-
-        public string Message
-        {
-            get { return _exception.Message; }
-        }
-
-        public string Source
-        {
-            get { return _exception.Source; }
-        }
-
-        public override string ToString()
-        {
-            return Message;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInfoMessageEventHandler.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInfoMessageEventHandler.cs
deleted file mode 100644 (file)
index f0fcbdd..0000000
+++ /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.
-
-
-
-//------------------------------------------------------------------------------
-
-
-
-namespace System.Data.SqlClient
-{
-    /// <devdoc>
-    ///    <para>
-    ///       Represents the method that will handle the <see cref='System.Data.SqlClient.SqlConnection.InfoMessage'/> event of a <see cref='System.Data.SqlClient.SqlConnection'/>.
-    ///    </para>
-    /// </devdoc>
-    public delegate void SqlInfoMessageEventHandler(object sender, SqlInfoMessageEventArgs e);
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs
deleted file mode 100644 (file)
index 8f73f6b..0000000
+++ /dev/null
@@ -1,626 +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.Data.Common;
-using System.Data.ProviderBase;
-using System.Diagnostics;
-using System.Transactions;
-
-
-namespace System.Data.SqlClient
-{
-    internal abstract class SqlInternalConnection : DbConnectionInternal
-    {
-        private readonly SqlConnectionString _connectionOptions;
-        private bool _isEnlistedInTransaction; // is the server-side connection enlisted? true while we're enlisted, reset only after we send a null...
-        private byte[] _promotedDTCToken;        // token returned by the server when we promote transaction
-        private byte[] _whereAbouts;             // cache the whereabouts (DTC Address) for exporting
-
-        private bool _isGlobalTransaction = false; // Whether this is a Global Transaction (Non-MSDTC, Azure SQL DB Transaction)
-        private bool _isGlobalTransactionEnabledForServer = false; // Whether Global Transactions are enabled for this Azure SQL DB Server
-        private static readonly Guid _globalTransactionTMID = new Guid("1c742caf-6680-40ea-9c26-6b6846079764"); // ID of the Non-MSDTC, Azure SQL DB Transaction Manager
-
-        // if connection is not open: null
-        // if connection is open: currently active database
-        internal string CurrentDatabase { get; set; }
-
-        // if connection is not open yet, CurrentDataSource is null
-        // if connection is open:
-        // * for regular connections, it is set to Data Source value from connection string
-        // * for connections with FailoverPartner, it is set to the FailoverPartner value from connection string if the connection was opened to it.
-        internal string CurrentDataSource { get; set; }
-
-        // the delegated (or promoted) transaction we're responsible for.
-        internal SqlDelegatedTransaction DelegatedTransaction { get; set; }
-
-        internal enum TransactionRequest
-        {
-            Begin,
-            Promote,
-            Commit,
-            Rollback,
-            IfRollback,
-            Save
-        };
-
-        internal SqlInternalConnection(SqlConnectionString connectionOptions) : base()
-        {
-            Debug.Assert(null != connectionOptions, "null connectionOptions?");
-            _connectionOptions = connectionOptions;
-        }
-
-        internal SqlConnection Connection
-        {
-            get
-            {
-                return (SqlConnection)Owner;
-            }
-        }
-
-        internal SqlConnectionString ConnectionOptions
-        {
-            get
-            {
-                return _connectionOptions;
-            }
-        }
-
-        internal abstract SqlInternalTransaction CurrentTransaction
-        {
-            get;
-        }
-
-        //  Get the internal transaction that should be hooked to a new outer transaction
-        //  during a BeginTransaction API call.  In some cases (i.e. connection is going to
-        //  be reset), CurrentTransaction should not be hooked up this way.
-        internal virtual SqlInternalTransaction AvailableInternalTransaction
-        {
-            get
-            {
-                return CurrentTransaction;
-            }
-        }
-
-        internal abstract SqlInternalTransaction PendingTransaction
-        {
-            get;
-        }
-
-        protected internal override bool IsNonPoolableTransactionRoot
-        {
-            get
-            {
-                return IsTransactionRoot;  // default behavior is that root transactions are NOT poolable.  Subclasses may override.
-            }
-        }
-
-        internal override bool IsTransactionRoot
-        {
-            get
-            {
-                var delegatedTransaction = DelegatedTransaction;
-                return ((null != delegatedTransaction) && (delegatedTransaction.IsActive));
-            }
-        }
-
-
-        internal bool HasLocalTransaction
-        {
-            get
-            {
-                SqlInternalTransaction currentTransaction = CurrentTransaction;
-                bool result = (null != currentTransaction && currentTransaction.IsLocal);
-                return result;
-            }
-        }
-
-        internal bool HasLocalTransactionFromAPI
-        {
-            get
-            {
-                SqlInternalTransaction currentTransaction = CurrentTransaction;
-                bool result = (null != currentTransaction && currentTransaction.HasParentTransaction);
-                return result;
-            }
-        }
-
-        internal bool IsEnlistedInTransaction
-        {
-            get
-            {
-                return _isEnlistedInTransaction;
-            }
-        }
-
-        internal abstract bool IsLockedForBulkCopy
-        {
-            get;
-        }
-
-
-        internal abstract bool IsKatmaiOrNewer
-        {
-            get;
-        }
-
-        internal byte[] PromotedDTCToken
-        {
-            get
-            {
-                return _promotedDTCToken;
-            }
-            set
-            {
-                _promotedDTCToken = value;
-            }
-        }
-
-        internal bool IsGlobalTransaction
-        {
-            get
-            {
-                return _isGlobalTransaction;
-            }
-            set
-            {
-                _isGlobalTransaction = value;
-            }
-        }
-
-        internal bool IsGlobalTransactionsEnabledForServer
-        {
-            get
-            {
-                return _isGlobalTransactionEnabledForServer;
-            }
-            set
-            {
-                _isGlobalTransactionEnabledForServer = value;
-            }
-        }
-
-        public override DbTransaction BeginTransaction(IsolationLevel iso)
-        {
-            return BeginSqlTransaction(iso, null, false);
-        }
-
-        internal virtual SqlTransaction BeginSqlTransaction(IsolationLevel iso, string transactionName, bool shouldReconnect)
-        {
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Connection.Statistics);
-
-                ValidateConnectionForExecute(null);
-
-                if (HasLocalTransactionFromAPI)
-                    throw ADP.ParallelTransactionsNotSupported(Connection);
-
-                if (iso == IsolationLevel.Unspecified)
-                {
-                    iso = IsolationLevel.ReadCommitted; // Default to ReadCommitted if unspecified.
-                }
-
-                SqlTransaction transaction = new SqlTransaction(this, Connection, iso, AvailableInternalTransaction);
-                transaction.InternalTransaction.RestoreBrokenConnection = shouldReconnect;
-                ExecuteTransaction(TransactionRequest.Begin, transactionName, iso, transaction.InternalTransaction, false);
-                transaction.InternalTransaction.RestoreBrokenConnection = false;
-                return transaction;
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public override void ChangeDatabase(string database)
-        {
-            if (string.IsNullOrEmpty(database))
-            {
-                throw ADP.EmptyDatabaseName();
-            }
-
-            ValidateConnectionForExecute(null);
-
-            ChangeDatabaseInternal(database);  // do the real work...
-        }
-
-        protected abstract void ChangeDatabaseInternal(string database);
-
-        protected override void CleanupTransactionOnCompletion(Transaction transaction)
-        {
-            // Note: unlocked, potentially multi-threaded code, so pull delegate to local to
-            //  ensure it doesn't change between test and call.
-            SqlDelegatedTransaction delegatedTransaction = DelegatedTransaction;
-            if (null != delegatedTransaction)
-            {
-                delegatedTransaction.TransactionEnded(transaction);
-            }
-        }
-
-        protected override DbReferenceCollection CreateReferenceCollection()
-        {
-            return new SqlReferenceCollection();
-        }
-
-        protected override void Deactivate()
-        {
-            try
-            {
-                SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection;
-                if (null != referenceCollection)
-                {
-                    referenceCollection.Deactivate();
-                }
-
-                // Invoke subclass-specific deactivation logic
-                InternalDeactivate();
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-
-                // if an exception occurred, the inner connection will be
-                // marked as unusable and destroyed upon returning to the
-                // pool
-                DoomThisConnection();
-            }
-        }
-
-        internal abstract void DisconnectTransaction(SqlInternalTransaction internalTransaction);
-
-        public override void Dispose()
-        {
-            _whereAbouts = null;
-            base.Dispose();
-        }
-
-        protected void Enlist(Transaction tx)
-        {
-            // This method should not be called while the connection has a
-            // reference to an active delegated transaction.
-            // Manual enlistment via SqlConnection.EnlistTransaction
-            // should catch this case and throw an exception.
-            //
-            // Automatic enlistment isn't possible because
-            // Sys.Tx keeps the connection alive until the transaction is completed.
-            Debug.Assert(!IsNonPoolableTransactionRoot, "cannot defect an active delegated transaction!");  // potential race condition, but it's an assert
-
-            if (null == tx)
-            {
-                if (IsEnlistedInTransaction)
-                {
-                    EnlistNull();
-                }
-                else
-                {
-                    // When IsEnlistedInTransaction is false, it means we are in one of two states:
-                    // 1. EnlistTransaction is null, so the connection is truly not enlisted in a transaction, or
-                    // 2. Connection is enlisted in a SqlDelegatedTransaction.
-                    //
-                    // For #2, we have to consider whether or not the delegated transaction is active.
-                    // If it is not active, we allow the enlistment in the NULL transaction.
-                    //
-                    // If it is active, technically this is an error.
-                    // However, no exception is thrown as this was the precedent (and this case is silently ignored, no error, but no enlistment either).
-                    // There are two mitigations for this:
-                    // 1. SqlConnection.EnlistTransaction checks that the enlisted transaction has completed before allowing a different enlistment.
-                    // 2. For debug builds, the assert at the beginning of this method checks for an enlistment in an active delegated transaction.
-                    Transaction enlistedTransaction = EnlistedTransaction;
-                    if (enlistedTransaction != null && enlistedTransaction.TransactionInformation.Status != TransactionStatus.Active)
-                    {
-                        EnlistNull();
-                    }
-                }
-            }
-            // Only enlist if it's different...
-            else if (!tx.Equals(EnlistedTransaction))
-            { // WebData 20000024 - Must use Equals, not !=
-                EnlistNonNull(tx);
-            }
-        }
-
-        private void EnlistNonNull(Transaction tx)
-        {
-            Debug.Assert(null != tx, "null transaction?");
-
-            bool hasDelegatedTransaction = false;
-
-            // Promotable transactions are only supported on Yukon
-            // servers or newer.
-            SqlDelegatedTransaction delegatedTransaction = new SqlDelegatedTransaction(this, tx);
-
-            try
-            {
-                // NOTE: System.Transactions claims to resolve all
-                // potential race conditions between multiple delegate
-                // requests of the same transaction to different
-                // connections in their code, such that only one
-                // attempt to delegate will succeed.
-
-                // NOTE: PromotableSinglePhaseEnlist will eventually
-                // make a round trip to the server; doing this inside
-                // a lock is not the best choice.  We presume that you
-                // aren't trying to enlist concurrently on two threads
-                // and leave it at that -- We don't claim any thread
-                // safety with regard to multiple concurrent requests
-                // to enlist the same connection in different
-                // transactions, which is good, because we don't have
-                // it anyway.
-
-                // PromotableSinglePhaseEnlist may not actually promote
-                // the transaction when it is already delegated (this is
-                // the way they resolve the race condition when two
-                // threads attempt to delegate the same Lightweight
-                // Transaction)  In that case, we can safely ignore
-                // our delegated transaction, and proceed to enlist
-                // in the promoted one.
-
-                // NOTE: Global Transactions is an Azure SQL DB only
-                // feature where the Transaction Manager (TM) is not
-                // MS-DTC. Sys.Tx added APIs to support Non MS-DTC
-                // promoter types/TM in .NET 4.6.1. Following directions
-                // from .NETFX shiproom, to avoid a "hard-dependency"
-                // (compile time) on Sys.Tx, we use reflection to invoke
-                // the new APIs. Further, the _isGlobalTransaction flag
-                // indicates that this is an Azure SQL DB Transaction
-                // that could be promoted to a Global Transaction (it's
-                // always false for on-prem Sql Server). The Promote()
-                // call in SqlDelegatedTransaction makes sure that the
-                // right Sys.Tx.dll is loaded and that Global Transactions
-                // are actually allowed for this Azure SQL DB.
-
-                if (_isGlobalTransaction)
-                {
-                    if (SysTxForGlobalTransactions.EnlistPromotableSinglePhase == null)
-                    {
-                        // This could be a local Azure SQL DB transaction.
-                        hasDelegatedTransaction = tx.EnlistPromotableSinglePhase(delegatedTransaction);
-                    }
-                    else
-                    {
-                        hasDelegatedTransaction = (bool)SysTxForGlobalTransactions.EnlistPromotableSinglePhase.Invoke(tx, new object[] { delegatedTransaction, _globalTransactionTMID });
-                    }
-                }
-                else
-                {
-                    // This is an MS-DTC distributed transaction
-                    hasDelegatedTransaction = tx.EnlistPromotableSinglePhase(delegatedTransaction);
-                }
-
-                if (hasDelegatedTransaction)
-                {
-                    this.DelegatedTransaction = delegatedTransaction;
-                }
-            }
-            catch (SqlException e)
-            {
-                // we do not want to eat the error if it is a fatal one
-                if (e.Class >= TdsEnums.FATAL_ERROR_CLASS)
-                {
-                    throw;
-                }
-
-                // if the parser is null or its state is not openloggedin, the connection is no longer good.
-                SqlInternalConnectionTds tdsConnection = this as SqlInternalConnectionTds;
-                if (tdsConnection != null)
-                {
-                    TdsParser parser = tdsConnection.Parser;
-                    if (parser == null || parser.State != TdsParserState.OpenLoggedIn)
-                    {
-                        throw;
-                    }
-                }
-
-                // In this case, SqlDelegatedTransaction.Initialize
-                // failed and we don't necessarily want to reject
-                // things -- there may have been a legitimate reason
-                // for the failure.
-            }
-
-            if (!hasDelegatedTransaction)
-            {
-                byte[] cookie = null;
-
-                if (_isGlobalTransaction)
-                {
-                    if (SysTxForGlobalTransactions.GetPromotedToken == null)
-                    {
-                        throw SQL.UnsupportedSysTxForGlobalTransactions();
-                    }
-
-                    cookie = (byte[])SysTxForGlobalTransactions.GetPromotedToken.Invoke(tx, null);
-                }
-                else
-                {
-                    if (null == _whereAbouts)
-                    {
-                        byte[] dtcAddress = GetDTCAddress();
-
-                        if (null == dtcAddress)
-                        {
-                            throw SQL.CannotGetDTCAddress();
-                        }
-                        _whereAbouts = dtcAddress;
-                    }
-                    cookie = GetTransactionCookie(tx, _whereAbouts);
-                }
-
-                // send cookie to server to finish enlistment
-                PropagateTransactionCookie(cookie);
-
-                _isEnlistedInTransaction = true;
-            }
-
-            EnlistedTransaction = tx; // Tell the base class about our enlistment
-
-
-            // If we're on a Yukon or newer server, and we delegate the
-            // transaction successfully, we will have done a begin transaction,
-            // which produces a transaction id that we should execute all requests
-            // on.  The TdsParser or SmiEventSink will store this information as
-            // the current transaction.
-            //
-            // Likewise, propagating a transaction to a Yukon or newer server will
-            // produce a transaction id that The TdsParser or SmiEventSink will
-            // store as the current transaction.
-            //
-            // In either case, when we're working with a Yukon or newer server
-            // we better have a current transaction by now.
-
-            Debug.Assert(null != CurrentTransaction, "delegated/enlisted transaction with null current transaction?");
-        }
-
-        internal void EnlistNull()
-        {
-            // We were in a transaction, but now we are not - so send
-            // message to server with empty transaction - confirmed proper
-            // behavior from Sameet Agarwal
-            //
-            // The connection pooler maintains separate pools for enlisted
-            // transactions, and only when that transaction is committed or
-            // rolled back will those connections be taken from that
-            // separate pool and returned to the general pool of connections
-            // that are not affiliated with any transactions.  When this
-            // occurs, we will have a new transaction of null and we are
-            // required to send an empty transaction payload to the server.
-
-            PropagateTransactionCookie(null);
-
-            _isEnlistedInTransaction = false;
-            EnlistedTransaction = null; // Tell the base class about our enlistment
-
-            // The EnlistTransaction above will return an TransactionEnded event,
-            // which causes the TdsParser or SmiEventSink should to clear the
-            // current transaction.
-            //
-            // In either case, when we're working with a Yukon or newer server
-            // we better not have a current transaction at this point.
-
-            Debug.Assert(null == CurrentTransaction, "unenlisted transaction with non-null current transaction?");   // verify it!
-        }
-
-        public override void EnlistTransaction(Transaction transaction)
-        {
-            ValidateConnectionForExecute(null);
-
-            // If a connection has a local transaction outstanding and you try
-            // to enlist in a DTC transaction, SQL Server will rollback the
-            // local transaction and then do the enlist (7.0 and 2000).  So, if
-            // the user tries to do this, throw.
-            if (HasLocalTransaction)
-            {
-                throw ADP.LocalTransactionPresent();
-            }
-
-            if (null != transaction && transaction.Equals(EnlistedTransaction))
-            {
-                // No-op if this is the current transaction
-                return;
-            }
-
-            // If a connection is already enlisted in a DTC transaction and you
-            // try to enlist in another one, in 7.0 the existing DTC transaction
-            // would roll back and then the connection would enlist in the new
-            // one. In SQL 2000 & Yukon, when you enlist in a DTC transaction
-            // while the connection is already enlisted in a DTC transaction,
-            // the connection simply switches enlistments.  Regardless, simply
-            // enlist in the user specified distributed transaction.  This
-            // behavior matches OLEDB and ODBC.
-
-            try
-            {
-                Enlist(transaction);
-            }
-            catch (System.OutOfMemoryException e)
-            {
-                Connection.Abort(e);
-                throw;
-            }
-            catch (System.StackOverflowException e)
-            {
-                Connection.Abort(e);
-                throw;
-            }
-            catch (System.Threading.ThreadAbortException e)
-            {
-                Connection.Abort(e);
-                throw;
-            }
-        }
-
-        internal abstract void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest);
-
-        internal SqlDataReader FindLiveReader(SqlCommand command)
-        {
-            SqlDataReader reader = null;
-            SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection;
-            if (null != referenceCollection)
-            {
-                reader = referenceCollection.FindLiveReader(command);
-            }
-            return reader;
-        }
-
-        internal SqlCommand FindLiveCommand(TdsParserStateObject stateObj)
-        {
-            SqlCommand command = null;
-            SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection;
-            if (null != referenceCollection)
-            {
-                command = referenceCollection.FindLiveCommand(stateObj);
-            }
-            return command;
-        }
-
-        protected abstract byte[] GetDTCAddress();
-
-        private static byte[] GetTransactionCookie(Transaction transaction, byte[] whereAbouts)
-        {
-            byte[] transactionCookie = null;
-            if (null != transaction)
-            {
-                transactionCookie = TransactionInterop.GetExportCookie(transaction, whereAbouts);
-            }
-            return transactionCookie;
-        }
-
-        protected virtual void InternalDeactivate()
-        {
-        }
-
-        // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
-        // The close action also supports being run asynchronously
-        internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction = null)
-        {
-            if (breakConnection)
-            {
-                DoomThisConnection();
-            }
-
-            var connection = Connection;
-            if (null != connection)
-            {
-                connection.OnError(exception, breakConnection, wrapCloseInAction);
-            }
-            else if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
-            {
-                // It is an error, and should be thrown.  Class of TdsEnums.MIN_ERROR_CLASS
-                // or above is an error, below TdsEnums.MIN_ERROR_CLASS denotes an info message.
-                throw exception;
-            }
-        }
-
-        protected abstract void PropagateTransactionCookie(byte[] transactionCookie);
-
-        internal abstract void ValidateConnectionForExecute(SqlCommand command);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
deleted file mode 100644 (file)
index 22fdf7b..0000000
+++ /dev/null
@@ -1,2099 +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.Generic;
-using System.Data.Common;
-using System.Data.ProviderBase;
-using System.Diagnostics;
-using System.Globalization;
-using System.Threading;
-using System.Diagnostics.CodeAnalysis;
-using System.Threading.Tasks;
-using System.Transactions;
-using System.Security;
-
-namespace System.Data.SqlClient
-{
-    internal class SessionStateRecord
-    {
-        internal bool _recoverable;
-        internal uint _version;
-        internal int _dataLength;
-        internal byte[] _data;
-    }
-
-    internal class SessionData
-    {
-        internal const int _maxNumberOfSessionStates = 256;
-        internal uint _tdsVersion;
-        internal bool _encrypted;
-
-        internal string _database;
-        internal SqlCollation _collation;
-        internal string _language;
-
-        internal string _initialDatabase;
-        internal SqlCollation _initialCollation;
-        internal string _initialLanguage;
-
-        internal byte _unrecoverableStatesCount = 0;
-        internal Dictionary<string, Tuple<string, string>> _resolvedAliases;
-
-#if DEBUG
-        internal bool _debugReconnectDataApplied;
-#endif
-
-        internal SessionStateRecord[] _delta = new SessionStateRecord[_maxNumberOfSessionStates];
-        internal bool _deltaDirty = false;
-        internal byte[][] _initialState = new byte[_maxNumberOfSessionStates][];
-
-        public SessionData(SessionData recoveryData)
-        {
-            _initialDatabase = recoveryData._initialDatabase;
-            _initialCollation = recoveryData._initialCollation;
-            _initialLanguage = recoveryData._initialLanguage;
-            _resolvedAliases = recoveryData._resolvedAliases;
-
-            for (int i = 0; i < _maxNumberOfSessionStates; i++)
-            {
-                if (recoveryData._initialState[i] != null)
-                {
-                    _initialState[i] = (byte[])recoveryData._initialState[i].Clone();
-                }
-            }
-        }
-
-        public SessionData()
-        {
-            _resolvedAliases = new Dictionary<string, Tuple<string, string>>(2);
-        }
-
-        public void Reset()
-        {
-            _database = null;
-            _collation = null;
-            _language = null;
-            if (_deltaDirty)
-            {
-                _delta = new SessionStateRecord[_maxNumberOfSessionStates];
-                _deltaDirty = false;
-            }
-            _unrecoverableStatesCount = 0;
-        }
-
-        [Conditional("DEBUG")]
-        public void AssertUnrecoverableStateCountIsCorrect()
-        {
-            byte unrecoverableCount = 0;
-            foreach (var state in _delta)
-            {
-                if (state != null && !state._recoverable)
-                    unrecoverableCount++;
-            }
-            Debug.Assert(unrecoverableCount == _unrecoverableStatesCount, "Unrecoverable count does not match");
-        }
-    }
-
-    internal sealed class SqlInternalConnectionTds : SqlInternalConnection, IDisposable
-    {
-        // CONNECTION AND STATE VARIABLES
-        private readonly SqlConnectionPoolGroupProviderInfo _poolGroupProviderInfo; // will only be null when called for ChangePassword, or creating SSE User Instance
-        private TdsParser _parser;
-        private SqlLoginAck _loginAck;
-        private readonly SqlCredential _credential;
-        private FederatedAuthenticationFeatureExtensionData? _fedAuthFeatureExtensionData;
-
-        // Connection Resiliency
-        private bool _sessionRecoveryRequested;
-        internal bool _sessionRecoveryAcknowledged;
-        internal SessionData _currentSessionData; // internal for use from TdsParser only, other should use CurrentSessionData property that will fix database and language
-        private SessionData _recoverySessionData;
-
-        // Federated Authentication
-        // Response obtained from the server for FEDAUTHREQUIRED prelogin option.
-        internal bool _fedAuthRequired;
-        internal bool _federatedAuthenticationRequested;
-        internal bool _federatedAuthenticationAcknowledged;
-        internal byte[] _accessTokenInBytes;
-
-        // The errors in the transient error set are contained in
-        // https://azure.microsoft.com/en-us/documentation/articles/sql-database-develop-error-messages/#transient-faults-connection-loss-and-other-temporary-errors
-        private static readonly HashSet<int> s_transientErrors = new HashSet<int>
-        {
-            // SQL Error Code: 4060
-            // Cannot open database "%.*ls" requested by the login. The login failed.
-            4060,
-
-            // SQL Error Code: 10928
-            // Resource ID: %d. The %s limit for the database is %d and has been reached.
-            10928,
-
-            // SQL Error Code: 10929
-            // Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d.
-            // However, the server is currently too busy to support requests greater than %d for this database.
-            10929,
-
-            // SQL Error Code: 40197
-            // You will receive this error, when the service is down due to software or hardware upgrades, hardware failures,
-            // or any other failover problems. The error code (%d) embedded within the message of error 40197 provides
-            // additional information about the kind of failure or failover that occurred. Some examples of the error codes are
-            // embedded within the message of error 40197 are 40020, 40143, 40166, and 40540.
-            40197,
-
-            // The service is currently busy. Retry the request after 10 seconds. Incident ID: %ls. Code: %d.
-            40501,
-
-            // Database '%.*ls' on server '%.*ls' is not currently available. Please retry the connection later.
-            // If the problem persists, contact customer support, and provide them the session tracing ID of '%.*ls'.
-            40613
-        };
-
-        internal SessionData CurrentSessionData
-        {
-            get
-            {
-                if (_currentSessionData != null)
-                {
-                    _currentSessionData._database = CurrentDatabase;
-                    _currentSessionData._language = _currentLanguage;
-                }
-                return _currentSessionData;
-            }
-        }
-
-        // FOR POOLING
-        private bool _fConnectionOpen = false;
-
-        // FOR CONNECTION RESET MANAGEMENT
-        private readonly bool _fResetConnection;
-        private string _originalDatabase;
-        private string _currentFailoverPartner;                     // only set by ENV change from server
-        private string _originalLanguage;
-        private string _currentLanguage;
-        private int _currentPacketSize;
-        private int _asyncCommandCount; // number of async Begins minus number of async Ends.
-
-        // FOR SSE
-        private string _instanceName = string.Empty;
-
-        // FOR NOTIFICATIONS
-        private readonly DbConnectionPoolIdentity _identity; // Used to lookup info for notification matching Start().
-
-        // FOR SYNCHRONIZATION IN TdsParser
-        // How to use these locks:
-        // 1. Whenever writing to the connection (with the exception of Cancellation) the _parserLock MUST be taken
-        // 2. _parserLock will also be taken during close (to prevent closing in the middle of a write)
-        // 3. Whenever you have the _parserLock and are calling a method that would cause the connection to close if it failed (with the exception of any writing method), you MUST set ThreadHasParserLockForClose to true
-        //      * This is to prevent the connection deadlocking with itself (since you already have the _parserLock, and Closing the connection will attempt to re-take that lock)
-        //      * It is safe to set ThreadHasParserLockForClose to true when writing as well, but it is unnecessary
-        //      * If you have a method that takes _parserLock, it is a good idea check ThreadHasParserLockForClose first (if you don't expect _parserLock to be taken by something higher on the stack, then you should at least assert that it is false)
-        // 4. ThreadHasParserLockForClose is thread-specific - this means that you must set it to false before returning a Task, and set it back to true in the continuation
-        // 5. ThreadHasParserLockForClose should only be modified if you currently own the _parserLock
-        // 6. Reading ThreadHasParserLockForClose is thread-safe
-        internal class SyncAsyncLock
-        {
-            private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
-
-            internal void Wait(bool canReleaseFromAnyThread)
-            {
-                Monitor.Enter(_semaphore); // semaphore is used as lock object, no relation to SemaphoreSlim.Wait/Release methods
-                if (canReleaseFromAnyThread || _semaphore.CurrentCount == 0)
-                {
-                    _semaphore.Wait();
-                    if (canReleaseFromAnyThread)
-                    {
-                        Monitor.Exit(_semaphore);
-                    }
-                    else
-                    {
-                        _semaphore.Release();
-                    }
-                }
-            }
-
-            internal void Wait(bool canReleaseFromAnyThread, int timeout, ref bool lockTaken)
-            {
-                lockTaken = false;
-                bool hasMonitor = false;
-                try
-                {
-                    Monitor.TryEnter(_semaphore, timeout, ref hasMonitor); // semaphore is used as lock object, no relation to SemaphoreSlim.Wait/Release methods
-                    if (hasMonitor)
-                    {
-                        if ((canReleaseFromAnyThread) || (_semaphore.CurrentCount == 0))
-                        {
-                            if (_semaphore.Wait(timeout))
-                            {
-                                if (canReleaseFromAnyThread)
-                                {
-                                    Monitor.Exit(_semaphore);
-                                    hasMonitor = false;
-                                }
-                                else
-                                {
-                                    _semaphore.Release();
-                                }
-                                lockTaken = true;
-                            }
-                        }
-                        else
-                        {
-                            lockTaken = true;
-                        }
-                    }
-                }
-                finally
-                {
-                    if ((!lockTaken) && (hasMonitor))
-                    {
-                        Monitor.Exit(_semaphore);
-                    }
-                }
-            }
-
-            internal void Release()
-            {
-                if (_semaphore.CurrentCount == 0)
-                {  //  semaphore methods were used for locking
-                    _semaphore.Release();
-                }
-                else
-                {
-                    Monitor.Exit(_semaphore);
-                }
-            }
-
-
-            internal bool CanBeReleasedFromAnyThread
-            {
-                get
-                {
-                    return _semaphore.CurrentCount == 0;
-                }
-            }
-
-            // Necessary but not sufficient condition for thread to have lock (since semaphore may be obtained by any thread)
-            internal bool ThreadMayHaveLock()
-            {
-                return Monitor.IsEntered(_semaphore) || _semaphore.CurrentCount == 0;
-            }
-        }
-
-
-        internal SyncAsyncLock _parserLock = new SyncAsyncLock();
-        private int _threadIdOwningParserLock = -1;
-
-        private readonly SqlConnectionTimeoutErrorInternal _timeoutErrorInternal;
-
-        internal SqlConnectionTimeoutErrorInternal TimeoutErrorInternal
-        {
-            get { return _timeoutErrorInternal; }
-        }
-
-        // OTHER STATE VARIABLES AND REFERENCES
-
-        internal Guid _clientConnectionId = Guid.Empty;
-
-        // Routing information (ROR)
-        private RoutingInfo _routingInfo = null;
-        private Guid _originalClientConnectionId = Guid.Empty;
-        private string _routingDestination = null;
-        private readonly TimeoutTimer _timeout;
-
-        // although the new password is generally not used it must be passed to the ctor
-        // the new Login7 packet will always write out the new password (or a length of zero and no bytes if not present)
-        //
-        internal SqlInternalConnectionTds(
-                DbConnectionPoolIdentity identity,
-                SqlConnectionString connectionOptions,
-                SqlCredential credential,
-                object providerInfo,
-                string newPassword,
-                SecureString newSecurePassword,
-                bool redirectedUserInstance,
-                SqlConnectionString userConnectionOptions = null, // NOTE: userConnectionOptions may be different to connectionOptions if the connection string has been expanded (see SqlConnectionString.Expand)
-                SessionData reconnectSessionData = null,
-                bool applyTransientFaultHandling = false,
-                string accessToken = null) : base(connectionOptions)
-
-        {
-#if DEBUG
-            if (reconnectSessionData != null)
-            {
-                reconnectSessionData._debugReconnectDataApplied = true;
-            }
-#endif
-            Debug.Assert(reconnectSessionData == null || connectionOptions.ConnectRetryCount > 0, "Reconnect data supplied with CR turned off");
-
-            if (connectionOptions.ConnectRetryCount > 0)
-            {
-                _recoverySessionData = reconnectSessionData;
-                if (reconnectSessionData == null)
-                {
-                    _currentSessionData = new SessionData();
-                }
-                else
-                {
-                    _currentSessionData = new SessionData(_recoverySessionData);
-                    _originalDatabase = _recoverySessionData._initialDatabase;
-                    _originalLanguage = _recoverySessionData._initialLanguage;
-                }
-            }
-
-            if (accessToken != null)
-            {
-                _accessTokenInBytes = System.Text.Encoding.Unicode.GetBytes(accessToken);
-            }
-
-            _identity = identity;
-            Debug.Assert(newSecurePassword != null || newPassword != null, "cannot have both new secure change password and string based change password to be null");
-            Debug.Assert(credential == null || (string.IsNullOrEmpty(connectionOptions.UserID) && string.IsNullOrEmpty(connectionOptions.Password)), "cannot mix the new secure password system and the connection string based password");
-
-            Debug.Assert(credential == null || !connectionOptions.IntegratedSecurity, "Cannot use SqlCredential and Integrated Security");
-
-            _poolGroupProviderInfo = (SqlConnectionPoolGroupProviderInfo)providerInfo;
-            _fResetConnection = connectionOptions.ConnectionReset;
-            if (_fResetConnection && _recoverySessionData == null)
-            {
-                _originalDatabase = connectionOptions.InitialCatalog;
-                _originalLanguage = connectionOptions.CurrentLanguage;
-            }
-
-            _timeoutErrorInternal = new SqlConnectionTimeoutErrorInternal();
-            _credential = credential;
-
-            _parserLock.Wait(canReleaseFromAnyThread: false);
-            ThreadHasParserLockForClose = true;   // In case of error, let ourselves know that we already own the parser lock
-
-            try
-            {
-                _timeout = TimeoutTimer.StartSecondsTimeout(connectionOptions.ConnectTimeout);
-
-                // If transient fault handling is enabled then we can retry the login up to the ConnectRetryCount.
-                int connectionEstablishCount = applyTransientFaultHandling ? connectionOptions.ConnectRetryCount + 1 : 1;
-                int transientRetryIntervalInMilliSeconds = connectionOptions.ConnectRetryInterval * 1000; // Max value of transientRetryInterval is 60*1000 ms. The max value allowed for ConnectRetryInterval is 60
-                for (int i = 0; i < connectionEstablishCount; i++)
-                {
-                    try
-                    {
-                        OpenLoginEnlist(_timeout, connectionOptions, credential, newPassword, newSecurePassword, redirectedUserInstance);
-
-                        break;
-                    }
-                    catch (SqlException sqlex)
-                    {
-                        if (i + 1 == connectionEstablishCount
-                            || !applyTransientFaultHandling
-                            || _timeout.IsExpired
-                            || _timeout.MillisecondsRemaining < transientRetryIntervalInMilliSeconds
-                            || !IsTransientError(sqlex))
-                        {
-                            throw;
-                        }
-                        else
-                        {
-                            Thread.Sleep(transientRetryIntervalInMilliSeconds);
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                ThreadHasParserLockForClose = false;
-                _parserLock.Release();
-            }
-        }
-
-
-        // Returns true if the Sql error is a transient.
-        private bool IsTransientError(SqlException exc)
-        {
-            if (exc == null)
-            {
-                return false;
-            }
-            foreach (SqlError error in exc.Errors)
-            {
-                if (s_transientErrors.Contains(error.Number))
-                {
-                    return true;
-                }
-            }
-            return false;
-        }
-
-        internal Guid ClientConnectionId
-        {
-            get
-            {
-                return _clientConnectionId;
-            }
-        }
-
-        internal Guid OriginalClientConnectionId
-        {
-            get
-            {
-                return _originalClientConnectionId;
-            }
-        }
-
-        internal string RoutingDestination
-        {
-            get
-            {
-                return _routingDestination;
-            }
-        }
-
-        internal override SqlInternalTransaction CurrentTransaction
-        {
-            get
-            {
-                return _parser.CurrentTransaction;
-            }
-        }
-
-        internal override SqlInternalTransaction AvailableInternalTransaction
-        {
-            get
-            {
-                return _parser._fResetConnection ? null : CurrentTransaction;
-            }
-        }
-
-        internal override SqlInternalTransaction PendingTransaction
-        {
-            get
-            {
-                return _parser.PendingTransaction;
-            }
-        }
-
-        internal DbConnectionPoolIdentity Identity
-        {
-            get
-            {
-                return _identity;
-            }
-        }
-
-        internal string InstanceName
-        {
-            get
-            {
-                return _instanceName;
-            }
-        }
-
-        internal override bool IsLockedForBulkCopy
-        {
-            get
-            {
-                return (!Parser.MARSOn && Parser._physicalStateObj.BcpLock);
-            }
-        }
-
-        protected internal override bool IsNonPoolableTransactionRoot
-        {
-            get
-            {
-                return IsTransactionRoot && (!IsKatmaiOrNewer || null == Pool);
-            }
-        }
-
-        internal override bool IsKatmaiOrNewer
-        {
-            get
-            {
-                return _parser.IsKatmaiOrNewer;
-            }
-        }
-
-        internal int PacketSize
-        {
-            get
-            {
-                return _currentPacketSize;
-            }
-        }
-
-        internal TdsParser Parser
-        {
-            get
-            {
-                return _parser;
-            }
-        }
-
-        internal string ServerProvidedFailOverPartner
-        {
-            get
-            {
-                return _currentFailoverPartner;
-            }
-        }
-
-        internal SqlConnectionPoolGroupProviderInfo PoolGroupProviderInfo
-        {
-            get
-            {
-                return _poolGroupProviderInfo;
-            }
-        }
-
-        protected override bool ReadyToPrepareTransaction
-        {
-            get
-            {
-                bool result = (null == FindLiveReader(null)); // can't prepare with a live data reader...
-                return result;
-            }
-        }
-
-        public override string ServerVersion
-        {
-            get
-            {
-                return (string.Format("{0:00}.{1:00}.{2:0000}", _loginAck.majorVersion,
-                       (short)_loginAck.minorVersion, _loginAck.buildNum));
-            }
-        }
-
-        protected override bool UnbindOnTransactionCompletion
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // GENERAL METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-        [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // copied from Triaged.cs
-        protected override void ChangeDatabaseInternal(string database)
-        {
-            // Add brackets around database
-            database = SqlConnection.FixupDatabaseTransactionName(database);
-            Task executeTask = _parser.TdsExecuteSQLBatch("use " + database, ConnectionOptions.ConnectTimeout, null, _parser._physicalStateObj, sync: true);
-            Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
-            _parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj);
-        }
-
-        public override void Dispose()
-        {
-            try
-            {
-                TdsParser parser = Interlocked.Exchange(ref _parser, null);  // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this.
-
-                Debug.Assert(parser != null && _fConnectionOpen || parser == null && !_fConnectionOpen, "Unexpected state on dispose");
-                if (null != parser)
-                {
-                    parser.Disconnect();
-                }
-            }
-            finally
-            {
-                // close will always close, even if exception is thrown
-                // remember to null out any object references
-                _loginAck = null;
-                _fConnectionOpen = false; // mark internal connection as closed
-            }
-            base.Dispose();
-        }
-
-        internal override void ValidateConnectionForExecute(SqlCommand command)
-        {
-            TdsParser parser = _parser;
-            if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed))
-            {
-                throw ADP.ClosedConnectionError();
-            }
-            else
-            {
-                SqlDataReader reader = null;
-                if (parser.MARSOn)
-                {
-                    if (null != command)
-                    { // command can't have datareader already associated with it
-                        reader = FindLiveReader(command);
-                    }
-                }
-                else
-                { // single execution/datareader per connection
-                    if (_asyncCommandCount > 0)
-                    {
-                        throw SQL.MARSUnspportedOnConnection();
-                    }
-
-                    reader = FindLiveReader(null);
-                }
-                if (null != reader)
-                {
-                    // if MARS is on, then a datareader associated with the command exists
-                    // or if MARS is off, then a datareader exists
-                    throw ADP.OpenReaderExists();
-                }
-                else if (!parser.MARSOn && parser._physicalStateObj._pendingData)
-                {
-                    parser.DrainData(parser._physicalStateObj);
-                }
-                Debug.Assert(!parser._physicalStateObj._pendingData, "Should not have a busy physicalStateObject at this point!");
-
-                parser.RollbackOrphanedAPITransactions();
-            }
-        }
-
-        /// <summary>
-        /// Validate the enlisted transaction state, taking into consideration the ambient transaction and transaction unbinding mode.
-        /// If there is no enlisted transaction, this method is a nop.
-        /// </summary>
-        /// <remarks>
-        /// <para>
-        /// This method must be called while holding a lock on the SqlInternalConnection instance,
-        /// to ensure we don't accidentally execute after the transaction has completed on a different thread,
-        /// causing us to unwittingly execute in auto-commit mode.
-        /// </para>
-        ///
-        /// <para>
-        /// When using Explicit transaction unbinding,
-        /// verify that the enlisted transaction is active and equal to the current ambient transaction.
-        /// </para>
-        ///
-        /// <para>
-        /// When using Implicit transaction unbinding,
-        /// verify that the enlisted transaction is active.
-        /// If it is not active, and the transaction object has been disposed, unbind from the transaction.
-        /// If it is not active and not disposed, throw an exception.
-        /// </para>
-        /// </remarks>
-        internal void CheckEnlistedTransactionBinding()
-        {
-            // If we are enlisted in a transaction, check that transaction is active.
-            // When using explicit transaction unbinding, also verify that the enlisted transaction is the current transaction.
-            Transaction enlistedTransaction = EnlistedTransaction;
-
-            if (enlistedTransaction != null)
-            {
-                bool requireExplicitTransactionUnbind = ConnectionOptions.TransactionBinding == SqlConnectionString.TransactionBindingEnum.ExplicitUnbind;
-
-                if (requireExplicitTransactionUnbind)
-                {
-                    Transaction currentTransaction = Transaction.Current;
-
-                    if (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status || !enlistedTransaction.Equals(currentTransaction))
-                    {
-                        throw ADP.TransactionConnectionMismatch();
-                    }
-                }
-                else // implicit transaction unbind
-                {
-                    if (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status)
-                    {
-                        if (EnlistedTransactionDisposed)
-                        {
-                            DetachTransaction(enlistedTransaction, true);
-                        }
-                        else
-                        {
-                            throw ADP.TransactionCompletedButNotDisposed();
-                        }
-                    }
-                }
-            }
-        }
-
-        internal override bool IsConnectionAlive(bool throwOnException)
-        {
-            bool isAlive = false;
-            isAlive = _parser._physicalStateObj.IsConnectionAlive(throwOnException);
-            return isAlive;
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // POOLING METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        protected override void Activate(Transaction transaction)
-        {
-            // When we're required to automatically enlist in transactions and
-            // there is one we enlist in it. On the other hand, if there isn't a
-            // transaction and we are currently enlisted in one, then we
-            // unenlist from it.
-            //
-            // Regardless of whether we're required to automatically enlist,
-            // when there is not a current transaction, we cannot leave the
-            // connection enlisted in a transaction.
-            if (null != transaction)
-            {
-                if (ConnectionOptions.Enlist)
-                {
-                    Enlist(transaction);
-                }
-            }
-            else
-            {
-                Enlist(null);
-            }
-        }
-
-        protected override void InternalDeactivate()
-        {
-            // When we're deactivated, the user must have called End on all
-            // the async commands, or we don't know that we're in a state that
-            // we can recover from.  We doom the connection in this case, to
-            // prevent odd cases when we go to the wire.
-            if (0 != _asyncCommandCount)
-            {
-                DoomThisConnection();
-            }
-
-            // If we're deactivating with a delegated transaction, we
-            // should not be cleaning up the parser just yet, that will
-            // cause our transaction to be rolled back and the connection
-            // to be reset.  We'll get called again once the delegated
-            // transaction is completed and we can do it all then.
-            if (!IsNonPoolableTransactionRoot)
-            {
-                Debug.Assert(null != _parser || IsConnectionDoomed, "Deactivating a disposed connection?");
-                if (_parser != null)
-                {
-                    _parser.Deactivate(IsConnectionDoomed);
-
-                    if (!IsConnectionDoomed)
-                    {
-                        ResetConnection();
-                    }
-                }
-            }
-        }
-
-        [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // copied from Triaged.cs
-        private void ResetConnection()
-        {
-            // For implicit pooled connections, if connection reset behavior is specified,
-            // reset the database and language properties back to default.  It is important
-            // to do this on activate so that the dictionary is correct before SqlConnection
-            // obtains a clone.
-
-            Debug.Assert(!HasLocalTransactionFromAPI, "Upon ResetConnection SqlInternalConnectionTds has a currently ongoing local transaction.");
-            Debug.Assert(!_parser._physicalStateObj._pendingData, "Upon ResetConnection SqlInternalConnectionTds has pending data.");
-
-            if (_fResetConnection)
-            {
-                // Ensure we are either going against shiloh, or we are not enlisted in a
-                // distributed transaction - otherwise don't reset!
-                // Prepare the parser for the connection reset - the next time a trip
-                // to the server is made.
-                _parser.PrepareResetConnection(IsTransactionRoot && !IsNonPoolableTransactionRoot);
-
-                // Reset dictionary values, since calling reset will not send us env_changes.
-                CurrentDatabase = _originalDatabase;
-                _currentLanguage = _originalLanguage;
-            }
-        }
-
-        internal void DecrementAsyncCount()
-        {
-            Interlocked.Decrement(ref _asyncCommandCount);
-        }
-
-        internal void IncrementAsyncCount()
-        {
-            Interlocked.Increment(ref _asyncCommandCount);
-        }
-
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // LOCAL TRANSACTION METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        internal override void DisconnectTransaction(SqlInternalTransaction internalTransaction)
-        {
-            TdsParser parser = Parser;
-
-            if (null != parser)
-            {
-                parser.DisconnectTransaction(internalTransaction);
-            }
-        }
-
-        internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso)
-        {
-            ExecuteTransaction(transactionRequest, name, iso, null, false);
-        }
-
-        internal override void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest)
-        {
-            if (IsConnectionDoomed)
-            {  // doomed means we can't do anything else...
-                if (transactionRequest == TransactionRequest.Rollback
-                 || transactionRequest == TransactionRequest.IfRollback)
-                {
-                    return;
-                }
-                throw SQL.ConnectionDoomed();
-            }
-
-            if (transactionRequest == TransactionRequest.Commit
-             || transactionRequest == TransactionRequest.Rollback
-             || transactionRequest == TransactionRequest.IfRollback)
-            {
-                if (!Parser.MARSOn && Parser._physicalStateObj.BcpLock)
-                {
-                    throw SQL.ConnectionLockedForBcpEvent();
-                }
-            }
-
-            string transactionName = (null == name) ? string.Empty : name;
-
-            ExecuteTransactionYukon(transactionRequest, transactionName, iso, internalTransaction, isDelegateControlRequest);
-        }
-
-
-        internal void ExecuteTransactionYukon(
-                    TransactionRequest transactionRequest,
-                    string transactionName,
-                    IsolationLevel iso,
-                    SqlInternalTransaction internalTransaction,
-                    bool isDelegateControlRequest
-        )
-        {
-            TdsEnums.TransactionManagerRequestType requestType = TdsEnums.TransactionManagerRequestType.Begin;
-            TdsEnums.TransactionManagerIsolationLevel isoLevel = TdsEnums.TransactionManagerIsolationLevel.ReadCommitted;
-
-            isoLevel = iso switch
-            {
-                IsolationLevel.Unspecified => TdsEnums.TransactionManagerIsolationLevel.Unspecified,
-                IsolationLevel.ReadCommitted => TdsEnums.TransactionManagerIsolationLevel.ReadCommitted,
-                IsolationLevel.ReadUncommitted => TdsEnums.TransactionManagerIsolationLevel.ReadUncommitted,
-                IsolationLevel.RepeatableRead => TdsEnums.TransactionManagerIsolationLevel.RepeatableRead,
-                IsolationLevel.Serializable => TdsEnums.TransactionManagerIsolationLevel.Serializable,
-                IsolationLevel.Snapshot => TdsEnums.TransactionManagerIsolationLevel.Snapshot,
-                IsolationLevel.Chaos => throw SQL.NotSupportedIsolationLevel(iso),
-                _ => throw ADP.InvalidIsolationLevel(iso),
-            };
-            TdsParserStateObject stateObj = _parser._physicalStateObj;
-            TdsParser parser = _parser;
-            bool mustPutSession = false;
-            bool releaseConnectionLock = false;
-
-            Debug.Assert(!ThreadHasParserLockForClose || _parserLock.ThreadMayHaveLock(), "Thread claims to have parser lock, but lock is not taken");
-            if (!ThreadHasParserLockForClose)
-            {
-                _parserLock.Wait(canReleaseFromAnyThread: false);
-                ThreadHasParserLockForClose = true;   // In case of error, let the connection know that we already own the parser lock
-                releaseConnectionLock = true;
-            }
-            try
-            {
-                switch (transactionRequest)
-                {
-                    case TransactionRequest.Begin:
-                        requestType = TdsEnums.TransactionManagerRequestType.Begin;
-                        break;
-                    case TransactionRequest.Promote:
-                        requestType = TdsEnums.TransactionManagerRequestType.Promote;
-                        break;
-                    case TransactionRequest.Commit:
-                        requestType = TdsEnums.TransactionManagerRequestType.Commit;
-                        break;
-                    case TransactionRequest.IfRollback:
-                    // Map IfRollback to Rollback since with Yukon and beyond we should never need
-                    // the if since the server will inform us when transactions have completed
-                    // as a result of an error on the server.
-                    case TransactionRequest.Rollback:
-                        requestType = TdsEnums.TransactionManagerRequestType.Rollback;
-                        break;
-                    case TransactionRequest.Save:
-                        requestType = TdsEnums.TransactionManagerRequestType.Save;
-                        break;
-                    default:
-                        Debug.Fail("Unknown transaction type");
-                        break;
-                }
-
-                // only restore if connection lock has been taken within the function
-                if (internalTransaction != null && internalTransaction.RestoreBrokenConnection && releaseConnectionLock)
-                {
-                    Task reconnectTask = internalTransaction.Parent.Connection.ValidateAndReconnect(() =>
-                    {
-                        ThreadHasParserLockForClose = false;
-                        _parserLock.Release();
-                        releaseConnectionLock = false;
-                    }, 0);
-                    if (reconnectTask != null)
-                    {
-                        AsyncHelper.WaitForCompletion(reconnectTask, 0); // there is no specific timeout for BeginTransaction, uses ConnectTimeout
-                        internalTransaction.ConnectionHasBeenRestored = true;
-                        return;
-                    }
-                }
-
-                // SQLBUDT #20010853 - Promote, Commit and Rollback requests for
-                // delegated transactions often happen while there is an open result
-                // set, so we need to handle them by using a different MARS session,
-                // otherwise we'll write on the physical state objects while someone
-                // else is using it.  When we don't have MARS enabled, we need to
-                // lock the physical state object to syncronize it's use at least
-                // until we increment the open results count.  Once it's been
-                // incremented the delegated transaction requests will fail, so they
-                // won't stomp on anything.
-                //
-                // We need to keep this lock through the duration of the TM reqeuest
-                // so that we won't hijack a different request's data stream and a
-                // different request won't hijack ours, so we have a lock here on
-                // an object that the ExecTMReq will also lock, but since we're on
-                // the same thread, the lock is a no-op.
-
-                if (null != internalTransaction && internalTransaction.IsDelegated)
-                {
-                    if (_parser.MARSOn)
-                    {
-                        stateObj = _parser.GetSession(this);
-                        mustPutSession = true;
-                    }
-                    else if (internalTransaction.OpenResultsCount != 0)
-                    {
-                        //throw SQL.CannotCompleteDelegatedTransactionWithOpenResults(this);
-                    }
-                }
-
-                //  _parser may be nulled out during TdsExecuteTrannsactionManagerRequest.
-                //  Only use local variable after this call.
-                _parser.TdsExecuteTransactionManagerRequest(null, requestType, transactionName, isoLevel,
-                    ConnectionOptions.ConnectTimeout, internalTransaction, stateObj, isDelegateControlRequest);
-            }
-            finally
-            {
-                if (mustPutSession)
-                {
-                    parser.PutSession(stateObj);
-                }
-
-                if (releaseConnectionLock)
-                {
-                    ThreadHasParserLockForClose = false;
-                    _parserLock.Release();
-                }
-            }
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // DISTRIBUTED TRANSACTION METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        internal override void DelegatedTransactionEnded()
-        {
-            base.DelegatedTransactionEnded();
-        }
-
-        protected override byte[] GetDTCAddress()
-        {
-            byte[] dtcAddress = _parser.GetDTCAddress(ConnectionOptions.ConnectTimeout, _parser.GetSession(this));
-            Debug.Assert(null != dtcAddress, "null dtcAddress?");
-            return dtcAddress;
-        }
-
-        protected override void PropagateTransactionCookie(byte[] cookie)
-        {
-            _parser.PropagateDistributedTransaction(cookie, ConnectionOptions.ConnectTimeout, _parser._physicalStateObj);
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // LOGIN-RELATED METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        private void CompleteLogin(bool enlistOK)
-        {
-            _parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj);
-
-            if (_routingInfo == null)
-            { // ROR should not affect state of connection recovery
-                if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged)
-                {
-                    throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged);
-                }
-                if (!_sessionRecoveryAcknowledged)
-                {
-                    _currentSessionData = null;
-                    if (_recoverySessionData != null)
-                    {
-                        throw SQL.CR_NoCRAckAtReconnection(this);
-                    }
-                }
-                if (_currentSessionData != null && _recoverySessionData == null)
-                {
-                    _currentSessionData._initialDatabase = CurrentDatabase;
-                    _currentSessionData._initialCollation = _currentSessionData._collation;
-                    _currentSessionData._initialLanguage = _currentLanguage;
-                }
-                bool isEncrypted = _parser.EncryptionOptions == EncryptionOptions.ON;
-                if (_recoverySessionData != null)
-                {
-                    if (_recoverySessionData._encrypted != isEncrypted)
-                    {
-                        throw SQL.CR_EncryptionChanged(this);
-                    }
-                }
-                if (_currentSessionData != null)
-                {
-                    _currentSessionData._encrypted = isEncrypted;
-                }
-                _recoverySessionData = null;
-            }
-
-            Debug.Assert(SniContext.Snix_Login == Parser._physicalStateObj.SniContext, $"SniContext should be Snix_Login; actual Value: {Parser._physicalStateObj.SniContext}");
-            _parser._physicalStateObj.SniContext = SniContext.Snix_EnableMars;
-            _parser.EnableMars();
-
-            _fConnectionOpen = true; // mark connection as open
-
-            // for non-pooled connections, enlist in a distributed transaction
-            // if present - and user specified to enlist
-            if (enlistOK && ConnectionOptions.Enlist)
-            {
-                _parser._physicalStateObj.SniContext = SniContext.Snix_AutoEnlist;
-                Transaction tx = ADP.GetCurrentTransaction();
-                Enlist(tx);
-            }
-
-            _parser._physicalStateObj.SniContext = SniContext.Snix_Login;
-        }
-
-        private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, SecureString newSecurePassword)
-        {
-            // create a new login record
-            SqlLogin login = new SqlLogin();
-
-            // gather all the settings the user set in the connection string or
-            // properties and do the login
-            CurrentDatabase = server.ResolvedDatabaseName;
-            _currentPacketSize = ConnectionOptions.PacketSize;
-            _currentLanguage = ConnectionOptions.CurrentLanguage;
-
-            int timeoutInSeconds = 0;
-
-            // If a timeout tick value is specified, compute the timeout based
-            // upon the amount of time left in seconds.
-            if (!timeout.IsInfinite)
-            {
-                long t = timeout.MillisecondsRemaining / 1000;
-                if ((long)int.MaxValue > t)
-                {
-                    timeoutInSeconds = (int)t;
-                }
-            }
-
-            login.timeout = timeoutInSeconds;
-            login.userInstance = ConnectionOptions.UserInstance;
-            login.hostName = ConnectionOptions.ObtainWorkstationId();
-            login.userName = ConnectionOptions.UserID;
-            login.password = ConnectionOptions.Password;
-            login.applicationName = ConnectionOptions.ApplicationName;
-
-            login.language = _currentLanguage;
-            if (!login.userInstance)
-            { // Do not send attachdbfilename or database to SSE primary instance
-                login.database = CurrentDatabase; ;
-                login.attachDBFilename = ConnectionOptions.AttachDBFilename;
-            }
-
-            // VSTS#795621 - Ensure ServerName is Sent During TdsLogin To Enable Sql Azure Connectivity.
-            // Using server.UserServerName (versus ConnectionOptions.DataSource) since TdsLogin requires
-            // serverName to always be non-null.
-            login.serverName = server.UserServerName;
-
-            login.useReplication = ConnectionOptions.Replication;
-            login.useSSPI = ConnectionOptions.IntegratedSecurity;
-            login.packetSize = _currentPacketSize;
-            login.newPassword = newPassword;
-            login.readOnlyIntent = ConnectionOptions.ApplicationIntent == ApplicationIntent.ReadOnly;
-            login.credential = _credential;
-            if (newSecurePassword != null)
-            {
-                login.newSecurePassword = newSecurePassword;
-            }
-
-            TdsEnums.FeatureExtension requestedFeatures = TdsEnums.FeatureExtension.None;
-            if (ConnectionOptions.ConnectRetryCount > 0)
-            {
-                requestedFeatures |= TdsEnums.FeatureExtension.SessionRecovery;
-                _sessionRecoveryRequested = true;
-            }
-
-            if (_accessTokenInBytes != null)
-            {
-                requestedFeatures |= TdsEnums.FeatureExtension.FedAuth;
-                _fedAuthFeatureExtensionData = new FederatedAuthenticationFeatureExtensionData
-                {
-                    libraryType = TdsEnums.FedAuthLibrary.SecurityToken,
-                    fedAuthRequiredPreLoginResponse = _fedAuthRequired,
-                    accessToken = _accessTokenInBytes
-                };
-                // No need any further info from the server for token based authentication. So set _federatedAuthenticationRequested to true
-                _federatedAuthenticationRequested = true;
-            }
-
-            // The GLOBALTRANSACTIONS and UTF8 support features are implicitly requested
-            requestedFeatures |= TdsEnums.FeatureExtension.GlobalTransactions | TdsEnums.FeatureExtension.UTF8Support;
-            _parser.TdsLogin(login, requestedFeatures, _recoverySessionData, _fedAuthFeatureExtensionData);
-        }
-
-        private void LoginFailure()
-        {
-            // 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.
-            // Disconnect can be called if the connection is already closed - becomes
-            // no-op, so no issues there.
-            if (_parser != null)
-            {
-                _parser.Disconnect();
-            }
-        }
-
-        private void OpenLoginEnlist(TimeoutTimer timeout,
-                                    SqlConnectionString connectionOptions,
-                                    SqlCredential credential,
-                                    string newPassword,
-                                    SecureString newSecurePassword,
-                                    bool redirectedUserInstance)
-        {
-            bool useFailoverPartner; // should we use primary or secondary first
-            ServerInfo dataSource = new ServerInfo(connectionOptions);
-            string failoverPartner;
-
-            if (null != PoolGroupProviderInfo)
-            {
-                useFailoverPartner = PoolGroupProviderInfo.UseFailoverPartner;
-                failoverPartner = PoolGroupProviderInfo.FailoverPartner;
-            }
-            else
-            {
-                // Only ChangePassword or SSE User Instance comes through this code path.
-                useFailoverPartner = false;
-                failoverPartner = ConnectionOptions.FailoverPartner;
-            }
-
-            _timeoutErrorInternal.SetInternalSourceType(useFailoverPartner ? SqlConnectionInternalSourceType.Failover : SqlConnectionInternalSourceType.Principle);
-
-            bool hasFailoverPartner = !string.IsNullOrEmpty(failoverPartner);
-
-            // Open the connection and Login
-            try
-            {
-                _timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin);
-                if (hasFailoverPartner)
-                {
-                    _timeoutErrorInternal.SetFailoverScenario(true); // this is a failover scenario
-                    LoginWithFailover(
-                                useFailoverPartner,
-                                dataSource,
-                                failoverPartner,
-                                newPassword,
-                                newSecurePassword,
-                                redirectedUserInstance,
-                                connectionOptions,
-                                credential,
-                                timeout);
-                }
-                else
-                {
-                    _timeoutErrorInternal.SetFailoverScenario(false); // not a failover scenario
-                    LoginNoFailover(
-                            dataSource,
-                            newPassword,
-                            newSecurePassword,
-                            redirectedUserInstance,
-                            connectionOptions,
-                            credential,
-                            timeout);
-                }
-                _timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PostLogin);
-            }
-            catch (Exception e)
-            {
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    LoginFailure();
-                }
-                throw;
-            }
-            _timeoutErrorInternal.SetAllCompleteMarker();
-
-#if DEBUG
-            _parser._physicalStateObj.InvalidateDebugOnlyCopyOfSniContext();
-#endif
-        }
-
-        // Is the given Sql error one that should prevent retrying
-        //   to connect.
-        private bool IsDoNotRetryConnectError(SqlException exc)
-        {
-            return (TdsEnums.LOGON_FAILED == exc.Number) // actual logon failed, i.e. bad password
-                || (TdsEnums.PASSWORD_EXPIRED == exc.Number) // actual logon failed, i.e. password isExpired
-                || (TdsEnums.IMPERSONATION_FAILED == exc.Number)  // Insufficient privilege for named pipe, among others
-                || exc._doNotReconnect; // Exception explicitly suppressed reconnection attempts
-        }
-
-        // Attempt to login to a host that does not have a failover partner
-        //
-        //  Will repeatedly attempt to connect, but back off between each attempt so as not to clog the network.
-        //  Back off period increases for first few failures: 100ms, 200ms, 400ms, 800ms, then 1000ms for subsequent attempts
-        //
-        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-        //  DEVNOTE: The logic in this method is paralleled by the logic in LoginWithFailover.
-        //           Changes to either one should be examined to see if they need to be reflected in the other
-        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-        private void LoginNoFailover(ServerInfo serverInfo,
-                                     string newPassword,
-                                     SecureString newSecurePassword,
-                                     bool redirectedUserInstance,
-                                     SqlConnectionString connectionOptions,
-                                     SqlCredential credential,
-                                     TimeoutTimer timeout)
-        {
-            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
-
-            int sleepInterval = 100;  //milliseconds to sleep (back off) between attempts.
-
-            ResolveExtendedServerName(serverInfo, !redirectedUserInstance, connectionOptions);
-
-            long timeoutUnitInterval = 0;
-
-            if (connectionOptions.MultiSubnetFailover)
-            {
-                // Determine unit interval
-                if (timeout.IsInfinite)
-                {
-                    timeoutUnitInterval = checked((long)(ADP.FailoverTimeoutStep * (1000L * ADP.DefaultConnectionTimeout)));
-                }
-                else
-                {
-                    timeoutUnitInterval = checked((long)(ADP.FailoverTimeoutStep * timeout.MillisecondsRemaining));
-                }
-            }
-            // Only three ways out of this loop:
-            //  1) Successfully connected
-            //  2) Parser threw exception while main timer was expired
-            //  3) Parser threw logon failure-related exception
-            //  4) Parser threw exception in post-initial connect code,
-            //      such as pre-login handshake or during actual logon. (parser state != Closed)
-            //
-            //  Of these methods, only #1 exits normally. This preserves the call stack on the exception
-            //  back into the parser for the error cases.
-            int attemptNumber = 0;
-            TimeoutTimer intervalTimer = null;
-            while (true)
-            {
-                if (connectionOptions.MultiSubnetFailover)
-                {
-                    attemptNumber++;
-                    // Set timeout for this attempt, but don't exceed original timer
-                    long nextTimeoutInterval = checked(timeoutUnitInterval * attemptNumber);
-                    long milliseconds = timeout.MillisecondsRemaining;
-                    if (nextTimeoutInterval > milliseconds)
-                    {
-                        nextTimeoutInterval = milliseconds;
-                    }
-                    intervalTimer = TimeoutTimer.StartMillisecondsTimeout(nextTimeoutInterval);
-                }
-
-                // Re-allocate parser each time to make sure state is known
-                // RFC 50002652 - if parser was created by previous attempt, dispose it to properly close the socket, if created
-                if (_parser != null)
-                    _parser.Disconnect();
-
-                _parser = new TdsParser(ConnectionOptions.MARS, ConnectionOptions.Asynchronous);
-                Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, $"SniContext should be Undefined; actual Value: {Parser._physicalStateObj.SniContext}");
-
-                try
-                {
-                    AttemptOneLogin(serverInfo,
-                                    newPassword,
-                                    newSecurePassword,
-                                    !connectionOptions.MultiSubnetFailover,    // ignore timeout for SniOpen call unless MSF
-                                    connectionOptions.MultiSubnetFailover ? intervalTimer : timeout);
-
-                    if (connectionOptions.MultiSubnetFailover && null != ServerProvidedFailOverPartner)
-                    {
-                        // connection succeeded: trigger exception if server sends failover partner and MultiSubnetFailover is used
-                        throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: true, internalConnection: this);
-                    }
-
-                    if (_routingInfo != null)
-                    {
-                        if (routingAttempts > 0)
-                        {
-                            throw SQL.ROR_RecursiveRoutingNotSupported(this);
-                        }
-
-                        if (timeout.IsExpired)
-                        {
-                            throw SQL.ROR_TimeoutAfterRoutingInfo(this);
-                        }
-
-                        serverInfo = new ServerInfo(ConnectionOptions, _routingInfo, serverInfo.ResolvedServerName);
-                        _timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.RoutingDestination);
-                        _originalClientConnectionId = _clientConnectionId;
-                        _routingDestination = serverInfo.UserServerName;
-
-                        // restore properties that could be changed by the environment tokens
-                        _currentPacketSize = ConnectionOptions.PacketSize;
-                        _currentLanguage = _originalLanguage = ConnectionOptions.CurrentLanguage;
-                        CurrentDatabase = _originalDatabase = ConnectionOptions.InitialCatalog;
-                        _currentFailoverPartner = null;
-                        _instanceName = string.Empty;
-
-                        routingAttempts++;
-
-                        continue; // repeat the loop, but skip code reserved for failed connections (after the catch)
-                    }
-                    else
-                    {
-                        break; // leave the while loop -- we've successfully connected
-                    }
-                }
-                catch (SqlException sqlex)
-                {
-                    if (null == _parser
-                            || TdsParserState.Closed != _parser.State
-                            || IsDoNotRetryConnectError(sqlex)
-                            || timeout.IsExpired)
-                    {       // no more time to try again
-                        throw;  // Caller will call LoginFailure()
-                    }
-
-                    // Check sleep interval to make sure we won't exceed the timeout
-                    //  Do this in the catch block so we can re-throw the current exception
-                    if (timeout.MillisecondsRemaining <= sleepInterval)
-                    {
-                        throw;
-                    }
-                }
-
-                // We only get here when we failed to connect, but are going to re-try
-
-                // Switch to failover logic if the server provided a partner
-                if (null != ServerProvidedFailOverPartner)
-                {
-                    if (connectionOptions.MultiSubnetFailover)
-                    {
-                        // connection failed: do not allow failover to server-provided failover partner if MultiSubnetFailover is set
-                        throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: true, internalConnection: this);
-                    }
-                    Debug.Assert(ConnectionOptions.ApplicationIntent != ApplicationIntent.ReadOnly, "FAILOVER+AppIntent=RO: Should already fail (at LOGSHIPNODE in OnEnvChange)");
-
-                    _timeoutErrorInternal.ResetAndRestartPhase();
-                    _timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin);
-                    _timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.Failover);
-                    _timeoutErrorInternal.SetFailoverScenario(true); // this is a failover scenario
-                    LoginWithFailover(
-                                true,   // start by using failover partner, since we already failed to connect to the primary
-                                serverInfo,
-                                ServerProvidedFailOverPartner,
-                                newPassword,
-                                newSecurePassword,
-                                redirectedUserInstance,
-                                connectionOptions,
-                                credential,
-                                timeout);
-                    return; // LoginWithFailover successfully connected and handled entire connection setup
-                }
-
-                // Sleep for a bit to prevent clogging the network with requests,
-                //  then update sleep interval for next iteration (max 1 second interval)
-                Thread.Sleep(sleepInterval);
-                sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000;
-            }
-
-            if (null != PoolGroupProviderInfo)
-            {
-                // We must wait for CompleteLogin to finish for to have the
-                // env change from the server to know its designated failover
-                // partner; save this information in _currentFailoverPartner.
-                PoolGroupProviderInfo.FailoverCheck(this, false, connectionOptions, ServerProvidedFailOverPartner);
-            }
-            CurrentDataSource = originalServerInfo.UserServerName;
-        }
-
-        // Attempt to login to a host that has a failover partner
-        //
-        // Connection & timeout sequence is
-        //      First target, timeout = interval * 1
-        //      second target, timeout = interval * 1
-        //      sleep for 100ms
-        //      First target, timeout = interval * 2
-        //      Second target, timeout = interval * 2
-        //      sleep for 200ms
-        //      First Target, timeout = interval * 3
-        //      etc.
-        //
-        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-        //  DEVNOTE: The logic in this method is paralleled by the logic in LoginNoFailover.
-        //           Changes to either one should be examined to see if they need to be reflected in the other
-        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-        private void LoginWithFailover(
-                bool useFailoverHost,
-                ServerInfo primaryServerInfo,
-                string failoverHost,
-                string newPassword,
-                SecureString newSecurePassword,
-                bool redirectedUserInstance,
-                SqlConnectionString connectionOptions,
-                SqlCredential credential,
-                TimeoutTimer timeout
-            )
-        {
-            Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used");
-
-            int sleepInterval = 100;  //milliseconds to sleep (back off) between attempts.
-            long timeoutUnitInterval;
-
-            ServerInfo failoverServerInfo = new ServerInfo(connectionOptions, failoverHost);
-
-            ResolveExtendedServerName(primaryServerInfo, !redirectedUserInstance, connectionOptions);
-            if (null == ServerProvidedFailOverPartner)
-            {
-                ResolveExtendedServerName(failoverServerInfo, !redirectedUserInstance && failoverHost != primaryServerInfo.UserServerName, connectionOptions);
-            }
-
-            // Determine unit interval
-            if (timeout.IsInfinite)
-            {
-                timeoutUnitInterval = checked((long)(ADP.FailoverTimeoutStep * ADP.TimerFromSeconds(ADP.DefaultConnectionTimeout)));
-            }
-            else
-            {
-                timeoutUnitInterval = checked((long)(ADP.FailoverTimeoutStep * timeout.MillisecondsRemaining));
-            }
-
-            // Initialize loop variables
-            int attemptNumber = 0;
-
-            // Only three ways out of this loop:
-            //  1) Successfully connected
-            //  2) Parser threw exception while main timer was expired
-            //  3) Parser threw logon failure-related exception (LOGON_FAILED, PASSWORD_EXPIRED, etc)
-            //
-            //  Of these methods, only #1 exits normally. This preserves the call stack on the exception
-            //  back into the parser for the error cases.
-            while (true)
-            {
-                // Set timeout for this attempt, but don't exceed original timer
-                long nextTimeoutInterval = checked(timeoutUnitInterval * ((attemptNumber / 2) + 1));
-                long milliseconds = timeout.MillisecondsRemaining;
-                if (nextTimeoutInterval > milliseconds)
-                {
-                    nextTimeoutInterval = milliseconds;
-                }
-
-                TimeoutTimer intervalTimer = TimeoutTimer.StartMillisecondsTimeout(nextTimeoutInterval);
-
-                // Re-allocate parser each time to make sure state is known
-                // RFC 50002652 - if parser was created by previous attempt, dispose it to properly close the socket, if created
-                if (_parser != null)
-                    _parser.Disconnect();
-
-                _parser = new TdsParser(ConnectionOptions.MARS, ConnectionOptions.Asynchronous);
-                Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, $"SniContext should be Undefined; actual Value: {Parser._physicalStateObj.SniContext}");
-
-                ServerInfo currentServerInfo;
-                if (useFailoverHost)
-                {
-                    // Primary server may give us a different failover partner than the connection string indicates.  Update it
-                    if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner)
-                    {
-                        failoverServerInfo.SetDerivedNames(string.Empty, ServerProvidedFailOverPartner);
-                    }
-                    currentServerInfo = failoverServerInfo;
-                    _timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.Failover);
-                }
-                else
-                {
-                    currentServerInfo = primaryServerInfo;
-                    _timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.Principle);
-                }
-
-                try
-                {
-                    // Attempt login.  Use timerInterval for attempt timeout unless infinite timeout was requested.
-                    AttemptOneLogin(
-                            currentServerInfo,
-                            newPassword,
-                            newSecurePassword,
-                            false,          // Use timeout in SniOpen
-                            intervalTimer,
-                            withFailover: true
-                            );
-
-                    if (_routingInfo != null)
-                    {
-                        // We are in login with failover scenation and server sent routing information
-                        // 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.
-                        throw SQL.ROR_UnexpectedRoutingInfo(this);
-                    }
-
-                    break; // leave the while loop -- we've successfully connected
-                }
-                catch (SqlException sqlex)
-                {
-                    if (IsDoNotRetryConnectError(sqlex)
-                            || timeout.IsExpired)
-                    {       // no more time to try again
-                        throw;  // Caller will call LoginFailure()
-                    }
-
-                    if (IsConnectionDoomed)
-                    {
-                        throw;
-                    }
-
-                    if (1 == attemptNumber % 2)
-                    {
-                        // Check sleep interval to make sure we won't exceed the original timeout
-                        //  Do this in the catch block so we can re-throw the current exception
-                        if (timeout.MillisecondsRemaining <= sleepInterval)
-                        {
-                            throw;
-                        }
-                    }
-                }
-
-                // We only get here when we failed to connect, but are going to re-try
-
-                // After trying to connect to both servers fails, sleep for a bit to prevent clogging
-                //  the network with requests, then update sleep interval for next iteration (max 1 second interval)
-                if (1 == attemptNumber % 2)
-                {
-                    Thread.Sleep(sleepInterval);
-                    sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000;
-                }
-
-                // Update attempt number and target host
-                attemptNumber++;
-                useFailoverHost = !useFailoverHost;
-            }
-
-            // If we get here, connection/login succeeded!  Just a few more checks & record-keeping
-
-            // if connected to failover host, but said host doesn't have DbMirroring set up, throw an error
-            if (useFailoverHost && null == ServerProvidedFailOverPartner)
-            {
-                throw SQL.InvalidPartnerConfiguration(failoverHost, CurrentDatabase);
-            }
-
-            if (null != PoolGroupProviderInfo)
-            {
-                // We must wait for CompleteLogin to finish for to have the
-                // env change from the server to know its designated failover
-                // partner; save this information in _currentFailoverPartner.
-                PoolGroupProviderInfo.FailoverCheck(this, useFailoverHost, connectionOptions, ServerProvidedFailOverPartner);
-            }
-            CurrentDataSource = (useFailoverHost ? failoverHost : primaryServerInfo.UserServerName);
-        }
-
-        private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, SqlConnectionString options)
-        {
-            if (serverInfo.ExtendedServerName == null)
-            {
-                string host = serverInfo.UserServerName;
-                string protocol = serverInfo.UserProtocol;
-
-
-                serverInfo.SetDerivedNames(protocol, host);
-            }
-        }
-
-        // 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)
-        {
-            _routingInfo = null; // forget routing information
-
-            _parser._physicalStateObj.SniContext = SniContext.Snix_Connect;
-
-            _parser.Connect(serverInfo,
-                            this,
-                            ignoreSniOpenTimeout,
-                            timeout.LegacyTimerExpire,
-                            ConnectionOptions.Encrypt,
-                            ConnectionOptions.TrustServerCertificate,
-                            ConnectionOptions.IntegratedSecurity,
-                            withFailover);
-
-            _timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake);
-            _timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.LoginBegin);
-
-            _parser._physicalStateObj.SniContext = SniContext.Snix_Login;
-            this.Login(serverInfo, timeout, newPassword, newSecurePassword);
-
-            _timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth);
-            _timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PostLogin);
-
-            CompleteLogin(!ConnectionOptions.Pooling);
-
-            _timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PostLogin);
-        }
-
-
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // PREPARED COMMAND METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        protected override object ObtainAdditionalLocksForClose()
-        {
-            bool obtainParserLock = !ThreadHasParserLockForClose;
-            Debug.Assert(obtainParserLock || _parserLock.ThreadMayHaveLock(), "Thread claims to have lock, but lock is not taken");
-            if (obtainParserLock)
-            {
-                _parserLock.Wait(canReleaseFromAnyThread: false);
-                ThreadHasParserLockForClose = true;
-            }
-            return obtainParserLock;
-        }
-
-        protected override void ReleaseAdditionalLocksForClose(object lockToken)
-        {
-            Debug.Assert(lockToken is bool, "Lock token should be boolean");
-            if ((bool)lockToken)
-            {
-                ThreadHasParserLockForClose = false;
-                _parserLock.Release();
-            }
-        }
-
-        // called by SqlConnection.RepairConnection which is a relatively expensive way of repair inner connection
-        // prior to execution of request, used from EnlistTransaction, EnlistDistributedTransaction and ChangeDatabase
-        internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = 0)
-        {
-            Debug.Assert(!ThreadHasParserLockForClose, "Cannot call this method if caller has parser lock");
-            if (ThreadHasParserLockForClose)
-            {
-                return false; // we cannot restore if we cannot release lock
-            }
-
-            _parserLock.Wait(canReleaseFromAnyThread: false);
-            ThreadHasParserLockForClose = true;   // In case of error, let the connection know that we already own the parser lock
-            bool releaseConnectionLock = true;
-
-            try
-            {
-                Task reconnectTask = parent.ValidateAndReconnect(() =>
-                {
-                    ThreadHasParserLockForClose = false;
-                    _parserLock.Release();
-                    releaseConnectionLock = false;
-                }, timeout);
-                if (reconnectTask != null)
-                {
-                    AsyncHelper.WaitForCompletion(reconnectTask, timeout);
-                    return true;
-                }
-                return false;
-            }
-            finally
-            {
-                if (releaseConnectionLock)
-                {
-                    ThreadHasParserLockForClose = false;
-                    _parserLock.Release();
-                }
-            }
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // PARSER CALLBACKS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        internal void BreakConnection()
-        {
-            var connection = Connection;
-            DoomThisConnection();   // Mark connection as unusable, so it will be destroyed
-            if (null != connection)
-            {
-                connection.Close();
-            }
-        }
-
-        internal bool IgnoreEnvChange
-        { // true if we are only draining environment change tokens, used by TdsParser
-            get
-            {
-                return _routingInfo != null; // connection was routed, ignore rest of env change
-            }
-        }
-
-        internal void OnEnvChange(SqlEnvChange rec)
-        {
-            Debug.Assert(!IgnoreEnvChange, "This function should not be called if IgnoreEnvChange is set!");
-            switch (rec.type)
-            {
-                case TdsEnums.ENV_DATABASE:
-                    // If connection is not open and recovery is not in progress, store the server value as the original.
-                    if (!_fConnectionOpen && _recoverySessionData == null)
-                    {
-                        _originalDatabase = rec.newValue;
-                    }
-
-                    CurrentDatabase = rec.newValue;
-                    break;
-
-                case TdsEnums.ENV_LANG:
-                    // If connection is not open and recovery is not in progress, store the server value as the original.
-                    if (!_fConnectionOpen && _recoverySessionData == null)
-                    {
-                        _originalLanguage = rec.newValue;
-                    }
-
-                    _currentLanguage = rec.newValue;
-                    break;
-
-                case TdsEnums.ENV_PACKETSIZE:
-                    _currentPacketSize = int.Parse(rec.newValue, CultureInfo.InvariantCulture);
-                    break;
-
-                case TdsEnums.ENV_COLLATION:
-                    if (_currentSessionData != null)
-                    {
-                        _currentSessionData._collation = rec.newCollation;
-                    }
-                    break;
-
-                case TdsEnums.ENV_CHARSET:
-                case TdsEnums.ENV_LOCALEID:
-                case TdsEnums.ENV_COMPFLAGS:
-                case TdsEnums.ENV_BEGINTRAN:
-                case TdsEnums.ENV_COMMITTRAN:
-                case TdsEnums.ENV_ROLLBACKTRAN:
-                case TdsEnums.ENV_ENLISTDTC:
-                case TdsEnums.ENV_DEFECTDTC:
-                    // only used on parser
-                    break;
-
-                case TdsEnums.ENV_LOGSHIPNODE:
-                    if (ConnectionOptions.ApplicationIntent == ApplicationIntent.ReadOnly)
-                    {
-                        throw SQL.ROR_FailoverNotSupportedServer(this);
-                    }
-                    _currentFailoverPartner = rec.newValue;
-                    break;
-
-                case TdsEnums.ENV_PROMOTETRANSACTION:
-                    byte[] dtcToken = null;
-                    if (rec.newBinRented)
-                    {
-                        dtcToken = new byte[rec.newLength];
-                        Buffer.BlockCopy(rec.newBinValue, 0, dtcToken, 0, dtcToken.Length);
-                    }
-                    else
-                    {
-                        dtcToken = rec.newBinValue;
-                        rec.newBinValue = null;
-                    }
-                    PromotedDTCToken = dtcToken;
-                    break;
-
-                case TdsEnums.ENV_TRANSACTIONENDED:
-                    break;
-
-                case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
-                    // For now we skip these Yukon only env change notifications
-                    break;
-
-                case TdsEnums.ENV_SPRESETCONNECTIONACK:
-                    // connection is being reset
-                    if (_currentSessionData != null)
-                    {
-                        _currentSessionData.Reset();
-                    }
-                    break;
-
-                case TdsEnums.ENV_USERINSTANCE:
-                    _instanceName = rec.newValue;
-                    break;
-
-                case TdsEnums.ENV_ROUTING:
-                    if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0)
-                    {
-                        throw SQL.ROR_InvalidRoutingInfo(this);
-                    }
-                    _routingInfo = rec.newRoutingInfo;
-                    break;
-
-                default:
-                    Debug.Fail("Missed token in EnvChange!");
-                    break;
-            }
-        }
-
-        internal void OnLoginAck(SqlLoginAck rec)
-        {
-            _loginAck = rec;
-            if (_recoverySessionData != null)
-            {
-                if (_recoverySessionData._tdsVersion != rec.tdsVersion)
-                {
-                    throw SQL.CR_TDSVersionNotPreserved(this);
-                }
-            }
-            if (_currentSessionData != null)
-            {
-                _currentSessionData._tdsVersion = rec.tdsVersion;
-            }
-        }
-
-        internal void OnFeatureExtAck(int featureId, byte[] data)
-        {
-            if (_routingInfo != null)
-            {
-                return;
-            }
-            switch (featureId)
-            {
-                case TdsEnums.FEATUREEXT_SRECOVERY:
-                    {
-                        // Session recovery not requested
-                        if (!_sessionRecoveryRequested)
-                        {
-                            throw SQL.ParsingError();
-                        }
-                        _sessionRecoveryAcknowledged = true;
-
-#if DEBUG
-                        foreach (var s in _currentSessionData._delta)
-                        {
-                            Debug.Assert(s == null, "Delta should be null at this point");
-                        }
-#endif
-                        Debug.Assert(_currentSessionData._unrecoverableStatesCount == 0, "Unrecoverable states count should be 0");
-
-                        int i = 0;
-                        while (i < data.Length)
-                        {
-                            byte stateId = data[i]; i++;
-                            int len;
-                            byte bLen = data[i]; i++;
-                            if (bLen == 0xFF)
-                            {
-                                len = BitConverter.ToInt32(data, i); i += 4;
-                            }
-                            else
-                            {
-                                len = bLen;
-                            }
-                            byte[] stateData = new byte[len];
-                            Buffer.BlockCopy(data, i, stateData, 0, len); i += len;
-                            if (_recoverySessionData == null)
-                            {
-                                _currentSessionData._initialState[stateId] = stateData;
-                            }
-                            else
-                            {
-                                _currentSessionData._delta[stateId] = new SessionStateRecord { _data = stateData, _dataLength = len, _recoverable = true, _version = 0 };
-                                _currentSessionData._deltaDirty = true;
-                            }
-                        }
-                        break;
-                    }
-
-                case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS:
-                    {
-                        if (data.Length < 1)
-                        {
-                            throw SQL.ParsingError();
-                        }
-
-                        IsGlobalTransaction = true;
-                        if (1 == data[0])
-                        {
-                            IsGlobalTransactionsEnabledForServer = true;
-                        }
-                        break;
-                    }
-                case TdsEnums.FEATUREEXT_FEDAUTH:
-                    {
-                        if (!_federatedAuthenticationRequested)
-                        {
-                            throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId);
-                        }
-
-                        Debug.Assert(_fedAuthFeatureExtensionData != null, "_fedAuthFeatureExtensionData must not be null when _federatedAuthenticatonRequested == true");
-
-                        switch (_fedAuthFeatureExtensionData.Value.libraryType)
-                        {
-                            case TdsEnums.FedAuthLibrary.SecurityToken:
-                                // The server shouldn't have sent any additional data with the ack (like a nonce)
-                                if (data.Length != 0)
-                                {
-                                    throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData);
-                                }
-                                break;
-
-                            default:
-                                Debug.Fail("Unknown _fedAuthLibrary type");
-                                throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType);
-                        }
-                        _federatedAuthenticationAcknowledged = true;
-                        break;
-                    }
-
-                case TdsEnums.FEATUREEXT_UTF8SUPPORT:
-                    {
-                        if (data.Length < 1)
-                        {
-                            throw SQL.ParsingError();
-                        }
-                        break;
-                    }
-                default:
-                    {
-                        // Unknown feature ack
-                        throw SQL.ParsingError();
-                    }
-            }
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // Helper methods for Locks
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        // Indicates if the current thread claims to hold the parser lock
-        internal bool ThreadHasParserLockForClose
-        {
-            get
-            {
-                return _threadIdOwningParserLock == Thread.CurrentThread.ManagedThreadId;
-            }
-            set
-            {
-                Debug.Assert(_parserLock.ThreadMayHaveLock(), "Should not modify ThreadHasParserLockForClose without taking the lock first");
-                Debug.Assert(_threadIdOwningParserLock == -1 || _threadIdOwningParserLock == Thread.CurrentThread.ManagedThreadId, "Another thread already claims to own the parser lock");
-
-                if (value)
-                {
-                    // If setting to true, then the thread owning the lock is the current thread
-                    _threadIdOwningParserLock = Thread.CurrentThread.ManagedThreadId;
-                }
-                else if (_threadIdOwningParserLock == Thread.CurrentThread.ManagedThreadId)
-                {
-                    // If setting to false and currently owns the lock, then no-one owns the lock
-                    _threadIdOwningParserLock = -1;
-                }
-                // else This thread didn't own the parser lock and doesn't claim to own it, so do nothing
-            }
-        }
-
-        internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
-        {
-            return base.TryOpenConnectionInternal(outerConnection, connectionFactory, retry, userOptions);
-        }
-    }
-
-    internal sealed class ServerInfo
-    {
-        internal string ExtendedServerName { get; private set; } // the resolved servername with protocol
-        internal string ResolvedServerName { get; private set; } // the resolved servername only
-        internal string ResolvedDatabaseName { get; private set; } // name of target database after resolution
-        internal string UserProtocol { get; private set; } // the user specified protocol
-
-        // The original user-supplied server name from the connection string.
-        // If connection string has no Data Source, the value is set to string.Empty.
-        // In case of routing, will be changed to routing destination
-        internal string UserServerName
-        {
-            get
-            {
-                return _userServerName;
-            }
-            private set
-            {
-                _userServerName = value;
-            }
-        }
-        private string _userServerName;
-
-        internal readonly string PreRoutingServerName;
-
-        // Initialize server info from connection options,
-        internal ServerInfo(SqlConnectionString userOptions) : this(userOptions, userOptions.DataSource) { }
-
-        // Initialize server info from connection options, but override DataSource with given server name
-        internal ServerInfo(SqlConnectionString userOptions, string serverName)
-        {
-            //-----------------
-            // Preconditions
-            Debug.Assert(null != userOptions);
-
-            //-----------------
-            //Method body
-
-            Debug.Assert(serverName != null, "server name should never be null");
-            UserServerName = (serverName ?? string.Empty); // ensure user server name is not null
-
-            UserProtocol = string.Empty;
-            ResolvedDatabaseName = userOptions.InitialCatalog;
-            PreRoutingServerName = null;
-        }
-
-
-        // Initialize server info from connection options, but override DataSource with given server name
-        internal ServerInfo(SqlConnectionString userOptions, RoutingInfo routing, string preRoutingServerName)
-        {
-            //-----------------
-            // Preconditions
-            Debug.Assert(null != userOptions && null != routing);
-
-            //-----------------
-            //Method body
-            Debug.Assert(routing.ServerName != null, "server name should never be null");
-            if (routing == null || routing.ServerName == null)
-            {
-                UserServerName = string.Empty; // ensure user server name is not null
-            }
-            else
-            {
-                UserServerName = string.Format(CultureInfo.InvariantCulture, "{0},{1}", routing.ServerName, routing.Port);
-            }
-            PreRoutingServerName = preRoutingServerName;
-            UserProtocol = TdsEnums.TCP;
-            SetDerivedNames(UserProtocol, UserServerName);
-            ResolvedDatabaseName = userOptions.InitialCatalog;
-        }
-
-        internal void SetDerivedNames(string protocol, string serverName)
-        {
-            // The following concatenates the specified netlib network protocol to the host string, if netlib is not null
-            // and the flag is on.  This allows the user to specify the network protocol for the connection - but only
-            // when using the Dbnetlib dll.  If the protocol is not specified, the netlib will
-            // try all protocols in the order listed in the Client Network Utility.  Connect will
-            // then fail if all protocols fail.
-            if (!string.IsNullOrEmpty(protocol))
-            {
-                ExtendedServerName = protocol + ":" + serverName;
-            }
-            else
-            {
-                ExtendedServerName = serverName;
-            }
-            ResolvedServerName = serverName;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalTransaction.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalTransaction.cs
deleted file mode 100644 (file)
index d88656a..0000000
+++ /dev/null
@@ -1,517 +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.Data.Common;
-using System.Diagnostics;
-using System.Threading;
-
-namespace System.Data.SqlClient
-{
-    internal enum TransactionState
-    {
-        Pending = 0,
-        Active = 1,
-        Aborted = 2,
-        Committed = 3,
-        Unknown = 4,
-    }
-
-    internal enum TransactionType
-    {
-        LocalFromTSQL = 1,
-        LocalFromAPI = 2,
-        Delegated = 3,
-        Distributed = 4,
-        Context = 5,     // only valid in proc.
-    };
-
-    internal sealed class SqlInternalTransaction
-    {
-        internal const long NullTransactionId = 0;
-
-        private TransactionState _transactionState;
-        private readonly TransactionType _transactionType;
-        private long _transactionId;             // passed in the MARS headers
-        private int _openResultCount;           // passed in the MARS headers
-        private SqlInternalConnection _innerConnection;
-        private bool _disposing;                 // used to prevent us from throwing exceptions while we're disposing
-        private WeakReference _parent;                    // weak ref to the outer transaction object; needs to be weak to allow GC to occur.
-
-
-        internal bool RestoreBrokenConnection { get; set; }
-        internal bool ConnectionHasBeenRestored { get; set; }
-
-        internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction) : this(innerConnection, type, outerTransaction, NullTransactionId)
-        {
-        }
-
-        internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId)
-        {
-            _innerConnection = innerConnection;
-            _transactionType = type;
-
-            if (null != outerTransaction)
-            {
-                _parent = new WeakReference(outerTransaction);
-            }
-
-            _transactionId = transactionId;
-            RestoreBrokenConnection = false;
-            ConnectionHasBeenRestored = false;
-        }
-
-        internal bool HasParentTransaction
-        {
-            get
-            {
-                // Return true if we are an API started local transaction, or if we were a TSQL
-                // started local transaction and were then wrapped with a parent transaction as
-                // a result of a later API begin transaction.
-                bool result = ((TransactionType.LocalFromAPI == _transactionType) ||
-                                (TransactionType.LocalFromTSQL == _transactionType && _parent != null));
-                return result;
-            }
-        }
-
-        internal bool IsAborted
-        {
-            get
-            {
-                return (TransactionState.Aborted == _transactionState);
-            }
-        }
-
-        internal bool IsActive
-        {
-            get
-            {
-                return (TransactionState.Active == _transactionState);
-            }
-        }
-
-        internal bool IsCommitted
-        {
-            get
-            {
-                return (TransactionState.Committed == _transactionState);
-            }
-        }
-
-        internal bool IsCompleted
-        {
-            get
-            {
-                return (TransactionState.Aborted == _transactionState
-                     || TransactionState.Committed == _transactionState
-                     || TransactionState.Unknown == _transactionState);
-            }
-        }
-
-        internal bool IsDelegated
-        {
-            get
-            {
-                bool result = (TransactionType.Delegated == _transactionType);
-                return result;
-            }
-        }
-
-        internal bool IsDistributed
-        {
-            get
-            {
-                bool result = (TransactionType.Distributed == _transactionType);
-                return result;
-            }
-        }
-
-        internal bool IsLocal
-        {
-            get
-            {
-                bool result = (TransactionType.LocalFromTSQL == _transactionType
-                            || TransactionType.LocalFromAPI == _transactionType
-                            );
-                return result;
-            }
-        }
-
-        internal bool IsOrphaned
-        {
-            get
-            {
-                // An internal transaction is orphaned when its parent has been
-                // reclaimed by GC.
-                bool result;
-                if (null == _parent)
-                {
-                    // No parent, so we better be LocalFromTSQL.  Should we even return in this case -
-                    // since it could be argued this is invalid?
-                    Debug.Fail("Why are we calling IsOrphaned with no parent?");
-                    Debug.Assert(_transactionType == TransactionType.LocalFromTSQL, "invalid state");
-                    result = false;
-                }
-                else if (null == _parent.Target)
-                {
-                    // We have an parent, but parent was GC'ed.
-                    result = true;
-                }
-                else
-                {
-                    // We have an parent, and parent is alive.
-                    result = false;
-                }
-
-                return result;
-            }
-        }
-
-        internal bool IsZombied
-        {
-            get
-            {
-                return (null == _innerConnection);
-            }
-        }
-
-
-        internal int OpenResultsCount
-        {
-            get
-            {
-                return _openResultCount;
-            }
-        }
-
-        internal SqlTransaction Parent
-        {
-            get
-            {
-                SqlTransaction result = null;
-                // Should we protect against this, since this probably is an invalid state?
-                Debug.Assert(null != _parent, "Why are we calling Parent with no parent?");
-                if (null != _parent)
-                {
-                    result = (SqlTransaction)_parent.Target;
-                }
-                return result;
-            }
-        }
-
-        internal long TransactionId
-        {
-            get
-            {
-                return _transactionId;
-            }
-            set
-            {
-                Debug.Assert(NullTransactionId == _transactionId, "setting transaction cookie while one is active?");
-                _transactionId = value;
-            }
-        }
-
-        internal void Activate()
-        {
-            _transactionState = TransactionState.Active;
-        }
-
-        private void CheckTransactionLevelAndZombie()
-        {
-            try
-            {
-                if (!IsZombied && GetServerTransactionLevel() == 0)
-                {
-                    // If not zombied, not closed, and not in transaction, zombie.
-                    Zombie();
-                }
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-                Zombie(); // If exception caught when trying to check level, zombie.
-            }
-        }
-
-        internal void CloseFromConnection()
-        {
-            SqlInternalConnection innerConnection = _innerConnection;
-
-            Debug.Assert(innerConnection != null, "How can we be here if the connection is null?");
-
-            bool processFinallyBlock = true;
-            try
-            {
-                innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null, false);
-            }
-            catch (Exception e)
-            {
-                processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                throw;
-            }
-            finally
-            {
-                if (processFinallyBlock)
-                {
-                    // Always ensure we're zombied; Yukon will send an EnvChange that
-                    // will cause the zombie, but only if we actually go to the wire;
-                    // Sphinx and Shiloh won't send the env change, so we have to handle
-                    // them ourselves.
-                    Zombie();
-                }
-            }
-        }
-
-        internal void Commit()
-        {
-            if (_innerConnection.IsLockedForBulkCopy)
-            {
-                throw SQL.ConnectionLockedForBcpEvent();
-            }
-
-            _innerConnection.ValidateConnectionForExecute(null);
-
-            // If this transaction has been completed, throw exception since it is unusable.
-            try
-            {
-                // COMMIT ignores transaction names, and so there is no reason to pass it anything.  COMMIT
-                // simply commits the transaction from the most recent BEGIN, nested or otherwise.
-                _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, null, false);
-                {
-                    ZombieParent();
-                }
-            }
-            catch (Exception e)
-            {
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    CheckTransactionLevelAndZombie();
-                }
-
-                throw;
-            }
-        }
-
-        internal void Completed(TransactionState transactionState)
-        {
-            Debug.Assert(TransactionState.Active < transactionState, "invalid transaction completion state?");
-            _transactionState = transactionState;
-            Zombie();
-        }
-
-        internal int DecrementAndObtainOpenResultCount()
-        {
-            int openResultCount = Interlocked.Decrement(ref _openResultCount);
-            if (openResultCount < 0)
-            {
-                throw SQL.OpenResultCountExceeded();
-            }
-            return openResultCount;
-        }
-
-        internal void Dispose()
-        {
-            this.Dispose(true);
-            System.GC.SuppressFinalize(this);
-        }
-
-        private /*protected override*/ void Dispose(bool disposing)
-        {
-            if (disposing)
-            {
-                if (null != _innerConnection)
-                {
-                    // implicitly rollback if transaction still valid
-                    _disposing = true;
-                    this.Rollback();
-                }
-            }
-        }
-
-        private int GetServerTransactionLevel()
-        {
-            // This function is needed for those times when it is impossible to determine the server's
-            // transaction level, unless the user's arguments were parsed - which is something we don't want
-            // to do.  An example when it is impossible to determine the level is after a rollback.
-
-            using (SqlCommand transactionLevelCommand = new SqlCommand("set @out = @@trancount", (SqlConnection)(_innerConnection.Owner)))
-            {
-                transactionLevelCommand.Transaction = Parent;
-
-                SqlParameter parameter = new SqlParameter("@out", SqlDbType.Int);
-                parameter.Direction = ParameterDirection.Output;
-                transactionLevelCommand.Parameters.Add(parameter);
-
-                transactionLevelCommand.RunExecuteReader(CommandBehavior.Default, RunBehavior.UntilDone, returnStream: false);
-
-                return (int)parameter.Value;
-            }
-        }
-
-        internal int IncrementAndObtainOpenResultCount()
-        {
-            int openResultCount = Interlocked.Increment(ref _openResultCount);
-
-            if (openResultCount < 0)
-            {
-                throw SQL.OpenResultCountExceeded();
-            }
-            return openResultCount;
-        }
-
-        internal void InitParent(SqlTransaction transaction)
-        {
-            Debug.Assert(_parent == null, "Why do we have a parent on InitParent?");
-            _parent = new WeakReference(transaction);
-        }
-
-        internal void Rollback()
-        {
-            if (_innerConnection.IsLockedForBulkCopy)
-            {
-                throw SQL.ConnectionLockedForBcpEvent();
-            }
-
-            _innerConnection.ValidateConnectionForExecute(null);
-
-            try
-            {
-                // If no arg is given to ROLLBACK it will rollback to the outermost begin - rolling back
-                // all nested transactions as well as the outermost transaction.
-                _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null, false);
-
-                // Since Rollback will rollback to outermost begin, no need to check
-                // server transaction level.  This transaction has been completed.
-                Zombie();
-            }
-            catch (Exception e)
-            {
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    CheckTransactionLevelAndZombie();
-
-                    if (!_disposing)
-                    {
-                        throw;
-                    }
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        internal void Rollback(string transactionName)
-        {
-            if (_innerConnection.IsLockedForBulkCopy)
-            {
-                throw SQL.ConnectionLockedForBcpEvent();
-            }
-
-            _innerConnection.ValidateConnectionForExecute(null);
-
-            // ROLLBACK takes either a save point name or a transaction name.  It will rollback the
-            // transaction to either the save point with the save point name or begin with the
-            // transaction name.  NOTE: for simplicity it is possible to give all save point names
-            // the same name, and ROLLBACK will simply rollback to the most recent save point with the
-            // save point name.
-            if (string.IsNullOrEmpty(transactionName))
-                throw SQL.NullEmptyTransactionName();
-
-            try
-            {
-                _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, transactionName, IsolationLevel.Unspecified, null, false);
-            }
-            catch (Exception e)
-            {
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    CheckTransactionLevelAndZombie();
-                }
-                throw;
-            }
-        }
-
-        internal void Save(string savePointName)
-        {
-            _innerConnection.ValidateConnectionForExecute(null);
-
-            // ROLLBACK takes either a save point name or a transaction name.  It will rollback the
-            // transaction to either the save point with the save point name or begin with the
-            // transaction name.  So, to rollback a nested transaction you must have a save point.
-            // SAVE TRANSACTION MUST HAVE AN ARGUMENT!!!  Save Transaction without an arg throws an
-            // exception from the server.  So, an overload for SaveTransaction without an arg doesn't make
-            // sense to have.  Save Transaction does not affect the transaction level.
-            if (string.IsNullOrEmpty(savePointName))
-                throw SQL.NullEmptyTransactionName();
-
-            try
-            {
-                _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Save, savePointName, IsolationLevel.Unspecified, null, false);
-            }
-            catch (Exception e)
-            {
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    CheckTransactionLevelAndZombie();
-                }
-
-                throw;
-            }
-        }
-
-        internal void Zombie()
-        {
-            // Called by several places in the code to ensure that the outer
-            // transaction object has been zombied and the parser has broken
-            // it's reference to us.
-
-            // NOTE: we'll be called from the TdsParser when it gets appropriate
-            // ENVCHANGE events that indicate the transaction has completed, however
-            // we cannot rely upon those events occurring in the case of pre-Yukon
-            // servers (and when we don't go to the wire because the connection
-            // is broken) so we can also be called from the Commit/Rollback/Save
-            // methods to handle that case as well.
-
-            // There are two parts to a full zombie:
-            // 1) Zombie parent and disconnect outer transaction from internal transaction
-            // 2) Disconnect internal transaction from connection and parser
-            // Number 1 needs to be done whenever a SqlTransaction object is completed.  Number
-            // 2 is only done when a transaction is actually completed.  Since users can begin
-            // transactions both in and outside of the API, and since nested begins are not actual
-            // transactions we need to distinguish between #1 and #2.
-
-            ZombieParent();
-
-            SqlInternalConnection innerConnection = _innerConnection;
-            _innerConnection = null;
-
-            if (null != innerConnection)
-            {
-                innerConnection.DisconnectTransaction(this);
-            }
-        }
-
-        private void ZombieParent()
-        {
-            if (null != _parent)
-            {
-                SqlTransaction parent = (SqlTransaction)_parent.Target;
-                if (null != parent)
-                {
-                    parent.Zombie();
-                }
-                _parent = null;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlMetadataFactory.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlMetadataFactory.cs
deleted file mode 100644 (file)
index 107c340..0000000
+++ /dev/null
@@ -1,286 +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.Data;
-using System.IO;
-using System.Data.ProviderBase;
-using System.Data.Common;
-using System.Text;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlMetaDataFactory : DbMetaDataFactory
-    {
-        private const string _serverVersionNormalized90 = "09.00.0000";
-        private const string _serverVersionNormalized10 = "10.00.0000";
-
-        public SqlMetaDataFactory(Stream XMLStream,
-                                    string serverVersion,
-                                    string serverVersionNormalized) :
-                base(XMLStream, serverVersion, serverVersionNormalized) { }
-
-        private void addUDTsToDataTypesTable(DataTable dataTypesTable, SqlConnection connection, string ServerVersion)
-        {
-            const string sqlCommand =
-                "select " +
-                    "assemblies.name, " +
-                    "types.assembly_class, " +
-                    "ASSEMBLYPROPERTY(assemblies.name, 'VersionMajor') as version_major, " +
-                    "ASSEMBLYPROPERTY(assemblies.name, 'VersionMinor') as version_minor, " +
-                    "ASSEMBLYPROPERTY(assemblies.name, 'VersionBuild') as version_build, " +
-                    "ASSEMBLYPROPERTY(assemblies.name, 'VersionRevision') as version_revision, " +
-                    "ASSEMBLYPROPERTY(assemblies.name, 'CultureInfo') as culture_info, " +
-                    "ASSEMBLYPROPERTY(assemblies.name, 'PublicKey') as public_key, " +
-                    "is_nullable, " +
-                    "is_fixed_length, " +
-                    "max_length " +
-                "from sys.assemblies as assemblies  join sys.assembly_types as types " +
-                "on assemblies.assembly_id = types.assembly_id ";
-
-            // pre 9.0/Yukon servers do not have UDTs
-            if (0 > string.Compare(ServerVersion, _serverVersionNormalized90, StringComparison.OrdinalIgnoreCase))
-            {
-                return;
-            }
-
-            // Execute the SELECT statement
-            SqlCommand command = connection.CreateCommand();
-            command.CommandText = sqlCommand;
-            DataRow newRow = null;
-            DataColumn providerDbtype = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType];
-            DataColumn columnSize = dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize];
-            DataColumn isFixedLength = dataTypesTable.Columns[DbMetaDataColumnNames.IsFixedLength];
-            DataColumn isSearchable = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable];
-            DataColumn isLiteralSupported = dataTypesTable.Columns[DbMetaDataColumnNames.IsLiteralSupported];
-            DataColumn typeName = dataTypesTable.Columns[DbMetaDataColumnNames.TypeName];
-            DataColumn isNullable = dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable];
-
-            if ((providerDbtype == null) ||
-                (columnSize == null) ||
-                (isFixedLength == null) ||
-                (isSearchable == null) ||
-                (isLiteralSupported == null) ||
-                (typeName == null) ||
-                (isNullable == null))
-            {
-                throw ADP.InvalidXml();
-            }
-
-            const int columnSizeIndex = 10;
-            const int isFixedLengthIndex = 9;
-            const int isNullableIndex = 8;
-            const int assemblyNameIndex = 0;
-            const int assemblyClassIndex = 1;
-            const int versionMajorIndex = 2;
-            const int versionMinorIndex = 3;
-            const int versionBuildIndex = 4;
-            const int versionRevisionIndex = 5;
-            const int cultureInfoIndex = 6;
-            const int publicKeyIndex = 7;
-
-
-            using (IDataReader reader = command.ExecuteReader())
-            {
-
-                object[] values = new object[11];
-                while (reader.Read())
-                {
-
-                    reader.GetValues(values);
-                    newRow = dataTypesTable.NewRow();
-
-                    newRow[providerDbtype] = SqlDbType.Udt;
-
-                    if (values[columnSizeIndex] != DBNull.Value)
-                    {
-                        newRow[columnSize] = values[columnSizeIndex];
-                    }
-
-                    if (values[isFixedLengthIndex] != DBNull.Value)
-                    {
-                        newRow[isFixedLength] = values[isFixedLengthIndex];
-                    }
-
-                    newRow[isSearchable] = true;
-                    newRow[isLiteralSupported] = false;
-                    if (values[isNullableIndex] != DBNull.Value)
-                    {
-                        newRow[isNullable] = values[isNullableIndex];
-                    }
-
-                    if ((values[assemblyNameIndex] != DBNull.Value) &&
-                        (values[assemblyClassIndex] != DBNull.Value) &&
-                        (values[versionMajorIndex] != DBNull.Value) &&
-                        (values[versionMinorIndex] != DBNull.Value) &&
-                        (values[versionBuildIndex] != DBNull.Value) &&
-                        (values[versionRevisionIndex] != DBNull.Value))
-                    {
-
-                        StringBuilder nameString = new StringBuilder();
-                        nameString.Append(values[assemblyClassIndex].ToString());
-                        nameString.Append(", ");
-                        nameString.Append(values[assemblyNameIndex].ToString());
-                        nameString.Append(", Version=");
-
-                        nameString.Append(values[versionMajorIndex].ToString());
-                        nameString.Append(".");
-                        nameString.Append(values[versionMinorIndex].ToString());
-                        nameString.Append(".");
-                        nameString.Append(values[versionBuildIndex].ToString());
-                        nameString.Append(".");
-                        nameString.Append(values[versionRevisionIndex].ToString());
-
-                        if (values[cultureInfoIndex] != DBNull.Value)
-                        {
-                            nameString.Append(", Culture=");
-                            nameString.Append(values[cultureInfoIndex].ToString());
-                        }
-
-                        if (values[publicKeyIndex] != DBNull.Value)
-                        {
-
-                            nameString.Append(", PublicKeyToken=");
-
-                            StringBuilder resultString = new StringBuilder();
-                            byte[] byteArrayValue = (byte[])values[publicKeyIndex];
-                            foreach (byte b in byteArrayValue)
-                            {
-                                resultString.Append(string.Format("{0,-2:x2}", b));
-                            }
-                            nameString.Append(resultString.ToString());
-                        }
-
-                        newRow[typeName] = nameString.ToString();
-                        dataTypesTable.Rows.Add(newRow);
-                        newRow.AcceptChanges();
-                    } // if assembly name
-
-                }//end while
-            } // end using
-        }
-
-        private void AddTVPsToDataTypesTable(DataTable dataTypesTable, SqlConnection connection, string ServerVersion)
-        {
-
-            const string sqlCommand =
-                "select " +
-                    "name, " +
-                    "is_nullable, " +
-                    "max_length " +
-                "from sys.types " +
-                "where is_table_type = 1";
-
-            // TODO: update this check once the server upgrades major version number!!!
-            // pre 9.0/Yukon servers do not have Table types
-            if (0 > string.Compare(ServerVersion, _serverVersionNormalized10, StringComparison.OrdinalIgnoreCase))
-            {
-                return;
-            }
-
-            // Execute the SELECT statement
-            SqlCommand command = connection.CreateCommand();
-            command.CommandText = sqlCommand;
-            DataRow newRow = null;
-            DataColumn providerDbtype = dataTypesTable.Columns[DbMetaDataColumnNames.ProviderDbType];
-            DataColumn columnSize = dataTypesTable.Columns[DbMetaDataColumnNames.ColumnSize];
-            DataColumn isSearchable = dataTypesTable.Columns[DbMetaDataColumnNames.IsSearchable];
-            DataColumn isLiteralSupported = dataTypesTable.Columns[DbMetaDataColumnNames.IsLiteralSupported];
-            DataColumn typeName = dataTypesTable.Columns[DbMetaDataColumnNames.TypeName];
-            DataColumn isNullable = dataTypesTable.Columns[DbMetaDataColumnNames.IsNullable];
-
-            if ((providerDbtype == null) ||
-                (columnSize == null) ||
-                (isSearchable == null) ||
-                (isLiteralSupported == null) ||
-                (typeName == null) ||
-                (isNullable == null))
-            {
-                throw ADP.InvalidXml();
-            }
-
-            const int columnSizeIndex = 2;
-            const int isNullableIndex = 1;
-            const int typeNameIndex = 0;
-
-            using (IDataReader reader = command.ExecuteReader())
-            {
-
-                object[] values = new object[11];
-                while (reader.Read())
-                {
-
-                    reader.GetValues(values);
-                    newRow = dataTypesTable.NewRow();
-
-                    newRow[providerDbtype] = SqlDbType.Structured;
-
-                    if (values[columnSizeIndex] != DBNull.Value)
-                    {
-                        newRow[columnSize] = values[columnSizeIndex];
-                    }
-
-                    newRow[isSearchable] = false;
-                    newRow[isLiteralSupported] = false;
-                    if (values[isNullableIndex] != DBNull.Value)
-                    {
-                        newRow[isNullable] = values[isNullableIndex];
-                    }
-
-                    if (values[typeNameIndex] != DBNull.Value)
-                    {
-                        newRow[typeName] = values[typeNameIndex];
-                        dataTypesTable.Rows.Add(newRow);
-                        newRow.AcceptChanges();
-                    } // if type name
-                }//end while
-            } // end using
-        }
-
-        private DataTable GetDataTypesTable(SqlConnection connection)
-        {
-            // verify the existance of the table in the data set
-            DataTable dataTypesTable = CollectionDataSet.Tables[DbMetaDataCollectionNames.DataTypes];
-            if (dataTypesTable == null)
-            {
-                throw ADP.UnableToBuildCollection(DbMetaDataCollectionNames.DataTypes);
-            }
-
-            // copy the table filtering out any rows that don't apply to tho current version of the prrovider
-            dataTypesTable = CloneAndFilterCollection(DbMetaDataCollectionNames.DataTypes, null);
-
-            addUDTsToDataTypesTable(dataTypesTable, connection, ServerVersionNormalized);
-            AddTVPsToDataTypesTable(dataTypesTable, connection, ServerVersionNormalized);
-
-            dataTypesTable.AcceptChanges();
-            return dataTypesTable;
-        }
-
-        protected override DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection)
-        {
-            SqlConnection sqlConnection = (SqlConnection)connection;
-            DataTable resultTable = null;
-
-            if (collectionName == DbMetaDataCollectionNames.DataTypes)
-            {
-                if (ADP.IsEmptyArray(restrictions) == false)
-                {
-                    throw ADP.TooManyRestrictions(DbMetaDataCollectionNames.DataTypes);
-                }
-                resultTable = GetDataTypesTable(sqlConnection);
-            }
-
-            if (resultTable == null)
-            {
-                throw ADP.UnableToBuildCollection(collectionName);
-            }
-
-            return resultTable;
-
-        }
-
-
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationEventArgs.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationEventArgs.cs
deleted file mode 100644 (file)
index 1fc02f2..0000000
+++ /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.
-
-namespace System.Data.SqlClient
-{
-    public class SqlNotificationEventArgs : EventArgs
-    {
-        private readonly SqlNotificationType _type;
-        private readonly SqlNotificationInfo _info;
-        private readonly SqlNotificationSource _source;
-
-        public SqlNotificationEventArgs(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source)
-        {
-            _info = info;
-            _source = source;
-            _type = type;
-        }
-
-        public SqlNotificationType Type => _type;
-
-        public SqlNotificationInfo Info => _info;
-
-        public SqlNotificationSource Source => _source;
-
-        internal static SqlNotificationEventArgs s_notifyError = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.Error, SqlNotificationSource.Object);
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationInfo.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationInfo.cs
deleted file mode 100644 (file)
index 983919a..0000000
+++ /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.
-
-namespace System.Data.SqlClient
-{
-    public enum SqlNotificationInfo
-    {
-        Truncate = 0,
-        Insert = 1,
-        Update = 2,
-        Delete = 3,
-        Drop = 4,
-        Alter = 5,
-        Restart = 6,
-        Error = 7,
-        Query = 8,
-        Invalid = 9,
-        Options = 10,
-        Isolation = 11,
-        Expired = 12,
-        Resource = 13,
-        PreviousFire = 14,
-        TemplateLimit = 15,
-        Merge = 16,
-
-        // use negative values for client-only-generated values
-        Unknown = -1,
-        AlreadyChanged = -2
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationSource.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationSource.cs
deleted file mode 100644 (file)
index 52be708..0000000
+++ /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.
-
-namespace System.Data.SqlClient
-{
-    public enum SqlNotificationSource
-    {
-        Data = 0,
-        Timeout = 1,
-        Object = 2,
-        Database = 3,
-        System = 4,
-        Statement = 5,
-        Environment = 6,
-        Execution = 7,
-        Owner = 8,
-
-        // use negative values for client-only-generated values
-        Unknown = -1,
-        Client = -2
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationType.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlNotificationType.cs
deleted file mode 100644 (file)
index e7bb989..0000000
+++ /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.
-
-namespace System.Data.SqlClient
-{
-    public enum SqlNotificationType
-    {
-        Change = 0,
-        Subscribe = 1,
-
-        // use negative values for client-only-generated values
-        Unknown = -1
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs
deleted file mode 100644 (file)
index 862c683..0000000
+++ /dev/null
@@ -1,2095 +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.Collections.Generic;
-using System.Data.Common;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.IO;
-using System.Globalization;
-using System.Reflection;
-using System.Xml;
-using MSS = Microsoft.SqlServer.Server;
-
-using Microsoft.SqlServer.Server;
-
-using System.ComponentModel.Design.Serialization;
-using System.Text;
-using System.Threading;
-
-namespace System.Data.SqlClient
-{
-    internal abstract class DataFeed
-    {
-    }
-
-    internal class StreamDataFeed : DataFeed
-    {
-        internal Stream _source;
-
-        internal StreamDataFeed(Stream source)
-        {
-            _source = source;
-        }
-    }
-
-    internal class TextDataFeed : DataFeed
-    {
-        private static UnicodeEncoding s_defaultEncoding;
-
-        internal TextReader _source;
-
-        internal TextDataFeed(TextReader source)
-        {
-            _source = source;
-        }
-
-        internal static UnicodeEncoding DefaultEncoding
-        {
-            get
-            {
-                UnicodeEncoding encoding = s_defaultEncoding;
-                if (encoding is null)
-                {
-                    encoding = new UnicodeEncoding(false, false);
-                    encoding = Interlocked.CompareExchange(ref s_defaultEncoding, encoding, null) ?? encoding;
-                }
-                return encoding;
-            }
-        }
-    }
-
-    internal class XmlDataFeed : DataFeed
-    {
-        internal XmlReader _source;
-
-        internal XmlDataFeed(XmlReader source)
-        {
-            _source = source;
-        }
-    }
-
-    [TypeConverter(typeof(SqlParameterConverter))]
-    public sealed partial class SqlParameter : DbParameter, IDbDataParameter, ICloneable
-    {
-        [Flags]
-        private enum SqlParameterFlags : short
-        {
-            None = 0,
-            IsNullable = 1 << 1,
-            IsNull = 1 << 2,
-            IsSqlParameterSqlType = 1 << 3,
-            CoercedValueIsSqlType = 1 << 4,
-            CoercedValueIsDataFeed = 1 << 5,
-            IsDerivedParameterTypeName = 1 << 6,
-            SourceColumnNullMapping = 1 << 7,
-            HasScale = 1 << 8,  // V1.0 compat, ignore _hasScale
-        }
-
-        private MetaType _metaType;
-        private SqlCollation _collation;
-        private SqlMetaDataXmlSchemaCollection _xmlSchemaCollection;
-
-        private string _udtTypeName;
-        private string _typeName;
-        private Exception _udtLoadError;
-
-        private string _parameterName;
-        private byte _precision;
-        private byte _scale;
-
-        private MetaType _internalMetaType;
-        private SqlBuffer _sqlBufferReturnValue;
-        private INullable _valueAsINullable;
-        private int _actualSize = -1;
-
-        private SqlParameterFlags _flags = SqlParameterFlags.IsNull;
-
-        private DataRowVersion _sourceVersion;
-
-        public SqlParameter() : base()
-        {
-        }
-
-        public SqlParameter(string parameterName, SqlDbType dbType) : this()
-        {
-            this.ParameterName = parameterName;
-            this.SqlDbType = dbType;
-        }
-
-        public SqlParameter(string parameterName, object value) : this()
-        {
-            Debug.Assert(!(value is SqlDbType), "use SqlParameter(string, SqlDbType)");
-
-            this.ParameterName = parameterName;
-            this.Value = value;
-        }
-
-        public SqlParameter(string parameterName, SqlDbType dbType, int size) : this()
-        {
-            this.ParameterName = parameterName;
-            this.SqlDbType = dbType;
-            this.Size = size;
-        }
-
-        public SqlParameter(string parameterName, SqlDbType dbType, int size, string sourceColumn) : this()
-        {
-            this.ParameterName = parameterName;
-            this.SqlDbType = dbType;
-            this.Size = size;
-            this.SourceColumn = sourceColumn;
-        }
-
-        public SqlParameter(
-            string parameterName,
-            SqlDbType dbType,
-            int size,
-            ParameterDirection direction,
-            bool isNullable,
-            byte precision,
-            byte scale,
-            string sourceColumn,
-            DataRowVersion sourceVersion,
-            object value
-        ) : this(parameterName, dbType, size, sourceColumn)
-        {
-            this.Direction = direction;
-            this.IsNullable = isNullable;
-            this.Precision = precision;
-            this.Scale = scale;
-            this.SourceVersion = sourceVersion;
-            this.Value = value;
-        }
-
-        public SqlParameter(
-            string parameterName,
-            SqlDbType dbType,
-            int size,
-            ParameterDirection direction,
-            byte precision,
-            byte scale,
-            string sourceColumn,
-            DataRowVersion sourceVersion,
-            bool sourceColumnNullMapping,
-            object value,
-            string xmlSchemaCollectionDatabase,
-            string xmlSchemaCollectionOwningSchema,
-            string xmlSchemaCollectionName
-        ) : this()
-        {
-            this.ParameterName = parameterName;
-            this.SqlDbType = dbType;
-            this.Size = size;
-            this.Direction = direction;
-            this.Precision = precision;
-            this.Scale = scale;
-            this.SourceColumn = sourceColumn;
-            this.SourceVersion = sourceVersion;
-            this.SourceColumnNullMapping = sourceColumnNullMapping;
-            this.Value = value;
-            this.XmlSchemaCollectionDatabase = xmlSchemaCollectionDatabase;
-            this.XmlSchemaCollectionOwningSchema = xmlSchemaCollectionOwningSchema;
-            this.XmlSchemaCollectionName = xmlSchemaCollectionName;
-        }
-
-        private SqlParameter(SqlParameter source) : this()
-        {
-            ADP.CheckArgumentNull(source, nameof(source));
-
-            source.CloneHelper(this);
-
-            ICloneable cloneable = (_value as ICloneable);
-            if (null != cloneable)
-            {
-                _value = cloneable.Clone();
-            }
-        }
-
-        internal SqlCollation Collation
-        {
-            get
-            {
-                return _collation;
-            }
-            set
-            {
-                _collation = value;
-            }
-        }
-
-        public SqlCompareOptions CompareInfo
-        {
-            // Bits 21 through 25 represent the CompareInfo
-            get
-            {
-                SqlCollation collation = _collation;
-                if (null != collation)
-                {
-                    return collation.SqlCompareOptions;
-                }
-                return SqlCompareOptions.None;
-            }
-            set
-            {
-                SqlCollation collation = _collation;
-                if (null == collation)
-                {
-                    _collation = collation = new SqlCollation();
-                }
-
-                // Copied from SQLString.x_iValidSqlCompareOptionMask
-                SqlCompareOptions validSqlCompareOptionMask =
-                    SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreWidth |
-                    SqlCompareOptions.IgnoreNonSpace | SqlCompareOptions.IgnoreKanaType |
-                    SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2;
-
-                if ((value & validSqlCompareOptionMask) != value)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(CompareInfo));
-                }
-                collation.SqlCompareOptions = value;
-            }
-        }
-
-        public string XmlSchemaCollectionDatabase
-        {
-            get
-            {
-                return (_xmlSchemaCollection?.Database ?? string.Empty);
-            }
-            set
-            {
-                EnsureXmlSchemaCollectionExists();
-                _xmlSchemaCollection.Database = value;
-            }
-        }
-
-        public string XmlSchemaCollectionOwningSchema
-        {
-            get
-            {
-                return (_xmlSchemaCollection?.OwningSchema ?? string.Empty);
-            }
-            set
-            {
-                EnsureXmlSchemaCollectionExists();
-                _xmlSchemaCollection.OwningSchema = value;
-            }
-        }
-
-        public string XmlSchemaCollectionName
-        {
-            get
-            {
-                return (_xmlSchemaCollection?.Name ?? string.Empty);
-            }
-            set
-            {
-                EnsureXmlSchemaCollectionExists();
-                _xmlSchemaCollection.Name = value;
-            }
-        }
-
-        public override DbType DbType
-        {
-            get
-            {
-                return GetMetaTypeOnly().DbType;
-            }
-            set
-            {
-                MetaType metatype = _metaType;
-                if ((null == metatype) || (metatype.DbType != value) ||
-                        // Two special datetime cases for backward compat
-                        // DbType.Date and DbType.Time should always be treated as setting DbType.DateTime instead
-                        value == DbType.Date ||
-                        value == DbType.Time)
-                {
-                    PropertyTypeChanging();
-                    _metaType = MetaType.GetMetaTypeFromDbType(value);
-                }
-            }
-        }
-
-        public override void ResetDbType()
-        {
-            ResetSqlDbType();
-        }
-
-        internal MetaType InternalMetaType
-        {
-            get
-            {
-                Debug.Assert(null != _internalMetaType, "null InternalMetaType");
-                return _internalMetaType;
-            }
-            set { _internalMetaType = value; }
-        }
-
-        internal bool IsDerivedParameterTypeName
-        {
-            get => _flags.HasFlag(SqlParameterFlags.IsDerivedParameterTypeName);
-            set => Set(SqlParameterFlags.IsDerivedParameterTypeName, value);
-        }
-
-        public int LocaleId
-        {
-            // Lowest 20 bits represent LocaleId
-            get
-            {
-                SqlCollation collation = _collation;
-                if (null != collation)
-                {
-                    return collation.LCID;
-                }
-                return 0;
-            }
-            set
-            {
-                SqlCollation collation = _collation;
-                if (null == collation)
-                {
-                    _collation = collation = new SqlCollation();
-                }
-                if (value != (SqlCollation.MaskLcid & value))
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(LocaleId));
-                }
-                collation.LCID = value;
-            }
-        }
-
-        internal MSS.SmiParameterMetaData MetaDataForSmi(out ParameterPeekAheadValue peekAhead)
-        {
-            peekAhead = null;
-            MetaType mt = ValidateTypeLengths();
-            long actualLen = GetActualSize();
-            long maxLen = this.Size;
-
-            // GetActualSize returns bytes length, but smi expects char length for
-            //  character types, so adjust
-            if (!mt.IsLong)
-            {
-                if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
-                {
-                    actualLen = actualLen / sizeof(char);
-                }
-
-                if (actualLen > maxLen)
-                {
-                    maxLen = actualLen;
-                }
-            }
-
-            // Determine maxLength for types that ValidateTypeLengths won't figure out
-            if (0 == maxLen)
-            {
-                if (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType)
-                {
-                    maxLen = MSS.SmiMetaData.MaxBinaryLength;
-                }
-                else if (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType)
-                {
-                    maxLen = MSS.SmiMetaData.MaxANSICharacters;
-                }
-                else if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
-                {
-                    maxLen = MSS.SmiMetaData.MaxUnicodeCharacters;
-                }
-            }
-            else if ((maxLen > MSS.SmiMetaData.MaxBinaryLength && (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType))
-                  || (maxLen > MSS.SmiMetaData.MaxANSICharacters && (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType))
-                  || (maxLen > MSS.SmiMetaData.MaxUnicodeCharacters && (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)))
-            {
-                maxLen = -1;
-            }
-
-
-            int localeId = LocaleId;
-            if (0 == localeId && mt.IsCharType)
-            {
-                object value = GetCoercedValue();
-                if (value is SqlString && !((SqlString)value).IsNull)
-                {
-                    localeId = ((SqlString)value).LCID;
-                }
-                else
-                {
-                    localeId = CultureInfo.CurrentCulture.LCID;
-                }
-            }
-
-            SqlCompareOptions compareOpts = CompareInfo;
-            if (0 == compareOpts && mt.IsCharType)
-            {
-                object value = GetCoercedValue();
-                if (value is SqlString && !((SqlString)value).IsNull)
-                {
-                    compareOpts = ((SqlString)value).SqlCompareOptions;
-                }
-                else
-                {
-                    compareOpts = MSS.SmiMetaData.GetDefaultForType(mt.SqlDbType).CompareOptions;
-                }
-            }
-
-            string typeSpecificNamePart1 = null;
-            string typeSpecificNamePart2 = null;
-            string typeSpecificNamePart3 = null;
-
-            if (SqlDbType.Xml == mt.SqlDbType)
-            {
-                typeSpecificNamePart1 = this.XmlSchemaCollectionDatabase;
-                typeSpecificNamePart2 = this.XmlSchemaCollectionOwningSchema;
-                typeSpecificNamePart3 = this.XmlSchemaCollectionName;
-            }
-            else if (SqlDbType.Udt == mt.SqlDbType || (SqlDbType.Structured == mt.SqlDbType && !string.IsNullOrEmpty(this.TypeName)))
-            {
-                // Split the input name. The type name is specified as single 3 part name.
-                // NOTE: ParseTypeName throws if format is incorrect
-                string[] names;
-                if (SqlDbType.Udt == mt.SqlDbType)
-                {
-                    names = ParseTypeName(UdtTypeName, true /* is UdtTypeName */);
-                }
-                else
-                {
-                    names = ParseTypeName(this.TypeName, false /* not UdtTypeName */);
-                }
-
-                if (1 == names.Length)
-                {
-                    typeSpecificNamePart3 = names[0];
-                }
-                else if (2 == names.Length)
-                {
-                    typeSpecificNamePart2 = names[0];
-                    typeSpecificNamePart3 = names[1];
-                }
-                else if (3 == names.Length)
-                {
-                    typeSpecificNamePart1 = names[0];
-                    typeSpecificNamePart2 = names[1];
-                    typeSpecificNamePart3 = names[2];
-                }
-                else
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(names));
-                }
-
-                if ((!string.IsNullOrEmpty(typeSpecificNamePart1) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart1.Length)
-                    || (!string.IsNullOrEmpty(typeSpecificNamePart2) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart2.Length)
-                    || (!string.IsNullOrEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length))
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(names));
-                }
-            }
-
-            byte precision = GetActualPrecision();
-            byte scale = GetActualScale();
-
-            // precision for decimal types may still need adjustment.
-            if (SqlDbType.Decimal == mt.SqlDbType)
-            {
-                if (0 == precision)
-                {
-                    precision = TdsEnums.DEFAULT_NUMERIC_PRECISION;
-                }
-            }
-
-            // Sub-field determination
-            List<SmiExtendedMetaData> fields = null;
-            MSS.SmiMetaDataPropertyCollection extendedProperties = null;
-            if (SqlDbType.Structured == mt.SqlDbType)
-            {
-                GetActualFieldsAndProperties(out fields, out extendedProperties, out peekAhead);
-            }
-
-            return new MSS.SmiParameterMetaData(mt.SqlDbType,
-                                            maxLen,
-                                            precision,
-                                            scale,
-                                            localeId,
-                                            compareOpts,
-                                            null,           // Udt type not used for parameters
-                                            SqlDbType.Structured == mt.SqlDbType,
-                                            fields,
-                                            extendedProperties,
-                                            this.ParameterNameFixed,
-                                            typeSpecificNamePart1,
-                                            typeSpecificNamePart2,
-                                            typeSpecificNamePart3,
-                                            this.Direction);
-        }
-
-        internal bool ParameterIsSqlType
-        {
-            get => _flags.HasFlag(SqlParameterFlags.IsSqlParameterSqlType);
-            set => Set(SqlParameterFlags.IsSqlParameterSqlType, value);
-        }
-
-        public override string ParameterName
-        {
-            get
-            {
-                string parameterName = _parameterName;
-                return (parameterName ?? string.Empty);
-            }
-            set
-            {
-                if (string.IsNullOrEmpty(value) || (value.Length < TdsEnums.MAX_PARAMETER_NAME_LENGTH)
-                    || (('@' == value[0]) && (value.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH)))
-                {
-                    if (_parameterName != value)
-                    {
-                        PropertyChanging();
-                        _parameterName = value;
-                    }
-                }
-                else
-                {
-                    throw SQL.InvalidParameterNameLength(value);
-                }
-            }
-        }
-
-        internal string ParameterNameFixed
-        {
-            get
-            {
-                string parameterName = ParameterName;
-                if ((0 < parameterName.Length) && ('@' != parameterName[0]))
-                {
-                    parameterName = "@" + parameterName;
-                }
-                Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
-                return parameterName;
-            }
-        }
-
-        [DefaultValue((byte)0)]
-        public new byte Precision
-        {
-            get
-            {
-                return PrecisionInternal;
-            }
-            set
-            {
-                PrecisionInternal = value;
-            }
-        }
-
-        internal byte PrecisionInternal
-        {
-            get
-            {
-                byte precision = _precision;
-                SqlDbType dbtype = GetMetaSqlDbTypeOnly();
-                if ((0 == precision) && (SqlDbType.Decimal == dbtype))
-                {
-                    precision = ValuePrecision(SqlValue);
-                }
-                return precision;
-            }
-            set
-            {
-                SqlDbType sqlDbType = SqlDbType;
-                if (sqlDbType == SqlDbType.Decimal && value > TdsEnums.MAX_NUMERIC_PRECISION)
-                {
-                    throw SQL.PrecisionValueOutOfRange(value);
-                }
-                if (_precision != value)
-                {
-                    PropertyChanging();
-                    _precision = value;
-                }
-            }
-        }
-
-        private bool ShouldSerializePrecision()
-        {
-            return (0 != _precision);
-        }
-
-        [DefaultValue((byte)0)]
-        public new byte Scale
-        {
-            get
-            {
-                return ScaleInternal;
-            }
-            set
-            {
-                ScaleInternal = value;
-            }
-        }
-
-        internal byte ScaleInternal
-        {
-            get
-            {
-                byte scale = _scale;
-                SqlDbType dbtype = GetMetaSqlDbTypeOnly();
-                if ((0 == scale) && (SqlDbType.Decimal == dbtype))
-                {
-                    scale = ValueScale(SqlValue);
-                }
-                return scale;
-            }
-            set
-            {
-                if (_scale != value || !_flags.HasFlag(SqlParameterFlags.HasScale))
-                {
-                    PropertyChanging();
-                    _scale = value;
-                    Set(SqlParameterFlags.HasScale, true);
-                    _actualSize = -1;   // Invalidate actual size such that it is re-calculated
-                }
-            }
-        }
-
-        private bool ShouldSerializeScale()
-        {
-            return (0 != _scale); // V1.0 compat, ignore _hasScale
-        }
-
-        [DbProviderSpecificTypeProperty(true)]
-        public SqlDbType SqlDbType
-        {
-            get
-            {
-                return GetMetaTypeOnly().SqlDbType;
-            }
-            set
-            {
-                MetaType metatype = _metaType;
-
-                if (TdsEnums.SmallVarBinary == value)
-                {
-                    throw SQL.InvalidSqlDbType(value);
-                }
-                if ((null == metatype) || (metatype.SqlDbType != value))
-                {
-                    PropertyTypeChanging();
-                    _metaType = MetaType.GetMetaTypeFromSqlDbType(value, value == SqlDbType.Structured);
-                }
-            }
-        }
-
-        private bool ShouldSerializeSqlDbType()
-        {
-            return (null != _metaType);
-        }
-
-        public void ResetSqlDbType()
-        {
-            if (null != _metaType)
-            {
-                PropertyTypeChanging();
-                _metaType = null;
-            }
-        }
-
-        public object SqlValue
-        {
-            get
-            {
-                if (_udtLoadError != null)
-                {
-                    throw _udtLoadError;
-                }
-
-                if (_value != null)
-                {
-                    if (_value == DBNull.Value)
-                    {
-                        return MetaType.GetNullSqlValue(GetMetaTypeOnly().SqlType);
-                    }
-                    if (_value is INullable)
-                    {
-                        return _value;
-                    }
-
-                    // For Date and DateTime2, return the CLR object directly without converting it to a SqlValue
-                    // GetMetaTypeOnly() will convert _value to a string in the case of char or char[], so only check
-                    // the SqlDbType for DateTime. This is the only case when we might return the CLR value directly.
-                    if (_value is DateTime)
-                    {
-                        SqlDbType sqlDbType = GetMetaTypeOnly().SqlDbType;
-                        if (sqlDbType == SqlDbType.Date || sqlDbType == SqlDbType.DateTime2)
-                        {
-                            return _value;
-                        }
-                    }
-
-                    return (MetaType.GetSqlValueFromComVariant(_value));
-                }
-                else if (_sqlBufferReturnValue != null)
-                {
-                    return _sqlBufferReturnValue.SqlValue;
-                }
-                return null;
-            }
-            set
-            {
-                Value = value;
-            }
-        }
-
-        public string UdtTypeName
-        {
-            get
-            {
-                string typeName = _udtTypeName;
-                return (typeName ?? string.Empty);
-            }
-            set
-            {
-                _udtTypeName = value;
-            }
-        }
-
-        public string TypeName
-        {
-            get => (_typeName ?? string.Empty);
-            set
-            {
-                _typeName = value;
-                Set(SqlParameterFlags.IsDerivedParameterTypeName, false);
-            }
-        }
-
-        [TypeConverter(typeof(StringConverter))]
-        public override object Value
-        {
-            get
-            {
-                if (_udtLoadError != null)
-                {
-                    throw _udtLoadError;
-                }
-
-                if (_value != null)
-                {
-                    return _value;
-                }
-                else if (_sqlBufferReturnValue != null)
-                {
-                    if (ParameterIsSqlType)
-                    {
-                        return _sqlBufferReturnValue.SqlValue;
-                    }
-                    return _sqlBufferReturnValue.Value;
-                }
-                return null;
-            }
-            set
-            {
-                _value = value;
-                _sqlBufferReturnValue = null;
-                _coercedValue = null;
-                _valueAsINullable = _value as INullable;
-                Set(SqlParameterFlags.IsSqlParameterSqlType, (_valueAsINullable != null));
-                Set(SqlParameterFlags.IsNull, ((_value == null) || (_value == DBNull.Value) || (((_valueAsINullable != null)) && (_valueAsINullable.IsNull))));
-                _udtLoadError = null;
-                _actualSize = -1;
-            }
-        }
-
-        internal INullable ValueAsINullable
-        {
-            get
-            {
-                return _valueAsINullable;
-            }
-        }
-
-        internal bool IsNull
-        {
-            get
-            {
-                // NOTE: Udts can change their value any time
-                if (_internalMetaType.SqlDbType == Data.SqlDbType.Udt)
-                {
-                    Set(SqlParameterFlags.IsNull, ((_value == null) || (_value == DBNull.Value) || ((_flags.HasFlag(SqlParameterFlags.IsSqlParameterSqlType)) && (_valueAsINullable.IsNull))));
-                }
-                return _flags.HasFlag(SqlParameterFlags.IsNull);
-            }
-        }
-
-        //
-        // always returns data in bytes - except for non-unicode chars, which will be in number of chars
-        //
-        internal int GetActualSize()
-        {
-            MetaType mt = InternalMetaType;
-            SqlDbType actualType = mt.SqlDbType;
-            // NOTE: Users can change the Udt at any time, so we may need to recalculate
-            if ((_actualSize == -1) || (actualType == Data.SqlDbType.Udt))
-            {
-                _actualSize = 0;
-                object val = GetCoercedValue();
-                bool isSqlVariant = false;
-
-                if (IsNull && !mt.IsVarTime)
-                {
-                    return 0;
-                }
-
-                // if this is a backend SQLVariant type, then infer the TDS type from the SQLVariant type
-                if (actualType == SqlDbType.Variant)
-                {
-                    mt = MetaType.GetMetaTypeFromValue(val, streamAllowed: false);
-                    actualType = MetaType.GetSqlDataType(mt.TDSType, 0 /*no user type*/, 0 /*non-nullable type*/).SqlDbType;
-                    isSqlVariant = true;
-                }
-
-                if (mt.IsFixed)
-                {
-                    _actualSize = mt.FixedLength;
-                }
-                else
-                {
-                    // @hack: until we have ForceOffset behavior we have the following semantics:
-                    // @hack: if the user supplies a Size through the Size property or constructor,
-                    // @hack: we only send a MAX of Size bytes over.  If the actualSize is < Size, then
-                    // @hack: we send over actualSize
-                    int coercedSize = 0;
-                    bool coercedValueIsDataFeed = _flags.HasFlag(SqlParameterFlags.CoercedValueIsDataFeed);
-                    bool coercedValueIsSqlType = _flags.HasFlag(SqlParameterFlags.CoercedValueIsSqlType);
-                    bool isNull = _flags.HasFlag(SqlParameterFlags.IsNull);
-                    // get the actual length of the data, in bytes
-                    switch (actualType)
-                    {
-                        case SqlDbType.NChar:
-                        case SqlDbType.NVarChar:
-                        case SqlDbType.NText:
-                        case SqlDbType.Xml:
-                            {
-                                coercedSize = ((!isNull) && (!coercedValueIsDataFeed)) ? (StringSize(val, coercedValueIsSqlType)) : 0;
-                                _actualSize = (ShouldSerializeSize() ? Size : 0);
-                                _actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
-                                if (_actualSize == -1)
-                                    _actualSize = coercedSize;
-                                _actualSize <<= 1;
-                            }
-                            break;
-                        case SqlDbType.Char:
-                        case SqlDbType.VarChar:
-                        case SqlDbType.Text:
-                            {
-                                // for these types, ActualSize is the num of chars, not actual bytes - since non-unicode chars are not always uniform size
-                                coercedSize = ((!isNull) && (!coercedValueIsDataFeed)) ? (StringSize(val, coercedValueIsSqlType)) : 0;
-                                _actualSize = (ShouldSerializeSize() ? Size : 0);
-                                _actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
-                                if (_actualSize == -1)
-                                    _actualSize = coercedSize;
-                            }
-                            break;
-                        case SqlDbType.Binary:
-                        case SqlDbType.VarBinary:
-                        case SqlDbType.Image:
-                        case SqlDbType.Timestamp:
-                            coercedSize = ((!isNull) && (!coercedValueIsDataFeed)) ? (BinarySize(val, coercedValueIsSqlType)) : 0;
-                            _actualSize = (ShouldSerializeSize() ? Size : 0);
-                            _actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
-                            if (_actualSize == -1)
-                                _actualSize = coercedSize;
-                            break;
-                        case SqlDbType.Udt:
-                            if (!IsNull)
-                            {
-                                coercedSize = SerializationHelperSql9.SizeInBytes(val);
-                            }
-                            break;
-                        case SqlDbType.Structured:
-                            coercedSize = -1;
-                            break;
-                        case SqlDbType.Time:
-                            _actualSize = (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
-                            break;
-                        case SqlDbType.DateTime2:
-                            // Date in number of days (3 bytes) + time
-                            _actualSize = 3 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
-                            break;
-                        case SqlDbType.DateTimeOffset:
-                            // Date in days (3 bytes) + offset in minutes (2 bytes) + time
-                            _actualSize = 5 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
-                            break;
-                        default:
-                            Debug.Fail("Unknown variable length type!");
-                            break;
-                    }
-
-                    // don't even send big values over to the variant
-                    if (isSqlVariant && (coercedSize > TdsEnums.TYPE_SIZE_LIMIT))
-                        throw SQL.ParameterInvalidVariant(this.ParameterName);
-                }
-            }
-
-            return _actualSize;
-        }
-
-        object ICloneable.Clone()
-        {
-            return new SqlParameter(this);
-        }
-
-        // Coerced Value is also used in SqlBulkCopy.ConvertValue(object value, _SqlMetaData metadata)
-        internal static object CoerceValue(object value, MetaType destinationType, out bool coercedToDataFeed, out bool typeChanged, bool allowStreaming = true)
-        {
-            Debug.Assert(!(value is DataFeed), "Value provided should not already be a data feed");
-            Debug.Assert(!ADP.IsNull(value), "Value provided should not be null");
-            Debug.Assert(null != destinationType, "null destinationType");
-
-            coercedToDataFeed = false;
-            typeChanged = false;
-            Type currentType = value.GetType();
-
-            if ((typeof(object) != destinationType.ClassType) &&
-                    (currentType != destinationType.ClassType) &&
-                    ((currentType != destinationType.SqlType) || (SqlDbType.Xml == destinationType.SqlDbType)))
-            {   // Special case for Xml types (since we need to convert SqlXml into a string)
-                try
-                {
-                    // Assume that the type changed
-                    typeChanged = true;
-                    if ((typeof(string) == destinationType.ClassType))
-                    {
-                        // For Xml data, destination Type is always string
-                        if (typeof(SqlXml) == currentType)
-                        {
-                            value = MetaType.GetStringFromXml((XmlReader)(((SqlXml)value).CreateReader()));
-                        }
-                        else if (typeof(SqlString) == currentType)
-                        {
-                            typeChanged = false;   // Do nothing
-                        }
-                        else if (typeof(XmlReader).IsAssignableFrom(currentType))
-                        {
-                            if (allowStreaming)
-                            {
-                                coercedToDataFeed = true;
-                                value = new XmlDataFeed((XmlReader)value);
-                            }
-                            else
-                            {
-                                value = MetaType.GetStringFromXml((XmlReader)value);
-                            }
-                        }
-                        else if (typeof(char[]) == currentType)
-                        {
-                            value = new string((char[])value);
-                        }
-                        else if (typeof(SqlChars) == currentType)
-                        {
-                            value = new string(((SqlChars)value).Value);
-                        }
-                        else if (value is TextReader && allowStreaming)
-                        {
-                            coercedToDataFeed = true;
-                            value = new TextDataFeed((TextReader)value);
-                        }
-                        else
-                        {
-                            value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
-                        }
-                    }
-                    else if ((DbType.Currency == destinationType.DbType) && (typeof(string) == currentType))
-                    {
-                        value = decimal.Parse((string)value, NumberStyles.Currency, (IFormatProvider)null);
-                    }
-                    else if ((typeof(SqlBytes) == currentType) && (typeof(byte[]) == destinationType.ClassType))
-                    {
-                        typeChanged = false;    // Do nothing
-                    }
-                    else if ((typeof(string) == currentType) && (SqlDbType.Time == destinationType.SqlDbType))
-                    {
-                        value = TimeSpan.Parse((string)value);
-                    }
-                    else if ((typeof(string) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
-                    {
-                        value = DateTimeOffset.Parse((string)value, (IFormatProvider)null);
-                    }
-                    else if ((typeof(DateTime) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
-                    {
-                        value = new DateTimeOffset((DateTime)value);
-                    }
-                    else if (TdsEnums.SQLTABLE == destinationType.TDSType && (
-                                value is DataTable ||
-                                value is DbDataReader ||
-                                value is System.Collections.Generic.IEnumerable<SqlDataRecord>))
-                    {
-                        // no conversion for TVPs.
-                        typeChanged = false;
-                    }
-                    else if (destinationType.ClassType == typeof(byte[]) && value is Stream && allowStreaming)
-                    {
-                        coercedToDataFeed = true;
-                        value = new StreamDataFeed((Stream)value);
-                    }
-                    else
-                    {
-                        value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
-                    }
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableExceptionType(e))
-                    {
-                        throw;
-                    }
-
-                    throw ADP.ParameterConversionFailed(value, destinationType.ClassType, e);
-                }
-            }
-
-            Debug.Assert(allowStreaming || !coercedToDataFeed, "Streaming is not allowed, but type was coerced into a data feed");
-            Debug.Assert(value.GetType() == currentType ^ typeChanged, "Incorrect value for typeChanged");
-            return value;
-        }
-
-        internal void FixStreamDataForNonPLP()
-        {
-            object value = GetCoercedValue();
-            AssertCachedPropertiesAreValid();
-            if (!_flags.HasFlag(SqlParameterFlags.CoercedValueIsDataFeed))
-            {
-                return;
-            }
-
-            Set(SqlParameterFlags.CoercedValueIsDataFeed, false);
-
-            if (value is TextDataFeed)
-            {
-                if (Size > 0)
-                {
-                    char[] buffer = new char[Size];
-                    int nRead = ((TextDataFeed)value)._source.ReadBlock(buffer, 0, Size);
-                    CoercedValue = new string(buffer, 0, nRead);
-                }
-                else
-                {
-                    CoercedValue = ((TextDataFeed)value)._source.ReadToEnd();
-                }
-                return;
-            }
-
-            if (value is StreamDataFeed)
-            {
-                if (Size > 0)
-                {
-                    byte[] buffer = new byte[Size];
-                    int totalRead = 0;
-                    Stream sourceStream = ((StreamDataFeed)value)._source;
-                    while (totalRead < Size)
-                    {
-                        int nRead = sourceStream.Read(buffer, totalRead, Size - totalRead);
-                        if (nRead == 0)
-                        {
-                            break;
-                        }
-                        totalRead += nRead;
-                    }
-                    if (totalRead < Size)
-                    {
-                        Array.Resize(ref buffer, totalRead);
-                    }
-                    CoercedValue = buffer;
-                }
-                else
-                {
-                    MemoryStream ms = new MemoryStream();
-                    ((StreamDataFeed)value)._source.CopyTo(ms);
-                    CoercedValue = ms.ToArray();
-                }
-                return;
-            }
-
-            if (value is XmlDataFeed)
-            {
-                CoercedValue = MetaType.GetStringFromXml(((XmlDataFeed)value)._source);
-                return;
-            }
-
-            // We should have returned before reaching here
-            Debug.Fail("_coercedValueIsDataFeed was true, but the value was not a known DataFeed type");
-        }
-
-        private void CloneHelper(SqlParameter destination)
-        {
-            // NOTE: _parent is not cloned
-            destination._value = _value;
-            destination._direction = _direction;
-            destination._size = _size;
-            destination._offset = _offset;
-            destination._sourceColumn = _sourceColumn;
-            destination._sourceVersion = _sourceVersion;
-            destination._metaType = _metaType;
-            destination._collation = _collation;
-            destination._udtTypeName = _udtTypeName;
-            destination._typeName = _typeName;
-            destination._udtLoadError = _udtLoadError;
-            destination._parameterName = _parameterName;
-            destination._precision = _precision;
-            destination._scale = _scale;
-            destination._sqlBufferReturnValue = _sqlBufferReturnValue;
-            destination._internalMetaType = _internalMetaType;
-            destination.CoercedValue = CoercedValue; // copy cached value reference because of XmlReader problem
-            destination._valueAsINullable = _valueAsINullable;
-
-            SqlParameterFlags setFlags =
-                SqlParameterFlags.IsSqlParameterSqlType |
-                SqlParameterFlags.IsNull |
-                SqlParameterFlags.IsNullable |
-                SqlParameterFlags.CoercedValueIsDataFeed |
-                SqlParameterFlags.CoercedValueIsSqlType |
-                SqlParameterFlags.SourceColumnNullMapping;
-            destination._flags = (destination._flags & ~setFlags) | (_flags & setFlags);
-            destination._actualSize = _actualSize;
-
-            if (_xmlSchemaCollection != null)
-            {
-                destination._xmlSchemaCollection = new SqlMetaDataXmlSchemaCollection();
-                destination._xmlSchemaCollection.CopyFrom(_xmlSchemaCollection);
-            }
-        }
-
-        public override DataRowVersion SourceVersion
-        {
-            get
-            {
-                DataRowVersion sourceVersion = _sourceVersion;
-                return ((0 != sourceVersion) ? sourceVersion : DataRowVersion.Current);
-            }
-            set
-            {
-                switch (value)
-                {
-                    case DataRowVersion.Original:
-                    case DataRowVersion.Current:
-                    case DataRowVersion.Proposed:
-                    case DataRowVersion.Default:
-                        _sourceVersion = value;
-                        break;
-                    default:
-                        throw ADP.InvalidDataRowVersion(value);
-                }
-            }
-        }
-
-        internal byte GetActualPrecision()
-        {
-            return ShouldSerializePrecision() ? PrecisionInternal : ValuePrecision(CoercedValue);
-        }
-
-        internal byte GetActualScale()
-        {
-            if (ShouldSerializeScale())
-            {
-                return ScaleInternal;
-            }
-
-            // issue: how could a user specify 0 as the actual scale?
-            if (GetMetaTypeOnly().IsVarTime)
-            {
-                return TdsEnums.DEFAULT_VARTIME_SCALE;
-            }
-            return ValueScale(CoercedValue);
-        }
-
-        internal int GetParameterSize()
-        {
-            return ShouldSerializeSize() ? Size : ValueSize(CoercedValue);
-        }
-
-        private void GetActualFieldsAndProperties(out List<MSS.SmiExtendedMetaData> fields, out SmiMetaDataPropertyCollection props, out ParameterPeekAheadValue peekAhead)
-        {
-            fields = null;
-            props = null;
-            peekAhead = null;
-
-            object value = GetCoercedValue();
-            if (value is DataTable dt)
-            {
-                if (dt.Columns.Count <= 0)
-                {
-                    throw SQL.NotEnoughColumnsInStructuredType();
-                }
-                fields = new List<MSS.SmiExtendedMetaData>(dt.Columns.Count);
-                bool[] keyCols = new bool[dt.Columns.Count];
-                bool hasKey = false;
-
-                // set up primary key as unique key list
-                //  do this prior to general metadata loop to favor the primary key
-                if (null != dt.PrimaryKey && 0 < dt.PrimaryKey.Length)
-                {
-                    foreach (DataColumn col in dt.PrimaryKey)
-                    {
-                        keyCols[col.Ordinal] = true;
-                        hasKey = true;
-                    }
-                }
-
-                for (int i = 0; i < dt.Columns.Count; i++)
-                {
-                    fields.Add(MSS.MetaDataUtilsSmi.SmiMetaDataFromDataColumn(dt.Columns[i], dt));
-
-                    // DataColumn uniqueness is only for a single column, so don't add
-                    //  more than one.  (keyCols.Count first for assumed minimal perf benefit)
-                    if (!hasKey && dt.Columns[i].Unique)
-                    {
-                        keyCols[i] = true;
-                        hasKey = true;
-                    }
-                }
-
-                // Add unique key property, if any found.
-                if (hasKey)
-                {
-                    props = new SmiMetaDataPropertyCollection();
-                    props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
-                }
-            }
-            else if (value is SqlDataReader)
-            {
-                fields = new List<MSS.SmiExtendedMetaData>(((SqlDataReader)value).GetInternalSmiMetaData());
-                if (fields.Count <= 0)
-                {
-                    throw SQL.NotEnoughColumnsInStructuredType();
-                }
-
-                bool[] keyCols = new bool[fields.Count];
-                bool hasKey = false;
-                for (int i = 0; i < fields.Count; i++)
-                {
-                    MSS.SmiQueryMetaData qmd = fields[i] as MSS.SmiQueryMetaData;
-                    if (null != qmd && !qmd.IsKey.IsNull && qmd.IsKey.Value)
-                    {
-                        keyCols[i] = true;
-                        hasKey = true;
-                    }
-                }
-
-                // Add unique key property, if any found.
-                if (hasKey)
-                {
-                    props = new SmiMetaDataPropertyCollection();
-                    props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
-                }
-            }
-            else if (value is IEnumerable<SqlDataRecord>)
-            {
-                // must grab the first record of the enumerator to get the metadata
-                IEnumerator<MSS.SqlDataRecord> enumerator = ((IEnumerable<MSS.SqlDataRecord>)value).GetEnumerator();
-                MSS.SqlDataRecord firstRecord = null;
-                try
-                {
-                    // no need for fields if there's no rows or no columns -- we'll be sending a null instance anyway.
-                    if (enumerator.MoveNext())
-                    {
-                        firstRecord = enumerator.Current;
-                        int fieldCount = firstRecord.FieldCount;
-                        if (0 < fieldCount)
-                        {
-                            // It's valid!  Grab those fields.
-                            bool[] keyCols = new bool[fieldCount];
-                            bool[] defaultFields = new bool[fieldCount];
-                            bool[] sortOrdinalSpecified = new bool[fieldCount];
-                            int maxSortOrdinal = -1;  // largest sort ordinal seen, used to optimize locating holes in the list
-                            bool hasKey = false;
-                            bool hasDefault = false;
-                            int sortCount = 0;
-                            SmiOrderProperty.SmiColumnOrder[] sort = new SmiOrderProperty.SmiColumnOrder[fieldCount];
-                            fields = new List<MSS.SmiExtendedMetaData>(fieldCount);
-                            for (int i = 0; i < fieldCount; i++)
-                            {
-                                SqlMetaData colMeta = firstRecord.GetSqlMetaData(i);
-                                fields.Add(MSS.MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(colMeta));
-                                if (colMeta.IsUniqueKey)
-                                {
-                                    keyCols[i] = true;
-                                    hasKey = true;
-                                }
-
-                                if (colMeta.UseServerDefault)
-                                {
-                                    defaultFields[i] = true;
-                                    hasDefault = true;
-                                }
-
-                                sort[i].Order = colMeta.SortOrder;
-                                if (SortOrder.Unspecified != colMeta.SortOrder)
-                                {
-                                    // SqlMetaData takes care of checking for negative sort ordinals with specified sort order
-
-                                    // bail early if there's no way sort order could be monotonically increasing
-                                    if (fieldCount <= colMeta.SortOrdinal)
-                                    {
-                                        throw SQL.SortOrdinalGreaterThanFieldCount(i, colMeta.SortOrdinal);
-                                    }
-
-                                    // Check to make sure we haven't seen this ordinal before
-                                    if (sortOrdinalSpecified[colMeta.SortOrdinal])
-                                    {
-                                        throw SQL.DuplicateSortOrdinal(colMeta.SortOrdinal);
-                                    }
-
-                                    sort[i].SortOrdinal = colMeta.SortOrdinal;
-                                    sortOrdinalSpecified[colMeta.SortOrdinal] = true;
-                                    if (colMeta.SortOrdinal > maxSortOrdinal)
-                                    {
-                                        maxSortOrdinal = colMeta.SortOrdinal;
-                                    }
-                                    sortCount++;
-                                }
-                            }
-
-                            if (hasKey)
-                            {
-                                props = new SmiMetaDataPropertyCollection();
-                                props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
-                            }
-
-                            if (hasDefault)
-                            {
-                                // May have already created props list in unique key handling
-                                if (null == props)
-                                {
-                                    props = new SmiMetaDataPropertyCollection();
-                                }
-
-                                props[MSS.SmiPropertySelector.DefaultFields] = new MSS.SmiDefaultFieldsProperty(new List<bool>(defaultFields));
-                            }
-
-                            if (0 < sortCount)
-                            {
-                                // validate monotonically increasing sort order.
-                                //  Since we already checked for duplicates, we just need
-                                //  to watch for values outside of the sortCount range.
-                                if (maxSortOrdinal >= sortCount)
-                                {
-                                    // there is at least one hole, find the first one
-                                    int i;
-                                    for (i = 0; i < sortCount; i++)
-                                    {
-                                        if (!sortOrdinalSpecified[i])
-                                        {
-                                            break;
-                                        }
-                                    }
-                                    Debug.Assert(i < sortCount, "SqlParameter.GetActualFieldsAndProperties: SortOrdinal hole-finding algorithm failed!");
-                                    throw SQL.MissingSortOrdinal(i);
-                                }
-
-                                // May have already created props list
-                                if (null == props)
-                                {
-                                    props = new SmiMetaDataPropertyCollection();
-                                }
-
-                                props[MSS.SmiPropertySelector.SortOrder] = new MSS.SmiOrderProperty(
-                                        new List<SmiOrderProperty.SmiColumnOrder>(sort));
-                            }
-
-                            // pack it up so we don't have to rewind to send the first value
-                            peekAhead = new ParameterPeekAheadValue()
-                            {
-                                Enumerator = enumerator,
-                                FirstRecord = firstRecord
-                            };
-
-                            // now that it's all packaged, make sure we don't dispose it.
-                            enumerator = null;
-                        }
-                        else
-                        {
-                            throw SQL.NotEnoughColumnsInStructuredType();
-                        }
-                    }
-                    else
-                    {
-                        throw SQL.IEnumerableOfSqlDataRecordHasNoRows();
-                    }
-                }
-                finally
-                {
-                    if (enumerator != null)
-                    {
-                        enumerator.Dispose();
-                    }
-                }
-            }
-            else if (value is DbDataReader)
-            {
-                DataTable schema = ((DbDataReader)value).GetSchemaTable();
-                if (schema.Rows.Count <= 0)
-                {
-                    throw SQL.NotEnoughColumnsInStructuredType();
-                }
-
-                int fieldCount = schema.Rows.Count;
-                fields = new List<MSS.SmiExtendedMetaData>(fieldCount);
-                bool[] keyCols = new bool[fieldCount];
-                bool hasKey = false;
-                int ordinalForIsKey = schema.Columns[SchemaTableColumn.IsKey].Ordinal;
-                int ordinalForColumnOrdinal = schema.Columns[SchemaTableColumn.ColumnOrdinal].Ordinal;
-                // Extract column metadata
-                for (int rowOrdinal = 0; rowOrdinal < fieldCount; rowOrdinal++)
-                {
-                    DataRow row = schema.Rows[rowOrdinal];
-                    MSS.SmiExtendedMetaData candidateMd = MSS.MetaDataUtilsSmi.SmiMetaDataFromSchemaTableRow(row);
-
-                    // Determine destination ordinal.  Allow for ordinal not specified by assuming rowOrdinal *is* columnOrdinal
-                    // in that case, but don't worry about mix-and-match of the two techniques
-                    int columnOrdinal = rowOrdinal;
-                    if (!row.IsNull(ordinalForColumnOrdinal))
-                    {
-                        columnOrdinal = (int)row[ordinalForColumnOrdinal];
-                    }
-
-                    // After this point, things we are creating (keyCols, fields) should be accessed by columnOrdinal
-                    // while the source should just be accessed via "row".
-
-                    // Watch for out-of-range ordinals
-                    if (columnOrdinal >= fieldCount || columnOrdinal < 0)
-                    {
-                        throw SQL.InvalidSchemaTableOrdinals();
-                    }
-
-                    // extend empty space if out-of-order ordinal
-                    while (columnOrdinal > fields.Count)
-                    {
-                        fields.Add(null);
-                    }
-
-                    // Now add the candidate to the list
-                    if (fields.Count == columnOrdinal)
-                    {
-                        fields.Add(candidateMd);
-                    }
-                    else
-                    {
-                        // Disallow two columns using the same ordinal (even if due to mixing null and non-null columnOrdinals)
-                        if (fields[columnOrdinal] != null)
-                        {
-                            throw SQL.InvalidSchemaTableOrdinals();
-                        }
-
-                        // Don't use insert, since it shifts all later columns down a notch
-                        fields[columnOrdinal] = candidateMd;
-                    }
-
-                    // Propagate key information
-                    if (!row.IsNull(ordinalForIsKey) && (bool)row[ordinalForIsKey])
-                    {
-                        keyCols[columnOrdinal] = true;
-                        hasKey = true;
-                    }
-                }
-
-#if DEBUG
-                // Check for holes
-                //  Above loop logic prevents holes since:
-                //      1) loop processes fieldcount # of columns
-                //      2) no ordinals outside continuous range from 0 to fieldcount - 1 are allowed
-                //      3) no duplicate ordinals are allowed
-                // But assert no holes to be sure.
-                foreach (MSS.SmiExtendedMetaData md in fields)
-                {
-                    Debug.Assert(null != md, "Shouldn't be able to have holes, since original loop algorithm prevents such.");
-                }
-#endif
-
-                // Add unique key property, if any defined.
-                if (hasKey)
-                {
-                    props = new MSS.SmiMetaDataPropertyCollection();
-                    props[MSS.SmiPropertySelector.UniqueKey] = new SmiUniqueKeyProperty(new List<bool>(keyCols));
-                }
-            }
-        }
-
-        internal object GetCoercedValue()
-        {
-            // NOTE: User can change the Udt at any time
-            if ((null == _coercedValue) || (_internalMetaType.SqlDbType == Data.SqlDbType.Udt))
-            {  // will also be set during parameter Validation
-                bool isDataFeed = Value is DataFeed;
-                bool isSqlParameterSqlType = _flags.HasFlag(SqlParameterFlags.IsSqlParameterSqlType);
-                bool isNull = IsNull;
-                if ((isNull) || (isDataFeed))
-                {
-                    // No coercion is done for DataFeeds and Nulls
-                    _coercedValue = Value;
-                    Set(SqlParameterFlags.CoercedValueIsSqlType, (_coercedValue is null) ? false : isSqlParameterSqlType); // set to null for output parameters that keeps _isSqlParameterSqlType
-                    Set(SqlParameterFlags.CoercedValueIsDataFeed, isDataFeed);
-                    _actualSize = isNull ? 0 : -1;
-                }
-                else
-                {
-                    bool typeChanged;
-                    bool coercedValueIsDataFeed;
-                    _coercedValue = CoerceValue(Value, _internalMetaType, out coercedValueIsDataFeed, out typeChanged);
-                    Set(SqlParameterFlags.CoercedValueIsDataFeed, coercedValueIsDataFeed);
-                    Set(SqlParameterFlags.CoercedValueIsSqlType, ((isSqlParameterSqlType) && (!typeChanged)));  // Type changed always results in a CLR type
-                    _actualSize = -1;
-                }
-            }
-            AssertCachedPropertiesAreValid();
-            return _coercedValue;
-        }
-
-        internal bool CoercedValueIsSqlType
-        {
-            get
-            {
-                if (null == _coercedValue)
-                {
-                    GetCoercedValue();
-                }
-                AssertCachedPropertiesAreValid();
-                return _flags.HasFlag(SqlParameterFlags.CoercedValueIsSqlType);
-            }
-        }
-
-        internal bool CoercedValueIsDataFeed
-        {
-            get
-            {
-                if (null == _coercedValue)
-                {
-                    GetCoercedValue();
-                }
-                AssertCachedPropertiesAreValid();
-                return _flags.HasFlag(SqlParameterFlags.CoercedValueIsDataFeed);
-            }
-        }
-
-        [Conditional("DEBUG")]
-        internal void AssertCachedPropertiesAreValid()
-        {
-            AssertPropertiesAreValid(_coercedValue, _flags.HasFlag(SqlParameterFlags.CoercedValueIsSqlType), _flags.HasFlag(SqlParameterFlags.CoercedValueIsDataFeed), IsNull);
-        }
-
-        [Conditional("DEBUG")]
-        internal void AssertPropertiesAreValid(object value, bool? isSqlType = null, bool? isDataFeed = null, bool? isNull = null)
-        {
-            Debug.Assert(!isSqlType.HasValue || (isSqlType.Value == (value is INullable)), "isSqlType is incorrect");
-            Debug.Assert(!isDataFeed.HasValue || (isDataFeed.Value == (value is DataFeed)), "isDataFeed is incorrect");
-            Debug.Assert(!isNull.HasValue || (isNull.Value == ADP.IsNull(value)), "isNull is incorrect");
-        }
-
-        private SqlDbType GetMetaSqlDbTypeOnly()
-        {
-            MetaType metaType = _metaType;
-            if (null == metaType)
-            { // infer the type from the value
-                metaType = MetaType.GetDefaultMetaType();
-            }
-            return metaType.SqlDbType;
-        }
-
-        // This may not be a good thing to do in case someone overloads the parameter type but I
-        // don't want to go from SqlDbType -> metaType -> TDSType
-        private MetaType GetMetaTypeOnly()
-        {
-            if (null != _metaType)
-            {
-                return _metaType;
-            }
-            if (null != _value && DBNull.Value != _value)
-            {
-                // We have a value set by the user then just use that value
-                // char and char[] are not directly supported so we convert those values to string
-                Type valueType = _value.GetType();
-                if (typeof(char) == valueType)
-                {
-                    _value = _value.ToString();
-                    valueType = typeof(string);
-                }
-                else if (typeof(char[]) == valueType)
-                {
-                    _value = new string((char[])_value);
-                    valueType = typeof(string);
-                }
-                return MetaType.GetMetaTypeFromType(valueType);
-            }
-            else if (null != _sqlBufferReturnValue)
-            {  // value came back from the server
-                Type valueType = _sqlBufferReturnValue.GetTypeFromStorageType(_flags.HasFlag(SqlParameterFlags.IsSqlParameterSqlType));
-                if (null != valueType)
-                {
-                    return MetaType.GetMetaTypeFromType(valueType);
-                }
-            }
-            return MetaType.GetDefaultMetaType();
-        }
-
-        internal void Prepare(SqlCommand cmd)
-        {
-            if (null == _metaType)
-            {
-                throw ADP.PrepareParameterType(cmd);
-            }
-            else if (!ShouldSerializeSize() && !_metaType.IsFixed)
-            {
-                throw ADP.PrepareParameterSize(cmd);
-            }
-            else if ((!ShouldSerializePrecision() && !ShouldSerializeScale()) && (_metaType.SqlDbType == SqlDbType.Decimal))
-            {
-                throw ADP.PrepareParameterScale(cmd, SqlDbType.ToString());
-            }
-        }
-
-        private void PropertyChanging()
-        {
-            _internalMetaType = null;
-        }
-
-        private void PropertyTypeChanging()
-        {
-            PropertyChanging();
-            CoercedValue = null;
-        }
-
-        internal void SetSqlBuffer(SqlBuffer buff)
-        {
-            _sqlBufferReturnValue = buff;
-            _value = null;
-            _coercedValue = null;
-            Set(SqlParameterFlags.IsNull, _sqlBufferReturnValue.IsNull);
-            Set(SqlParameterFlags.CoercedValueIsDataFeed, false);
-            Set(SqlParameterFlags.CoercedValueIsSqlType, false);
-            _udtLoadError = null;
-            _actualSize = -1;
-        }
-
-        internal void SetUdtLoadError(Exception e)
-        {
-            _udtLoadError = e;
-        }
-
-        private void Set(SqlParameterFlags flag, bool value)
-        {
-            if (value)
-            {
-                _flags |= flag;
-            }
-            else
-            {
-                _flags &= ~flag;
-            }
-        }
-
-        internal void Validate(int index, bool isCommandProc)
-        {
-            MetaType metaType = GetMetaTypeOnly();
-            _internalMetaType = metaType;
-
-            // SqlParameter does a Size Validation check and would fail if the size is 0.
-            // This condition filters all scenarios where we view a valid size 0.
-            if (ADP.IsDirection(this, ParameterDirection.Output) &&
-                !ADP.IsDirection(this, ParameterDirection.ReturnValue) &&
-                (!metaType.IsFixed) &&
-                !ShouldSerializeSize() &&
-                ((null == _value) || Convert.IsDBNull(_value)) &&
-                (SqlDbType != SqlDbType.Timestamp) &&
-                (SqlDbType != SqlDbType.Udt) &&
-                (SqlDbType != SqlDbType.Xml) &&
-                !metaType.IsVarTime)
-            {
-
-                throw ADP.UninitializedParameterSize(index, metaType.ClassType);
-            }
-
-            if (metaType.SqlDbType != SqlDbType.Udt && Direction != ParameterDirection.Output)
-            {
-                GetCoercedValue();
-            }
-
-            //check if the UdtTypeName is specified for Udt params
-            if (metaType.SqlDbType == SqlDbType.Udt)
-            {
-                if (string.IsNullOrEmpty(UdtTypeName))
-                    throw SQL.MustSetUdtTypeNameForUdtParams();
-            }
-            else if (!string.IsNullOrEmpty(UdtTypeName))
-            {
-                throw SQL.UnexpectedUdtTypeNameForNonUdtParams();
-            }
-
-            // Validate structured-type-specific details.
-            if (metaType.SqlDbType == SqlDbType.Structured)
-            {
-                if (!isCommandProc && string.IsNullOrEmpty(TypeName))
-                    throw SQL.MustSetTypeNameForParam(metaType.TypeName, this.ParameterName);
-
-                if (ParameterDirection.Input != this.Direction)
-                {
-                    throw SQL.UnsupportedTVPOutputParameter(this.Direction, this.ParameterName);
-                }
-
-                if (DBNull.Value == GetCoercedValue())
-                {
-                    throw SQL.DBNullNotSupportedForTVPValues(this.ParameterName);
-                }
-            }
-            else if (!string.IsNullOrEmpty(TypeName))
-            {
-                throw SQL.UnexpectedTypeNameForNonStructParams(this.ParameterName);
-            }
-        }
-
-        // func will change type to that with a 4 byte length if the type has a two
-        // byte length and a parameter length > than that expressible in 2 bytes
-        internal MetaType ValidateTypeLengths()
-        {
-            MetaType mt = InternalMetaType;
-            // Since the server will automatically reject any
-            // char, varchar, binary, varbinary, nchar, or nvarchar parameter that has a
-            // byte sizeInCharacters > 8000 bytes, we promote the parameter to image, text, or ntext.  This
-            // allows the user to specify a parameter type using a COM+ datatype and be able to
-            // use that parameter against a BLOB column.
-            if ((SqlDbType.Udt != mt.SqlDbType) && (false == mt.IsFixed) && (false == mt.IsLong))
-            { // if type has 2 byte length
-                long actualSizeInBytes = this.GetActualSize();
-                long sizeInCharacters = this.Size;
-
-                long maxSizeInBytes = 0;
-                if (mt.IsNCharType)
-                {
-                    maxSizeInBytes = ((sizeInCharacters * sizeof(char)) > actualSizeInBytes) ? sizeInCharacters * sizeof(char) : actualSizeInBytes;
-                }
-                else
-                {
-                    // Notes:
-                    // Elevation from (n)(var)char (4001+) to (n)text succeeds without failure only with Yukon and greater.
-                    // it fails in sql server 2000
-                    maxSizeInBytes = (sizeInCharacters > actualSizeInBytes) ? sizeInCharacters : actualSizeInBytes;
-                }
-
-                if ((maxSizeInBytes > TdsEnums.TYPE_SIZE_LIMIT) || (_flags.HasFlag(SqlParameterFlags.CoercedValueIsDataFeed)) ||
-                    (sizeInCharacters == -1) || (actualSizeInBytes == -1))
-                { // is size > size able to be described by 2 bytes
-                    // Convert the parameter to its max type
-                    mt = MetaType.GetMaxMetaTypeFromMetaType(mt);
-                    _metaType = mt;
-                    InternalMetaType = mt;
-                    if (!mt.IsPlp)
-                    {
-                        if (mt.SqlDbType == SqlDbType.Xml)
-                        {
-                            throw ADP.InvalidMetaDataValue();     //Xml should always have IsPartialLength = true
-                        }
-                        if (mt.SqlDbType == SqlDbType.NVarChar
-                         || mt.SqlDbType == SqlDbType.VarChar
-                         || mt.SqlDbType == SqlDbType.VarBinary)
-                        {
-                            Size = (int)(SmiMetaData.UnlimitedMaxLengthIndicator);
-                        }
-                    }
-                }
-            }
-            return mt;
-        }
-
-        private byte ValuePrecision(object value)
-        {
-            if (value is SqlDecimal)
-            {
-                if (((SqlDecimal)value).IsNull)
-                    return 0;
-
-                return ((SqlDecimal)value).Precision;
-            }
-            return ValuePrecisionCore(value);
-        }
-
-        private byte ValueScale(object value)
-        {
-            if (value is SqlDecimal)
-            {
-                if (((SqlDecimal)value).IsNull)
-                    return 0;
-
-                return ((SqlDecimal)value).Scale;
-            }
-            return ValueScaleCore(value);
-        }
-
-        private static int StringSize(object value, bool isSqlType)
-        {
-            if (isSqlType)
-            {
-                Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
-                if (value is SqlString)
-                {
-                    return ((SqlString)value).Value.Length;
-                }
-                if (value is SqlChars)
-                {
-                    return ((SqlChars)value).Value.Length;
-                }
-            }
-            else
-            {
-                string svalue = (value as string);
-                if (null != svalue)
-                {
-                    return svalue.Length;
-                }
-                char[] cvalue = (value as char[]);
-                if (null != cvalue)
-                {
-                    return cvalue.Length;
-                }
-                if (value is char)
-                {
-                    return 1;
-                }
-            }
-
-            // Didn't match, unknown size
-            return 0;
-        }
-
-        private static int BinarySize(object value, bool isSqlType)
-        {
-            if (isSqlType)
-            {
-                Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
-                if (value is SqlBinary)
-                {
-                    return ((SqlBinary)value).Length;
-                }
-                if (value is SqlBytes)
-                {
-                    return ((SqlBytes)value).Value.Length;
-                }
-            }
-            else
-            {
-                byte[] bvalue = (value as byte[]);
-                if (null != bvalue)
-                {
-                    return bvalue.Length;
-                }
-                if (value is byte)
-                {
-                    return 1;
-                }
-            }
-
-            // Didn't match, unknown size
-            return 0;
-        }
-
-        private int ValueSize(object value)
-        {
-            if (value is SqlString)
-            {
-                if (((SqlString)value).IsNull)
-                    return 0;
-
-                return ((SqlString)value).Value.Length;
-            }
-            if (value is SqlChars)
-            {
-                if (((SqlChars)value).IsNull)
-                    return 0;
-
-                return ((SqlChars)value).Value.Length;
-            }
-
-            if (value is SqlBinary)
-            {
-                if (((SqlBinary)value).IsNull)
-                    return 0;
-
-                return ((SqlBinary)value).Length;
-            }
-            if (value is SqlBytes)
-            {
-                if (((SqlBytes)value).IsNull)
-                    return 0;
-
-                return (int)(((SqlBytes)value).Length);
-            }
-            if (value is DataFeed)
-            {
-                // Unknown length
-                return 0;
-            }
-            return ValueSizeCore(value);
-        }
-
-        // parse an string of the form db.schema.name where any of the three components
-        // might have "[" "]" and dots within it.
-        // returns:
-        //   [0] dbname (or null)
-        //   [1] schema (or null)
-        //   [2] name
-        // NOTE: if perf/space implications of Regex is not a problem, we can get rid
-        // of this and use a simple regex to do the parsing
-        internal static string[] ParseTypeName(string typeName, bool isUdtTypeName)
-        {
-            Debug.Assert(null != typeName, "null typename passed to ParseTypeName");
-
-            try
-            {
-                string errorMsg = isUdtTypeName ? SR.SQL_UDTTypeName : SR.SQL_TypeName;
-                return MultipartIdentifier.ParseMultipartIdentifier(typeName, "[\"", "]\"", '.', 3, true, errorMsg, true);
-            }
-            catch (ArgumentException)
-            {
-                if (isUdtTypeName)
-                {
-                    throw SQL.InvalidUdt3PartNameFormat();
-                }
-                else
-                {
-                    throw SQL.InvalidParameterTypeNameFormat();
-                }
-            }
-        }
-
-        private void EnsureXmlSchemaCollectionExists()
-        {
-            if (_xmlSchemaCollection is null)
-            {
-                _xmlSchemaCollection = new SqlMetaDataXmlSchemaCollection();
-            }
-        }
-
-        internal sealed class SqlParameterConverter : ExpandableObjectConverter
-        {
-
-            // converter classes should have public ctor
-            public SqlParameterConverter()
-            {
-            }
-
-            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
-            {
-                if (typeof(InstanceDescriptor) == destinationType)
-                {
-                    return true;
-                }
-                return base.CanConvertTo(context, destinationType);
-            }
-
-            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
-            {
-                if (destinationType == null)
-                {
-                    throw ADP.ArgumentNull(nameof(destinationType));
-                }
-                if ((typeof(InstanceDescriptor) == destinationType) && (value is SqlParameter))
-                {
-                    return ConvertToInstanceDescriptor(value as SqlParameter);
-                }
-                return base.ConvertTo(context, culture, value, destinationType);
-            }
-
-            private InstanceDescriptor ConvertToInstanceDescriptor(SqlParameter p)
-            {
-                int flags = 0; // if part of the collection - the parametername can't be empty
-
-                if (p.ShouldSerializeSqlDbType())
-                {
-                    flags |= 1;
-                }
-                if (p.ShouldSerializeSize())
-                {
-                    flags |= 2;
-                }
-                if (!string.IsNullOrEmpty(p.SourceColumn))
-                {
-                    flags |= 4;
-                }
-                if (null != p.Value)
-                {
-                    flags |= 8;
-                }
-                if ((ParameterDirection.Input != p.Direction) || p.IsNullable
-                    || p.ShouldSerializePrecision() || p.ShouldSerializeScale()
-                    || (DataRowVersion.Current != p.SourceVersion)
-                    )
-                {
-                    flags |= 16; // v1.0 everything
-                }
-
-                if (p.SourceColumnNullMapping || !string.IsNullOrEmpty(p.XmlSchemaCollectionDatabase) ||
-                    !string.IsNullOrEmpty(p.XmlSchemaCollectionOwningSchema) || !string.IsNullOrEmpty(p.XmlSchemaCollectionName))
-                {
-                    flags |= 32; // v2.0 everything
-                }
-
-                Type[] ctorParams;
-                object[] ctorValues;
-                switch (flags)
-                {
-                    case 0: // ParameterName
-                    case 1: // SqlDbType
-                        ctorParams = new Type[] { typeof(string), typeof(SqlDbType) };
-                        ctorValues = new object[] { p.ParameterName, p.SqlDbType };
-                        break;
-                    case 2: // Size
-                    case 3: // Size, SqlDbType
-                        ctorParams = new Type[] { typeof(string), typeof(SqlDbType), typeof(int) };
-                        ctorValues = new object[] { p.ParameterName, p.SqlDbType, p.Size };
-                        break;
-                    case 4: // SourceColumn
-                    case 5: // SourceColumn, SqlDbType
-                    case 6: // SourceColumn, Size
-                    case 7: // SourceColumn, Size, SqlDbType
-                        ctorParams = new Type[] { typeof(string), typeof(SqlDbType), typeof(int), typeof(string) };
-                        ctorValues = new object[] { p.ParameterName, p.SqlDbType, p.Size, p.SourceColumn };
-                        break;
-                    case 8: // Value
-                        ctorParams = new Type[] { typeof(string), typeof(object) };
-                        ctorValues = new object[] { p.ParameterName, p.Value };
-                        break;
-                    default:
-                        if (0 == (32 & flags))
-                        { // v1.0 everything
-                            ctorParams = new Type[] {
-                                                    typeof(string), typeof(SqlDbType), typeof(int), typeof(ParameterDirection),
-                                                    typeof(bool), typeof(byte), typeof(byte),
-                                                    typeof(string), typeof(DataRowVersion),
-                                                    typeof(object) };
-                            ctorValues = new object[] {
-                                                      p.ParameterName, p.SqlDbType,  p.Size, p.Direction,
-                                                      p.IsNullable, p.PrecisionInternal, p.ScaleInternal,
-                                                      p.SourceColumn, p.SourceVersion,
-                                                      p.Value };
-                        }
-                        else
-                        { // v2.0 everything - round trip all browsable properties + precision/scale
-                            ctorParams = new Type[] {
-                                                    typeof(string), typeof(SqlDbType), typeof(int), typeof(ParameterDirection),
-                                                    typeof(byte), typeof(byte),
-                                                    typeof(string), typeof(DataRowVersion), typeof(bool),
-                                                    typeof(object),
-                                                    typeof(string), typeof(string),
-                                                    typeof(string) };
-                            ctorValues = new object[] {
-                                                      p.ParameterName, p.SqlDbType,  p.Size, p.Direction,
-                                                      p.PrecisionInternal, p.ScaleInternal,
-                                                      p.SourceColumn, p.SourceVersion, p.SourceColumnNullMapping,
-                                                      p.Value,
-                                                      p.XmlSchemaCollectionDatabase, p.XmlSchemaCollectionOwningSchema,
-                                                      p.XmlSchemaCollectionName};
-                        }
-                        break;
-                }
-                ConstructorInfo ctor = typeof(SqlParameter).GetConstructor(ctorParams);
-                return new InstanceDescriptor(ctor, ctorValues);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterCollection.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterCollection.cs
deleted file mode 100644 (file)
index d9cf0bb..0000000
+++ /dev/null
@@ -1,125 +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.Data.Common;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlParameterCollection : DbParameterCollection
-    {
-        private bool _isDirty;
-        private static readonly Type s_itemType = typeof(SqlParameter);
-
-        internal SqlParameterCollection() : base()
-        {
-        }
-
-        internal bool IsDirty
-        {
-            get
-            {
-                return _isDirty;
-            }
-            set
-            {
-                _isDirty = value;
-            }
-        }
-        public override bool IsFixedSize => ((System.Collections.IList)InnerList).IsFixedSize;
-        public override bool IsReadOnly => ((System.Collections.IList)InnerList).IsReadOnly;
-        public new SqlParameter this[int index]
-        {
-            get
-            {
-                return (SqlParameter)GetParameter(index);
-            }
-            set
-            {
-                SetParameter(index, value);
-            }
-        }
-
-        public new SqlParameter this[string parameterName]
-        {
-            get
-            {
-                return (SqlParameter)GetParameter(parameterName);
-            }
-            set
-            {
-                SetParameter(parameterName, value);
-            }
-        }
-
-        public SqlParameter Add(SqlParameter value)
-        {
-            Add((object)value);
-            return value;
-        }
-
-        public SqlParameter AddWithValue(string parameterName, object value)
-        { // 79027
-            return Add(new SqlParameter(parameterName, value));
-        }
-
-        public SqlParameter Add(string parameterName, SqlDbType sqlDbType)
-        {
-            return Add(new SqlParameter(parameterName, sqlDbType));
-        }
-
-        public SqlParameter Add(string parameterName, SqlDbType sqlDbType, int size)
-        {
-            return Add(new SqlParameter(parameterName, sqlDbType, size));
-        }
-
-        public SqlParameter Add(string parameterName, SqlDbType sqlDbType, int size, string sourceColumn)
-        {
-            return Add(new SqlParameter(parameterName, sqlDbType, size, sourceColumn));
-        }
-
-        public void AddRange(SqlParameter[] values)
-        {
-            AddRange((Array)values);
-        }
-
-        public override bool Contains(string value)
-        { // WebData 97349
-            return (-1 != IndexOf(value));
-        }
-
-        public bool Contains(SqlParameter value)
-        {
-            return (-1 != IndexOf(value));
-        }
-
-        public void CopyTo(SqlParameter[] array, int index)
-        {
-            CopyTo((Array)array, index);
-        }
-
-        public int IndexOf(SqlParameter value)
-        {
-            return IndexOf((object)value);
-        }
-
-        public void Insert(int index, SqlParameter value)
-        {
-            Insert(index, (object)value);
-        }
-
-        private void OnChange()
-        {
-            IsDirty = true;
-        }
-
-        public void Remove(SqlParameter value)
-        {
-            Remove((object)value);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterCollectionHelper.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterCollectionHelper.cs
deleted file mode 100644 (file)
index a77af35..0000000
+++ /dev/null
@@ -1,321 +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.
-
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-// In the .NET Framework version of the framework, this file is generated from ProviderBase\DbParameterCollectionHelper.cs
-//#line 1 "e:\\fxdata\\src\\ndp\\fx\\src\\data\\system\\data\\providerbase\\dbparametercollectionhelper.cs"
-
-using System.Collections.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Globalization;
-using System.Reflection;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlParameterCollection : DbParameterCollection
-    {
-        private List<SqlParameter> _items;
-
-        public override int Count
-        {
-            get
-            {
-                return ((null != _items) ? _items.Count : 0);
-            }
-        }
-
-        private List<SqlParameter> InnerList
-        {
-            get
-            {
-                List<SqlParameter> items = _items;
-
-                if (null == items)
-                {
-                    items = new List<SqlParameter>();
-                    _items = items;
-                }
-                return items;
-            }
-        }
-
-
-        public override object SyncRoot
-        {
-            get
-            {
-                return ((System.Collections.ICollection)InnerList).SyncRoot;
-            }
-        }
-
-        public override int Add(object value)
-        {
-            OnChange();
-            ValidateType(value);
-            Validate(-1, value);
-            InnerList.Add((SqlParameter)value);
-            return Count - 1;
-        }
-
-        public override void AddRange(System.Array values)
-        {
-            OnChange();
-            if (null == values)
-            {
-                throw ADP.ArgumentNull(nameof(values));
-            }
-            foreach (object value in values)
-            {
-                ValidateType(value);
-            }
-            foreach (SqlParameter value in values)
-            {
-                Validate(-1, value);
-                InnerList.Add((SqlParameter)value);
-            }
-        }
-
-        private int CheckName(string parameterName)
-        {
-            int index = IndexOf(parameterName);
-            if (index < 0)
-            {
-                throw ADP.ParametersSourceIndex(parameterName, this, s_itemType);
-            }
-            return index;
-        }
-
-        public override void Clear()
-        {
-            OnChange();
-            List<SqlParameter> items = InnerList;
-
-            if (null != items)
-            {
-                foreach (SqlParameter item in items)
-                {
-                    item.ResetParent();
-                }
-                items.Clear();
-            }
-        }
-
-        public override bool Contains(object value)
-        {
-            return (-1 != IndexOf(value));
-        }
-
-        public override void CopyTo(Array array, int index)
-        {
-            ((System.Collections.ICollection)InnerList).CopyTo(array, index);
-        }
-
-        public override System.Collections.IEnumerator GetEnumerator()
-        {
-            return ((System.Collections.ICollection)InnerList).GetEnumerator();
-        }
-
-        protected override DbParameter GetParameter(int index)
-        {
-            RangeCheck(index);
-            return InnerList[index];
-        }
-
-        protected override DbParameter GetParameter(string parameterName)
-        {
-            int index = IndexOf(parameterName);
-            if (index < 0)
-            {
-                throw ADP.ParametersSourceIndex(parameterName, this, s_itemType);
-            }
-            return InnerList[index];
-        }
-
-        private static int IndexOf(System.Collections.IEnumerable items, string parameterName)
-        {
-            if (null != items)
-            {
-                int i = 0;
-
-                foreach (SqlParameter parameter in items)
-                {
-                    if (parameterName == parameter.ParameterName)
-                    {
-                        return i;
-                    }
-                    ++i;
-                }
-                i = 0;
-
-                foreach (SqlParameter parameter in items)
-                {
-                    if (0 == ADP.DstCompare(parameterName, parameter.ParameterName))
-                    {
-                        return i;
-                    }
-                    ++i;
-                }
-            }
-            return -1;
-        }
-
-        public override int IndexOf(string parameterName)
-        {
-            return IndexOf(InnerList, parameterName);
-        }
-
-        public override int IndexOf(object value)
-        {
-            if (null != value)
-            {
-                ValidateType(value);
-
-                List<SqlParameter> items = InnerList;
-
-                if (null != items)
-                {
-                    int count = items.Count;
-
-                    for (int i = 0; i < count; i++)
-                    {
-                        if (value == items[i])
-                        {
-                            return i;
-                        }
-                    }
-                }
-            }
-            return -1;
-        }
-
-        public override void Insert(int index, object value)
-        {
-            OnChange();
-            ValidateType(value);
-            Validate(-1, (SqlParameter)value);
-            InnerList.Insert(index, (SqlParameter)value);
-        }
-
-        private void RangeCheck(int index)
-        {
-            if ((index < 0) || (Count <= index))
-            {
-                throw ADP.ParametersMappingIndex(index, this);
-            }
-        }
-
-        public override void Remove(object value)
-        {
-            OnChange();
-            ValidateType(value);
-            int index = IndexOf(value);
-            if (-1 != index)
-            {
-                RemoveIndex(index);
-            }
-            else if (this != ((SqlParameter)value).CompareExchangeParent(null, this))
-            {
-                throw ADP.CollectionRemoveInvalidObject(s_itemType, this);
-            }
-        }
-
-        public override void RemoveAt(int index)
-        {
-            OnChange();
-            RangeCheck(index);
-            RemoveIndex(index);
-        }
-
-        public override void RemoveAt(string parameterName)
-        {
-            OnChange();
-            int index = CheckName(parameterName);
-            RemoveIndex(index);
-        }
-
-        private void RemoveIndex(int index)
-        {
-            List<SqlParameter> items = InnerList;
-            Debug.Assert((null != items) && (0 <= index) && (index < Count), "RemoveIndex, invalid");
-            SqlParameter item = items[index];
-            items.RemoveAt(index);
-            item.ResetParent();
-        }
-
-        private void Replace(int index, object newValue)
-        {
-            List<SqlParameter> items = InnerList;
-            Debug.Assert((null != items) && (0 <= index) && (index < Count), "Replace Index invalid");
-            ValidateType(newValue);
-            Validate(index, newValue);
-            SqlParameter item = items[index];
-            items[index] = (SqlParameter)newValue;
-            item.ResetParent();
-        }
-
-        protected override void SetParameter(int index, DbParameter value)
-        {
-            OnChange();
-            RangeCheck(index);
-            Replace(index, value);
-        }
-
-        protected override void SetParameter(string parameterName, DbParameter value)
-        {
-            OnChange();
-            int index = IndexOf(parameterName);
-            if (index < 0)
-            {
-                throw ADP.ParametersSourceIndex(parameterName, this, s_itemType);
-            }
-            Replace(index, value);
-        }
-
-        private void Validate(int index, object value)
-        {
-            if (null == value)
-            {
-                throw ADP.ParameterNull(nameof(value), this, s_itemType);
-            }
-
-            object parent = ((SqlParameter)value).CompareExchangeParent(this, null);
-            if (null != parent)
-            {
-                if (this != parent)
-                {
-                    throw ADP.ParametersIsNotParent(s_itemType, this);
-                }
-                if (index != IndexOf(value))
-                {
-                    throw ADP.ParametersIsParent(s_itemType, this);
-                }
-            }
-
-            string name = ((SqlParameter)value).ParameterName;
-            if (0 == name.Length)
-            {
-                index = 1;
-                do
-                {
-                    name = ADP.Parameter + index.ToString(CultureInfo.CurrentCulture);
-                    index++;
-                } while (-1 != IndexOf(name));
-                ((SqlParameter)value).ParameterName = name;
-            }
-        }
-
-        private void ValidateType(object value)
-        {
-            if (null == value)
-            {
-                throw ADP.ParameterNull(nameof(value), this, s_itemType);
-            }
-            else if (!s_itemType.IsInstanceOfType(value))
-            {
-                throw ADP.InvalidParameterType(this, s_itemType, value);
-            }
-        }
-    };
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterHelper.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameterHelper.cs
deleted file mode 100644 (file)
index 3491b16..0000000
+++ /dev/null
@@ -1,203 +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.
-
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-// In the .NET Framework version of the framework, this file is generated from ProviderBase\DbParameterHelper.cs
-//#line 1 "e:\\fxdata\\src\\ndp\\fx\\src\\data\\system\\data\\providerbase\\dbparameterhelper.cs"
-
-using System.Data.Common;
-
-namespace System.Data.SqlClient
-{
-    public sealed partial class SqlParameter : DbParameter
-    {
-        private object _value;
-        private object _parent;
-        private ParameterDirection _direction;
-        private int _size;
-        private int _offset;
-        private string _sourceColumn;
-        private object _coercedValue;
-
-        private object CoercedValue
-        {
-            get => _coercedValue;
-            set => _coercedValue = value;
-        }
-
-        public override ParameterDirection Direction
-        {
-            get
-            {
-                ParameterDirection direction = _direction;
-                return ((0 != direction) ? direction : ParameterDirection.Input);
-            }
-            set
-            {
-                if (_direction != value)
-                {
-                    switch (value)
-                    {
-                        case ParameterDirection.Input:
-                        case ParameterDirection.Output:
-                        case ParameterDirection.InputOutput:
-                        case ParameterDirection.ReturnValue:
-                            PropertyChanging();
-                            _direction = value;
-                            break;
-                        default:
-                            throw ADP.InvalidParameterDirection(value);
-                    }
-                }
-            }
-        }
-
-        public override bool IsNullable
-        {
-            get => _flags.HasFlag(SqlParameterFlags.IsNullable);
-            set => Set(SqlParameterFlags.IsNullable, value);
-        }
-
-        public int Offset
-        {
-            get
-            {
-                return _offset;
-            }
-            set
-            {
-                if (value < 0)
-                {
-                    throw ADP.InvalidOffsetValue(value);
-                }
-                _offset = value;
-            }
-        }
-
-        public override int Size
-        {
-            get
-            {
-                int size = _size;
-                if (0 == size)
-                {
-                    size = ValueSize(Value);
-                }
-                return size;
-            }
-            set
-            {
-                if (_size != value)
-                {
-                    if (value < -1)
-                    {
-                        throw ADP.InvalidSizeValue(value);
-                    }
-                    PropertyChanging();
-                    _size = value;
-                }
-            }
-        }
-
-        private bool ShouldSerializeSize()
-        {
-            return (0 != _size);
-        }
-
-        public override string SourceColumn
-        {
-            get => (_sourceColumn ?? string.Empty);
-            set => _sourceColumn = value;
-        }
-
-        public override bool SourceColumnNullMapping
-        {
-            get => _flags.HasFlag(SqlParameterFlags.SourceColumnNullMapping);
-            set => Set(SqlParameterFlags.SourceColumnNullMapping, value);
-        }
-
-        internal object CompareExchangeParent(object value, object comparand)
-        {
-            object parent = _parent;
-            if (comparand == parent)
-            {
-                _parent = value;
-            }
-            return parent;
-        }
-
-        internal void ResetParent()
-        {
-            _parent = null;
-        }
-
-        public override string ToString()
-        {
-            return ParameterName;
-        }
-
-        private byte ValuePrecisionCore(object value)
-        {
-            if (value is decimal)
-            {
-                return ((System.Data.SqlTypes.SqlDecimal)(decimal)value).Precision;
-            }
-            return 0;
-        }
-
-        private byte ValueScaleCore(object value)
-        {
-            if (value is decimal)
-            {
-                return (byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10);
-            }
-            return 0;
-        }
-
-        private int ValueSizeCore(object value)
-        {
-            if (!ADP.IsNull(value))
-            {
-                string svalue = (value as string);
-                if (null != svalue)
-                {
-                    return svalue.Length;
-                }
-                byte[] bvalue = (value as byte[]);
-                if (null != bvalue)
-                {
-                    return bvalue.Length;
-                }
-                char[] cvalue = (value as char[]);
-                if (null != cvalue)
-                {
-                    return cvalue.Length;
-                }
-                if ((value is byte) || (value is char))
-                {
-                    return 1;
-                }
-            }
-            return 0;
-        }
-
-        internal void CopyTo(SqlParameter destination)
-        {
-            ADP.CheckArgumentNull(destination, nameof(destination));
-
-            // NOTE: _parent is not cloned
-            destination._value = _value;
-            destination._direction = _direction;
-            destination._size = _size;
-            destination._offset = _offset;
-            destination._sourceColumn = _sourceColumn;
-            destination._sourceVersion = _sourceVersion;
-            destination._parameterName = _parameterName;
-
-            SqlParameterFlags setFlags = SqlParameterFlags.SourceColumnNullMapping | SqlParameterFlags.IsNullable | SqlParameterFlags.IsNull;
-            destination._flags = (destination._flags & ~setFlags) | (_flags & setFlags);
-
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlReferenceCollection.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlReferenceCollection.cs
deleted file mode 100644 (file)
index 2cf5729..0000000
+++ /dev/null
@@ -1,88 +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.Data.ProviderBase;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlReferenceCollection : DbReferenceCollection
-    {
-        internal const int DataReaderTag = 1;
-        internal const int CommandTag = 2;
-        internal const int BulkCopyTag = 3;
-
-        public override void Add(object value, int tag)
-        {
-            Debug.Assert(DataReaderTag == tag || CommandTag == tag || BulkCopyTag == tag, "unexpected tag?");
-            Debug.Assert(DataReaderTag != tag || value is SqlDataReader, "tag doesn't match object type: SqlDataReader");
-            Debug.Assert(CommandTag != tag || value is SqlCommand, "tag doesn't match object type: SqlCommand");
-            Debug.Assert(BulkCopyTag != tag || value is SqlBulkCopy, "tag doesn't match object type: SqlBulkCopy");
-
-            base.AddItem(value, tag);
-        }
-
-        internal void Deactivate()
-        {
-            base.Notify(0);
-        }
-
-        internal SqlDataReader FindLiveReader(SqlCommand command)
-        {
-            if (command == null)
-            {
-                // if null == command, will find first live datareader
-                return FindItem<SqlDataReader>(DataReaderTag, (dataReader) => (!dataReader.IsClosed));
-            }
-            else
-            {
-                // else will find live datareader associated with the command
-                return FindItem<SqlDataReader>(DataReaderTag, (dataReader) => ((!dataReader.IsClosed) && (command == dataReader.Command)));
-            }
-        }
-
-        // Finds a SqlCommand associated with the given StateObject
-        internal SqlCommand FindLiveCommand(TdsParserStateObject stateObj)
-        {
-            return FindItem<SqlCommand>(CommandTag, (command) => (command.StateObject == stateObj));
-        }
-
-        protected override void NotifyItem(int message, int tag, object value)
-        {
-            Debug.Assert(0 == message, "unexpected message?");
-            Debug.Assert(DataReaderTag == tag || CommandTag == tag || BulkCopyTag == tag, "unexpected tag?");
-
-            if (tag == DataReaderTag)
-            {
-                Debug.Assert(value is SqlDataReader, "Incorrect object type");
-                var rdr = (SqlDataReader)value;
-                if (!rdr.IsClosed)
-                {
-                    rdr.CloseReaderFromConnection();
-                }
-            }
-            else if (tag == CommandTag)
-            {
-                Debug.Assert(value is SqlCommand, "Incorrect object type");
-                ((SqlCommand)value).OnConnectionClosed();
-            }
-            else if (tag == BulkCopyTag)
-            {
-                Debug.Assert(value is SqlBulkCopy, "Incorrect object type");
-                ((SqlBulkCopy)value).OnConnectionClosed();
-            }
-        }
-
-        public override void Remove(object value)
-        {
-            Debug.Assert(value is SqlDataReader || value is SqlCommand || value is SqlBulkCopy, "SqlReferenceCollection.Remove expected a SqlDataReader or SqlCommand or SqlBulkCopy");
-
-            base.RemoveItem(value);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatedEvent.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatedEvent.cs
deleted file mode 100644 (file)
index e89af9d..0000000
+++ /dev/null
@@ -1,26 +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.Data;
-using System.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlRowUpdatedEventArgs : RowUpdatedEventArgs
-    {
-        public SqlRowUpdatedEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
-        : base(row, command, statementType, tableMapping)
-        {
-        }
-
-        public new SqlCommand Command
-        {
-            get
-            {
-                return (SqlCommand)base.Command;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatedEventHandler.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatedEventHandler.cs
deleted file mode 100644 (file)
index 01f2496..0000000
+++ /dev/null
@@ -1,8 +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.Data.SqlClient
-{
-    public delegate void SqlRowUpdatedEventHandler(object sender, SqlRowUpdatedEventArgs e);
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatingEvent.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatingEvent.cs
deleted file mode 100644 (file)
index 359a72c..0000000
+++ /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.Data;
-using System.Data.Common;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlRowUpdatingEventArgs : RowUpdatingEventArgs
-    {
-        public SqlRowUpdatingEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
-        : base(row, command, statementType, tableMapping)
-        {
-        }
-
-        public new SqlCommand Command
-        {
-            get { return (base.Command as SqlCommand); }
-            set { base.Command = value; }
-        }
-
-        protected override IDbCommand BaseCommand
-        {
-            get { return base.BaseCommand; }
-            set { base.BaseCommand = (value as SqlCommand); }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatingEventHandler.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlRowUpdatingEventHandler.cs
deleted file mode 100644 (file)
index 2ea4a91..0000000
+++ /dev/null
@@ -1,8 +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.Data.SqlClient
-{
-    public delegate void SqlRowUpdatingEventHandler(object sender, SqlRowUpdatingEventArgs e);
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlSequentialStream.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlSequentialStream.cs
deleted file mode 100644 (file)
index 409ac89..0000000
+++ /dev/null
@@ -1,316 +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.Data.Common;
-using System.Diagnostics;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlSequentialStream : System.IO.Stream
-    {
-        private SqlDataReader _reader;  // The SqlDataReader that we are reading data from
-        private readonly int _columnIndex;       // The index of out column in the table
-        private Task _currentTask;      // Holds the current task being processed
-        private int _readTimeout;       // Read timeout for this stream in ms (for Stream.ReadTimeout)
-        private readonly CancellationTokenSource _disposalTokenSource;    // Used to indicate that a cancellation is requested due to disposal
-
-        internal SqlSequentialStream(SqlDataReader reader, int columnIndex)
-        {
-            Debug.Assert(reader != null, "Null reader when creating sequential stream");
-            Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential stream");
-
-            _reader = reader;
-            _columnIndex = columnIndex;
-            _currentTask = null;
-            _disposalTokenSource = new CancellationTokenSource();
-
-            // Safely convert the CommandTimeout from seconds to milliseconds
-            if ((reader.Command != null) && (reader.Command.CommandTimeout != 0))
-            {
-                _readTimeout = (int)Math.Min((long)reader.Command.CommandTimeout * 1000L, (long)int.MaxValue);
-            }
-            else
-            {
-                _readTimeout = Timeout.Infinite;
-            }
-        }
-
-        public override bool CanRead
-        {
-            get { return ((_reader != null) && (!_reader.IsClosed)); }
-        }
-
-        public override bool CanSeek
-        {
-            get { return false; }
-        }
-
-        public override bool CanTimeout
-        {
-            get { return true; }
-        }
-
-        public override bool CanWrite
-        {
-            get { return false; }
-        }
-
-        public override void Flush()
-        { }
-
-        public override long Length
-        {
-            get { throw ADP.NotSupported(); }
-        }
-
-        public override long Position
-        {
-            get { throw ADP.NotSupported(); }
-            set { throw ADP.NotSupported(); }
-        }
-
-        public override int ReadTimeout
-        {
-            get { return _readTimeout; }
-            set
-            {
-                if ((value > 0) || (value == Timeout.Infinite))
-                {
-                    _readTimeout = value;
-                }
-                else
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(value));
-                }
-            }
-        }
-
-        internal int ColumnIndex
-        {
-            get { return _columnIndex; }
-        }
-
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            ValidateReadParameters(buffer, offset, count);
-            if (!CanRead)
-            {
-                throw ADP.ObjectDisposed(this);
-            }
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            try
-            {
-                return _reader.GetBytesInternalSequential(_columnIndex, buffer, offset, count, _readTimeout);
-            }
-            catch (SqlException ex)
-            {
-                // Stream.Read() can't throw a SqlException - so wrap it in an IOException
-                throw ADP.ErrorReadingFromStream(ex);
-            }
-        }
-
-
-        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
-        {
-            ValidateReadParameters(buffer, offset, count);
-
-            TaskCompletionSource<int> completion = new TaskCompletionSource<int>();
-            if (!CanRead)
-            {
-                completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
-            }
-            else
-            {
-                try
-                {
-                    Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null);
-                    if (original != null)
-                    {
-                        completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-                    }
-                    else
-                    {
-                        // Set up a combined cancellation token for both the user's and our disposal tokens
-                        CancellationTokenSource combinedTokenSource;
-                        if (!cancellationToken.CanBeCanceled)
-                        {
-                            // Users token is not cancellable - just use ours
-                            combinedTokenSource = _disposalTokenSource;
-                        }
-                        else
-                        {
-                            // Setup registrations from user and disposal token to cancel the combined token
-                            combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposalTokenSource.Token);
-                        }
-
-                        int bytesRead = 0;
-                        Task<int> getBytesTask = null;
-                        var reader = _reader;
-                        if ((reader != null) && (!cancellationToken.IsCancellationRequested) && (!_disposalTokenSource.Token.IsCancellationRequested))
-                        {
-                            getBytesTask = reader.GetBytesAsync(_columnIndex, buffer, offset, count, _readTimeout, combinedTokenSource.Token, out bytesRead);
-                        }
-
-                        if (getBytesTask == null)
-                        {
-                            _currentTask = null;
-                            if (cancellationToken.IsCancellationRequested)
-                            {
-                                completion.SetCanceled();
-                            }
-                            else if (!CanRead)
-                            {
-                                completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
-                            }
-                            else
-                            {
-                                completion.SetResult(bytesRead);
-                            }
-
-                            if (combinedTokenSource != _disposalTokenSource)
-                            {
-                                combinedTokenSource.Dispose();
-                            }
-                        }
-                        else
-                        {
-                            getBytesTask.ContinueWith((t) =>
-                            {
-                                _currentTask = null;
-                                // If we completed, but _reader is null (i.e. the stream is closed), then report cancellation
-                                if ((t.Status == TaskStatus.RanToCompletion) && (CanRead))
-                                {
-                                    completion.SetResult((int)t.Result);
-                                }
-                                else if (t.Status == TaskStatus.Faulted)
-                                {
-                                    if (t.Exception.InnerException is SqlException)
-                                    {
-                                        // Stream.ReadAsync() can't throw a SqlException - so wrap it in an IOException
-                                        completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException)));
-                                    }
-                                    else
-                                    {
-                                        completion.SetException(t.Exception.InnerException);
-                                    }
-                                }
-                                else if (!CanRead)
-                                {
-                                    completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
-                                }
-                                else
-                                {
-                                    completion.SetCanceled();
-                                }
-
-                                if (combinedTokenSource != _disposalTokenSource)
-                                {
-                                    combinedTokenSource.Dispose();
-                                }
-                            }, TaskScheduler.Default);
-                        }
-                    }
-                }
-                catch (Exception ex)
-                {
-                    // In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it
-                    completion.TrySetException(ex);
-                    Interlocked.CompareExchange(ref _currentTask, null, completion.Task);
-                    throw;
-                }
-            }
-
-            return completion.Task;
-        }
-
-        public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
-            TaskToApm.Begin(ReadAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncState);
-
-        public override int EndRead(IAsyncResult asyncResult) =>
-            TaskToApm.End<int>(asyncResult);
-
-        public override long Seek(long offset, IO.SeekOrigin origin)
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override void SetLength(long value)
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            throw ADP.NotSupported();
-        }
-
-        /// <summary>
-        /// Forces the stream to act as if it was closed (i.e. CanRead=false and Read() throws)
-        /// This does not actually close the stream, read off the rest of the data or dispose this
-        /// </summary>
-        internal void SetClosed()
-        {
-            _disposalTokenSource.Cancel();
-            _reader = null;
-
-            // Wait for pending task
-            var currentTask = _currentTask;
-            if (currentTask != null)
-            {
-                ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
-            }
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            if (disposing)
-            {
-                // Set the stream as closed
-                SetClosed();
-            }
-
-            base.Dispose(disposing);
-        }
-
-        /// <summary>
-        /// Checks the parameters passed into a Read() method are valid
-        /// </summary>
-        /// <param name="buffer"></param>
-        /// <param name="offset"></param>
-        /// <param name="count"></param>
-        internal static void ValidateReadParameters(byte[] buffer, int offset, int count)
-        {
-            if (buffer == null)
-            {
-                throw ADP.ArgumentNull(nameof(buffer));
-            }
-            if (offset < 0)
-            {
-                throw ADP.ArgumentOutOfRange(nameof(offset));
-            }
-            if (count < 0)
-            {
-                throw ADP.ArgumentOutOfRange(nameof(count));
-            }
-            try
-            {
-                if (checked(offset + count) > buffer.Length)
-                {
-                    throw ExceptionBuilder.InvalidOffsetLength();
-                }
-            }
-            catch (OverflowException)
-            {
-                // If we've overflowed when adding offset and count, then they never would have fit into buffer anyway
-                throw ExceptionBuilder.InvalidOffsetLength();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlSequentialTextReader.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlSequentialTextReader.cs
deleted file mode 100644 (file)
index a72355a..0000000
+++ /dev/null
@@ -1,532 +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.Data.Common;
-using System.Diagnostics;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlSequentialTextReader : System.IO.TextReader
-    {
-        private SqlDataReader _reader;  // The SqlDataReader that we are reading data from
-        private readonly int _columnIndex;       // The index of out column in the table
-        private readonly Encoding _encoding;     // Encoding for this character stream
-        private readonly Decoder _decoder;       // Decoder based on the encoding (NOTE: Decoders are stateful as they are designed to process streams of data)
-        private byte[] _leftOverBytes;  // Bytes leftover from the last Read() operation - this can be null if there were no bytes leftover (Possible optimization: re-use the same array?)
-        private int _peekedChar;        // The last character that we peeked at (or -1 if we haven't peeked at anything)
-        private Task _currentTask;      // The current async task
-        private readonly CancellationTokenSource _disposalTokenSource;    // Used to indicate that a cancellation is requested due to disposal
-
-        internal SqlSequentialTextReader(SqlDataReader reader, int columnIndex, Encoding encoding)
-        {
-            Debug.Assert(reader != null, "Null reader when creating sequential textreader");
-            Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential textreader");
-            Debug.Assert(encoding != null, "Null encoding when creating sequential textreader");
-
-            _reader = reader;
-            _columnIndex = columnIndex;
-            _encoding = encoding;
-            _decoder = encoding.GetDecoder();
-            _leftOverBytes = null;
-            _peekedChar = -1;
-            _currentTask = null;
-            _disposalTokenSource = new CancellationTokenSource();
-        }
-
-        internal int ColumnIndex
-        {
-            get { return _columnIndex; }
-        }
-
-        public override int Peek()
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-            if (IsClosed)
-            {
-                throw ADP.ObjectDisposed(this);
-            }
-
-            if (!HasPeekedChar)
-            {
-                _peekedChar = Read();
-            }
-
-            Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), $"Bad peeked character: {_peekedChar}");
-            return _peekedChar;
-        }
-
-        public override int Read()
-        {
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-            if (IsClosed)
-            {
-                throw ADP.ObjectDisposed(this);
-            }
-
-            int readChar = -1;
-
-            // If there is already a peeked char, then return it
-            if (HasPeekedChar)
-            {
-                readChar = _peekedChar;
-                _peekedChar = -1;
-            }
-            // If there is data available try to read a char
-            else
-            {
-                char[] tempBuffer = new char[1];
-                int charsRead = InternalRead(tempBuffer, 0, 1);
-                if (charsRead == 1)
-                {
-                    readChar = tempBuffer[0];
-                }
-            }
-
-            Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), $"Bad read character: {readChar}");
-            return readChar;
-        }
-
-        public override int Read(char[] buffer, int index, int count)
-        {
-            ValidateReadParameters(buffer, index, count);
-
-            if (IsClosed)
-            {
-                throw ADP.ObjectDisposed(this);
-            }
-            if (_currentTask != null)
-            {
-                throw ADP.AsyncOperationPending();
-            }
-
-            int charsRead = 0;
-            int charsNeeded = count;
-            // Load in peeked char
-            if ((charsNeeded > 0) && (HasPeekedChar))
-            {
-                Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}");
-                buffer[index + charsRead] = (char)_peekedChar;
-                charsRead++;
-                charsNeeded--;
-                _peekedChar = -1;
-            }
-
-            // If we need more data and there is data available, read
-            charsRead += InternalRead(buffer, index + charsRead, charsNeeded);
-
-            return charsRead;
-        }
-
-        public override Task<int> ReadAsync(char[] buffer, int index, int count)
-        {
-            ValidateReadParameters(buffer, index, count);
-            TaskCompletionSource<int> completion = new TaskCompletionSource<int>();
-
-            if (IsClosed)
-            {
-                completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
-            }
-            else
-            {
-                try
-                {
-                    Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null);
-                    if (original != null)
-                    {
-                        completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
-                    }
-                    else
-                    {
-                        bool completedSynchronously = true;
-                        int charsRead = 0;
-                        int adjustedIndex = index;
-                        int charsNeeded = count;
-
-                        // Load in peeked char
-                        if ((HasPeekedChar) && (charsNeeded > 0))
-                        {
-                            // Take a copy of _peekedChar in case it is cleared during close
-                            int peekedChar = _peekedChar;
-                            if (peekedChar >= char.MinValue)
-                            {
-                                Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}");
-                                buffer[adjustedIndex] = (char)peekedChar;
-                                adjustedIndex++;
-                                charsRead++;
-                                charsNeeded--;
-                                _peekedChar = -1;
-                            }
-                        }
-
-                        int byteBufferUsed;
-                        byte[] byteBuffer = PrepareByteBuffer(charsNeeded, out byteBufferUsed);
-
-                        // Permit a 0 byte read in order to advance the reader to the correct column
-                        if ((byteBufferUsed < byteBuffer.Length) || (byteBuffer.Length == 0))
-                        {
-                            int bytesRead;
-                            var reader = _reader;
-                            if (reader != null)
-                            {
-                                Task<int> getBytesTask = reader.GetBytesAsync(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed, Timeout.Infinite, _disposalTokenSource.Token, out bytesRead);
-                                if (getBytesTask == null)
-                                {
-                                    byteBufferUsed += bytesRead;
-                                }
-                                else
-                                {
-                                    // We need more data - setup the callback, and mark this as not completed sync
-                                    completedSynchronously = false;
-                                    getBytesTask.ContinueWith((t) =>
-                                    {
-                                        _currentTask = null;
-                                        // If we completed but the textreader is closed, then report cancellation
-                                        if ((t.Status == TaskStatus.RanToCompletion) && (!IsClosed))
-                                        {
-                                            try
-                                            {
-                                                int bytesReadFromStream = t.Result;
-                                                byteBufferUsed += bytesReadFromStream;
-                                                if (byteBufferUsed > 0)
-                                                {
-                                                    charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
-                                                }
-                                                completion.SetResult(charsRead);
-                                            }
-                                            catch (Exception ex)
-                                            {
-                                                completion.SetException(ex);
-                                            }
-                                        }
-                                        else if (IsClosed)
-                                        {
-                                            completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
-                                        }
-                                        else if (t.Status == TaskStatus.Faulted)
-                                        {
-                                            if (t.Exception.InnerException is SqlException)
-                                            {
-                                                // ReadAsync can't throw a SqlException, so wrap it in an IOException
-                                                completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException)));
-                                            }
-                                            else
-                                            {
-                                                completion.SetException(t.Exception.InnerException);
-                                            }
-                                        }
-                                        else
-                                        {
-                                            completion.SetCanceled();
-                                        }
-                                    }, TaskScheduler.Default);
-                                }
-
-
-                                if ((completedSynchronously) && (byteBufferUsed > 0))
-                                {
-                                    // No more data needed, decode what we have
-                                    charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded);
-                                }
-                            }
-                            else
-                            {
-                                // Reader is null, close must of happened in the middle of this read
-                                completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this)));
-                            }
-                        }
-
-
-                        if (completedSynchronously)
-                        {
-                            _currentTask = null;
-                            if (IsClosed)
-                            {
-                                completion.SetCanceled();
-                            }
-                            else
-                            {
-                                completion.SetResult(charsRead);
-                            }
-                        }
-                    }
-                }
-                catch (Exception ex)
-                {
-                    // In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it
-                    completion.TrySetException(ex);
-                    Interlocked.CompareExchange(ref _currentTask, null, completion.Task);
-                    throw;
-                }
-            }
-
-            return completion.Task;
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            if (disposing)
-            {
-                // Set the textreader as closed
-                SetClosed();
-            }
-
-            base.Dispose(disposing);
-        }
-
-        /// <summary>
-        /// Forces the TextReader to act as if it was closed
-        /// This does not actually close the stream, read off the rest of the data or dispose this
-        /// </summary>
-        internal void SetClosed()
-        {
-            _disposalTokenSource.Cancel();
-            _reader = null;
-            _peekedChar = -1;
-
-            // Wait for pending task
-            var currentTask = _currentTask;
-            if (currentTask != null)
-            {
-                ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();
-            }
-        }
-
-        /// <summary>
-        /// Performs the actual reading and converting
-        /// NOTE: This assumes that buffer, index and count are all valid, we're not closed (!IsClosed) and that there is data left (IsDataLeft())
-        /// </summary>
-        /// <param name="buffer"></param>
-        /// <param name="index"></param>
-        /// <param name="count"></param>
-        /// <returns></returns>
-        private int InternalRead(char[] buffer, int index, int count)
-        {
-            Debug.Assert(buffer != null, "Null output buffer");
-            Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), $"Bad count: {count} or index: {index}");
-            Debug.Assert(!IsClosed, "Can't read while textreader is closed");
-
-            try
-            {
-                int byteBufferUsed;
-                byte[] byteBuffer = PrepareByteBuffer(count, out byteBufferUsed);
-                byteBufferUsed += _reader.GetBytesInternalSequential(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed);
-
-                if (byteBufferUsed > 0)
-                {
-                    return DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, index, count);
-                }
-                else
-                {
-                    // Nothing to read, or nothing read
-                    return 0;
-                }
-            }
-            catch (SqlException ex)
-            {
-                // Read can't throw a SqlException - so wrap it in an IOException
-                throw ADP.ErrorReadingFromStream(ex);
-            }
-        }
-
-        /// <summary>
-        /// Creates a byte array large enough to store all bytes for the characters in the current encoding, then fills it with any leftover bytes
-        /// </summary>
-        /// <param name="numberOfChars">Number of characters that are to be read</param>
-        /// <param name="byteBufferUsed">Number of bytes pre-filled by the leftover bytes</param>
-        /// <returns>A byte array of the correct size, pre-filled with leftover bytes</returns>
-        private byte[] PrepareByteBuffer(int numberOfChars, out int byteBufferUsed)
-        {
-            Debug.Assert(numberOfChars >= 0, "Can't prepare a byte buffer for negative characters");
-
-            byte[] byteBuffer;
-
-            if (numberOfChars == 0)
-            {
-                byteBuffer = Array.Empty<byte>();
-                byteBufferUsed = 0;
-            }
-            else
-            {
-                int byteBufferSize = _encoding.GetMaxByteCount(numberOfChars);
-
-                if (_leftOverBytes != null)
-                {
-                    // If we have more leftover bytes than we need for this conversion, then just re-use the leftover buffer
-                    if (_leftOverBytes.Length > byteBufferSize)
-                    {
-                        byteBuffer = _leftOverBytes;
-                        byteBufferUsed = byteBuffer.Length;
-                    }
-                    else
-                    {
-                        // Otherwise, copy over the leftover buffer
-                        byteBuffer = new byte[byteBufferSize];
-                        Buffer.BlockCopy(_leftOverBytes, 0, byteBuffer, 0, _leftOverBytes.Length);
-                        byteBufferUsed = _leftOverBytes.Length;
-                    }
-                }
-                else
-                {
-                    byteBuffer = new byte[byteBufferSize];
-                    byteBufferUsed = 0;
-                }
-            }
-
-            return byteBuffer;
-        }
-
-        /// <summary>
-        /// Decodes the given bytes into characters, and stores the leftover bytes for later use
-        /// </summary>
-        /// <param name="inBuffer">Buffer of bytes to decode</param>
-        /// <param name="inBufferCount">Number of bytes to decode from the inBuffer</param>
-        /// <param name="outBuffer">Buffer to write the characters to</param>
-        /// <param name="outBufferOffset">Offset to start writing to outBuffer at</param>
-        /// <param name="outBufferCount">Maximum number of characters to decode</param>
-        /// <returns>The actual number of characters decoded</returns>
-        private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount)
-        {
-            Debug.Assert(inBuffer != null, "Null input buffer");
-            Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), $"Bad inBufferCount: {inBufferCount}");
-            Debug.Assert(outBuffer != null, "Null output buffer");
-            Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), $"Bad outBufferCount: {outBufferCount} or outBufferOffset: {outBufferOffset}");
-
-            int charsRead;
-            int bytesUsed;
-            bool completed;
-            _decoder.Convert(inBuffer, 0, inBufferCount, outBuffer, outBufferOffset, outBufferCount, false, out bytesUsed, out charsRead, out completed);
-
-            // completed may be false and there is no spare bytes if the Decoder has stored bytes to use later
-            if ((!completed) && (bytesUsed < inBufferCount))
-            {
-                _leftOverBytes = new byte[inBufferCount - bytesUsed];
-                Buffer.BlockCopy(inBuffer, bytesUsed, _leftOverBytes, 0, _leftOverBytes.Length);
-            }
-            else
-            {
-                // If Convert() sets completed to true, then it must have used all of the bytes we gave it
-                Debug.Assert(bytesUsed >= inBufferCount, "Converted completed, but not all bytes were used");
-                _leftOverBytes = null;
-            }
-
-            Debug.Assert(((_reader == null) || (_reader.ColumnDataBytesRemaining() > 0) || (!completed) || (_leftOverBytes == null)), "Stream has run out of data and the decoder finished, but there are leftover bytes");
-            Debug.Assert(charsRead > 0, "Converted no chars. Bad encoding?");
-
-            return charsRead;
-        }
-
-        /// <summary>
-        /// True if this TextReader is supposed to be closed
-        /// </summary>
-        private bool IsClosed
-        {
-            get { return (_reader == null); }
-        }
-
-        /// <summary>
-        /// True if there is a peeked character available
-        /// </summary>
-        private bool HasPeekedChar
-        {
-            get { return (_peekedChar >= char.MinValue); }
-        }
-
-        /// <summary>
-        /// Checks the parameters passed into a Read() method are valid
-        /// </summary>
-        /// <param name="buffer"></param>
-        /// <param name="index"></param>
-        /// <param name="count"></param>
-        internal static void ValidateReadParameters(char[] buffer, int index, int count)
-        {
-            if (buffer == null)
-            {
-                throw ADP.ArgumentNull(nameof(buffer));
-            }
-            if (index < 0)
-            {
-                throw ADP.ArgumentOutOfRange(nameof(index));
-            }
-            if (count < 0)
-            {
-                throw ADP.ArgumentOutOfRange(nameof(count));
-            }
-            try
-            {
-                if (checked(index + count) > buffer.Length)
-                {
-                    throw ExceptionBuilder.InvalidOffsetLength();
-                }
-            }
-            catch (OverflowException)
-            {
-                // If we've overflowed when adding index and count, then they never would have fit into buffer anyway
-                throw ExceptionBuilder.InvalidOffsetLength();
-            }
-        }
-    }
-
-    internal sealed class SqlUnicodeEncoding : UnicodeEncoding
-    {
-        private static readonly SqlUnicodeEncoding s_singletonEncoding = new SqlUnicodeEncoding();
-
-        private SqlUnicodeEncoding() : base(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false)
-        { }
-
-        public override Decoder GetDecoder()
-        {
-            return new SqlUnicodeDecoder();
-        }
-
-        public override int GetMaxByteCount(int charCount)
-        {
-            // SQL Server never sends a BOM, so we can assume that its 2 bytes per char
-            return charCount * 2;
-        }
-
-        public static Encoding SqlUnicodeEncodingInstance
-        {
-            get { return s_singletonEncoding; }
-        }
-
-        private sealed class SqlUnicodeDecoder : Decoder
-        {
-            public override int GetCharCount(byte[] bytes, int index, int count)
-            {
-                // SQL Server never sends a BOM, so we can assume that its 2 bytes per char
-                return count / 2;
-            }
-
-            public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
-            {
-                // This method is required - simply call Convert()
-                int bytesUsed;
-                int charsUsed;
-                bool completed;
-                Convert(bytes, byteIndex, byteCount, chars, charIndex, chars.Length - charIndex, true, out bytesUsed, out charsUsed, out completed);
-                return charsUsed;
-            }
-
-            public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
-            {
-                // Assume 2 bytes per char and no BOM
-                charsUsed = Math.Min(charCount, byteCount / 2);
-                bytesUsed = charsUsed * 2;
-                completed = (bytesUsed == byteCount);
-
-                // BlockCopy uses offsets\length measured in bytes, not the actual array index
-                Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * 2, bytesUsed);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlStatistics.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlStatistics.cs
deleted file mode 100644 (file)
index 0175966..0000000
+++ /dev/null
@@ -1,340 +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.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlStatistics
-    {
-        internal static SqlStatistics StartTimer(SqlStatistics statistics)
-        {
-            if ((null != statistics) && !statistics.RequestExecutionTimer())
-            {
-                // we're re-entrant -- don't bother.
-                statistics = null;
-            }
-            return statistics;
-        }
-
-        internal static void StopTimer(SqlStatistics statistics)
-        {
-            if (null != statistics)
-            {
-                statistics.ReleaseAndUpdateExecutionTimer();
-            }
-        }
-
-        // internal values that are not exposed through properties
-        internal long _closeTimestamp;
-        internal long _openTimestamp;
-        internal long _startExecutionTimestamp;
-        internal long _startFetchTimestamp;
-        internal long _startNetworkServerTimestamp;
-
-        // internal values that are exposed through properties
-        internal long _buffersReceived;
-        internal long _buffersSent;
-        internal long _bytesReceived;
-        internal long _bytesSent;
-        internal long _connectionTime;
-        internal long _cursorOpens;
-        internal long _executionTime;
-        internal long _iduCount;
-        internal long _iduRows;
-        internal long _networkServerTime;
-        internal long _preparedExecs;
-        internal long _prepares;
-        internal long _selectCount;
-        internal long _selectRows;
-        internal long _serverRoundtrips;
-        internal long _sumResultSets;
-        internal long _transactions;
-        internal long _unpreparedExecs;
-
-        // these flags are required if statistics is turned on/off in the middle of command execution
-        private bool _waitForDoneAfterRow;
-        private bool _waitForReply;
-
-
-        internal bool WaitForDoneAfterRow
-        {
-            get
-            {
-                return _waitForDoneAfterRow;
-            }
-            set
-            {
-                _waitForDoneAfterRow = value;
-            }
-        }
-
-        internal bool WaitForReply
-        {
-            get
-            {
-                return _waitForReply;
-            }
-        }
-
-        internal SqlStatistics()
-        {
-        }
-
-        internal void ContinueOnNewConnection()
-        {
-            _startExecutionTimestamp = 0;
-            _startFetchTimestamp = 0;
-            _waitForDoneAfterRow = false;
-            _waitForReply = false;
-        }
-
-        internal IDictionary GetDictionary()
-        {
-            const int Count = 18;
-            var dictionary = new StatisticsDictionary(Count)
-            {
-                { "BuffersReceived", _buffersReceived },
-                { "BuffersSent", _buffersSent },
-                { "BytesReceived", _bytesReceived },
-                { "BytesSent", _bytesSent },
-                { "CursorOpens", _cursorOpens },
-                { "IduCount", _iduCount },
-                { "IduRows", _iduRows },
-                { "PreparedExecs", _preparedExecs },
-                { "Prepares", _prepares },
-                { "SelectCount", _selectCount },
-                { "SelectRows", _selectRows },
-                { "ServerRoundtrips", _serverRoundtrips },
-                { "SumResultSets", _sumResultSets },
-                { "Transactions", _transactions },
-                { "UnpreparedExecs", _unpreparedExecs },
-
-                { "ConnectionTime", ADP.TimerToMilliseconds(_connectionTime) },
-                { "ExecutionTime", ADP.TimerToMilliseconds(_executionTime) },
-                { "NetworkServerTime", ADP.TimerToMilliseconds(_networkServerTime) }
-            };
-            Debug.Assert(dictionary.Count == Count);
-            return dictionary;
-        }
-
-        internal bool RequestExecutionTimer()
-        {
-            if (_startExecutionTimestamp == 0)
-            {
-                ADP.TimerCurrent(out _startExecutionTimestamp);
-                return true;
-            }
-            return false;
-        }
-
-        internal void RequestNetworkServerTimer()
-        {
-            Debug.Assert(_startExecutionTimestamp != 0, "No network time expected outside execution period");
-            if (_startNetworkServerTimestamp == 0)
-            {
-                ADP.TimerCurrent(out _startNetworkServerTimestamp);
-            }
-            _waitForReply = true;
-        }
-
-        internal void ReleaseAndUpdateExecutionTimer()
-        {
-            if (_startExecutionTimestamp > 0)
-            {
-                _executionTime += (ADP.TimerCurrent() - _startExecutionTimestamp);
-                _startExecutionTimestamp = 0;
-            }
-        }
-
-        internal void ReleaseAndUpdateNetworkServerTimer()
-        {
-            if (_waitForReply && _startNetworkServerTimestamp > 0)
-            {
-                _networkServerTime += (ADP.TimerCurrent() - _startNetworkServerTimestamp);
-                _startNetworkServerTimestamp = 0;
-            }
-            _waitForReply = false;
-        }
-
-        internal void Reset()
-        {
-            _buffersReceived = 0;
-            _buffersSent = 0;
-            _bytesReceived = 0;
-            _bytesSent = 0;
-            _connectionTime = 0;
-            _cursorOpens = 0;
-            _executionTime = 0;
-            _iduCount = 0;
-            _iduRows = 0;
-            _networkServerTime = 0;
-            _preparedExecs = 0;
-            _prepares = 0;
-            _selectCount = 0;
-            _selectRows = 0;
-            _serverRoundtrips = 0;
-            _sumResultSets = 0;
-            _transactions = 0;
-            _unpreparedExecs = 0;
-            _waitForDoneAfterRow = false;
-            _waitForReply = false;
-            _startExecutionTimestamp = 0;
-            _startNetworkServerTimestamp = 0;
-        }
-
-        internal void SafeAdd(ref long value, long summand)
-        {
-            if (long.MaxValue - value > summand)
-            {
-                value += summand;
-            }
-            else
-            {
-                value = long.MaxValue;
-            }
-        }
-
-        internal long SafeIncrement(ref long value)
-        {
-            if (value < long.MaxValue) value++;
-            return value;
-        }
-
-        internal void UpdateStatistics()
-        {
-            // update connection time
-            if (_closeTimestamp >= _openTimestamp)
-            {
-                SafeAdd(ref _connectionTime, _closeTimestamp - _openTimestamp);
-            }
-            else
-            {
-                _connectionTime = long.MaxValue;
-            }
-        }
-
-        // We subclass Dictionary to provide our own implementation of GetEnumerator, CopyTo, Keys.CopyTo,
-        // and Values.CopyTo to match the behavior of Hashtable, which is used in the full framework:
-        //
-        //  - Hashtable's IEnumerator.GetEnumerator enumerator yields DictionaryEntry entries whereas
-        //    Dictionary's yields KeyValuePair entries.
-        //
-        //  - When arrayIndex > array.Length, Hashtable throws ArgumentException whereas Dictionary
-        //    throws ArgumentOutOfRangeException.
-        //
-        //  - Hashtable specifies the ArgumentOutOfRangeException paramName as "arrayIndex" whereas
-        //    Dictionary uses "index".
-        //
-        //  - When the array is of a mismatched type, Hashtable throws InvalidCastException whereas
-        //    Dictionary throws ArrayTypeMismatchException.
-        //
-        //  - Hashtable allows copying values to a long[] array via Values.CopyTo, whereas Dictionary
-        //    throws ArgumentException due to the "Target array type is not compatible with type of
-        //    items in the collection" (when Dictionary<object, object> is used).
-        //
-        // Ideally this would derive from Dictionary<string, long>, but that would break compatibility
-        // with the full framework, which allows adding keys/values of any type.
-        private sealed class StatisticsDictionary : Dictionary<object, object>, IDictionary, IEnumerable
-        {
-            private Collection _keys;
-            private Collection _values;
-
-            public StatisticsDictionary(int capacity) : base(capacity) { }
-
-            ICollection IDictionary.Keys => _keys ?? (_keys = new Collection(this, Keys));
-
-            ICollection IDictionary.Values => _values ?? (_values = new Collection(this, Values));
-
-            // Return a DictionaryEntry enumerator instead of a KeyValuePair enumerator.
-            IEnumerator IEnumerable.GetEnumerator() => ((IDictionary)this).GetEnumerator();
-
-            void ICollection.CopyTo(Array array, int arrayIndex)
-            {
-                ValidateCopyToArguments(array, arrayIndex);
-
-                foreach (KeyValuePair<object, object> pair in this)
-                {
-                    var entry = new DictionaryEntry(pair.Key, pair.Value);
-                    array.SetValue(entry, arrayIndex++);
-                }
-            }
-
-            private void CopyKeys(Array array, int arrayIndex)
-            {
-                ValidateCopyToArguments(array, arrayIndex);
-
-                foreach (KeyValuePair<object, object> pair in this)
-                {
-                    array.SetValue(pair.Key, arrayIndex++);
-                }
-            }
-
-            private void CopyValues(Array array, int arrayIndex)
-            {
-                ValidateCopyToArguments(array, arrayIndex);
-
-                foreach (KeyValuePair<object, object> pair in this)
-                {
-                    array.SetValue(pair.Value, arrayIndex++);
-                }
-            }
-
-            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);
-                if (arrayIndex < 0)
-                    throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
-                if (array.Length - arrayIndex < Count)
-                    throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
-            }
-
-            private sealed class Collection : ICollection
-            {
-                private readonly StatisticsDictionary _dictionary;
-                private readonly ICollection _collection;
-
-                public Collection(StatisticsDictionary dictionary, ICollection collection)
-                {
-                    Debug.Assert(dictionary != null);
-                    Debug.Assert(collection != null);
-                    Debug.Assert((collection is KeyCollection) || (collection is ValueCollection));
-
-                    _dictionary = dictionary;
-                    _collection = collection;
-                }
-
-                int ICollection.Count => _collection.Count;
-
-                bool ICollection.IsSynchronized => _collection.IsSynchronized;
-
-                object ICollection.SyncRoot => _collection.SyncRoot;
-
-                void ICollection.CopyTo(Array array, int arrayIndex)
-                {
-                    if (_collection is KeyCollection)
-                    {
-                        _dictionary.CopyKeys(array, arrayIndex);
-                    }
-                    else
-                    {
-                        _dictionary.CopyValues(array, arrayIndex);
-                    }
-                }
-
-                IEnumerator IEnumerable.GetEnumerator() => _collection.GetEnumerator();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlStream.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlStream.cs
deleted file mode 100644 (file)
index 42d1163..0000000
+++ /dev/null
@@ -1,733 +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.Generic;
-using System.Data.Common;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.IO;
-using System.Text;
-using System.Xml;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class SqlStream : Stream
-    {
-        private SqlDataReader _reader; // reader we will stream off
-        private readonly int _columnOrdinal;
-        private long _bytesCol;
-        private int _bom;
-        private byte[] _bufferedData;
-        private readonly bool _processAllRows;
-        private readonly bool _advanceReader;
-        private bool _readFirstRow = false;
-        private bool _endOfColumn = false;
-
-        internal SqlStream(SqlDataReader reader, bool addByteOrderMark, bool processAllRows) :
-            this(0, reader, addByteOrderMark, processAllRows, true)
-        {
-        }
-
-        internal SqlStream(int columnOrdinal, SqlDataReader reader, bool addByteOrderMark, bool processAllRows, bool advanceReader)
-        {
-            _columnOrdinal = columnOrdinal;
-            _reader = reader;
-            _bom = addByteOrderMark ? 0xfeff : 0;
-            _processAllRows = processAllRows;
-            _advanceReader = advanceReader;
-        }
-
-        public override bool CanRead
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        public override bool CanSeek
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public override bool CanWrite
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public override long Length
-        {
-            get
-            {
-                throw ADP.NotSupported();
-            }
-        }
-
-        public override long Position
-        {
-            get
-            {
-                throw ADP.NotSupported();
-            }
-            set
-            {
-                throw ADP.NotSupported();
-            }
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            try
-            {
-                if (disposing && _advanceReader && _reader != null && !_reader.IsClosed)
-                {
-                    _reader.Close();
-                }
-                _reader = null;
-            }
-            finally
-            {
-                base.Dispose(disposing);
-            }
-        }
-
-        public override void Flush()
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            int intCount = 0;
-            int cBufferedData = 0;
-
-            if ((null == _reader))
-            {
-                throw ADP.StreamClosed();
-            }
-            if (null == buffer)
-            {
-                throw ADP.ArgumentNull(nameof(buffer));
-            }
-            if ((offset < 0) || (count < 0))
-            {
-                throw ADP.ArgumentOutOfRange(string.Empty, (offset < 0 ? nameof(offset) : nameof(count)));
-            }
-            if (buffer.Length - offset < count)
-            {
-                throw ADP.ArgumentOutOfRange(nameof(count));
-            }
-
-            // Need to find out if we should add byte order mark or not.
-            // We need to add this if we are getting ntext xml, not if we are getting binary xml
-            // Binary Xml always begins with the bytes 0xDF and 0xFF
-            // If we aren't getting these, then we are getting unicode xml
-            if (_bom > 0)
-            {
-                // Read and buffer the first two bytes
-                _bufferedData = new byte[2];
-                cBufferedData = ReadBytes(_bufferedData, 0, 2);
-                // Check to se if we should add the byte order mark
-                if ((cBufferedData < 2) || ((_bufferedData[0] == 0xDF) && (_bufferedData[1] == 0xFF)))
-                {
-                    _bom = 0;
-                }
-                while (count > 0)
-                {
-                    if (_bom > 0)
-                    {
-                        buffer[offset] = (byte)_bom;
-                        _bom >>= 8;
-                        offset++;
-                        count--;
-                        intCount++;
-                    }
-                    else
-                    {
-                        break;
-                    }
-                }
-            }
-
-            if (cBufferedData > 0)
-            {
-                while (count > 0)
-                {
-                    buffer[offset++] = _bufferedData[0];
-                    intCount++;
-                    count--;
-                    if ((cBufferedData > 1) && (count > 0))
-                    {
-                        buffer[offset++] = _bufferedData[1];
-                        intCount++;
-                        count--;
-                        break;
-                    }
-                }
-                _bufferedData = null;
-            }
-
-            intCount += ReadBytes(buffer, offset, count);
-
-            return intCount;
-        }
-
-        private static bool AdvanceToNextRow(SqlDataReader reader)
-        {
-            Debug.Assert(reader != null && !reader.IsClosed);
-
-            // this method skips empty result sets
-            do
-            {
-                if (reader.Read())
-                {
-                    return true;
-                }
-            } while (reader.NextResult());
-
-            // no more rows
-            return false;
-        }
-
-        private int ReadBytes(byte[] buffer, int offset, int count)
-        {
-            bool gotData = true;
-            int intCount = 0;
-            int cb = 0;
-
-            if (_reader.IsClosed || _endOfColumn)
-            {
-                return 0;
-            }
-            try
-            {
-                while (count > 0)
-                {
-                    // if no bytes were read, get the next row
-                    if (_advanceReader && (0 == _bytesCol))
-                    {
-                        gotData = false;
-
-                        if (_readFirstRow && !_processAllRows)
-                        {
-                            // for XML column, stop processing after the first row
-                            // no op here - reader is closed after the end of this loop
-                        }
-                        else if (AdvanceToNextRow(_reader))
-                        {
-                            _readFirstRow = true;
-
-                            if (_reader.IsDBNull(_columnOrdinal))
-                            {
-                                // Handle row with DBNULL as empty data
-                                // for XML column, processing is stopped on the next loop since _readFirstRow is true
-                                continue;
-                            }
-
-                            // the value is not null, read it
-                            gotData = true;
-                        }
-                        // else AdvanceToNextRow has returned false - no more rows or result sets remained, stop processing
-                    }
-
-                    if (gotData)
-                    {
-                        cb = (int)_reader.GetBytesInternal(_columnOrdinal, _bytesCol, buffer, offset, count);
-
-                        if (cb < count)
-                        {
-                            _bytesCol = 0;
-                            gotData = false;
-                            if (!_advanceReader)
-                            {
-                                _endOfColumn = true;
-                            }
-                        }
-                        else
-                        {
-                            Debug.Assert(cb == count);
-                            _bytesCol += cb;
-                        }
-
-                        // we are guaranteed that cb is < Int32.Max since we always pass in count which is of type Int32 to
-                        // our getbytes interface
-                        count -= (int)cb;
-                        offset += (int)cb;
-                        intCount += (int)cb;
-                    }
-                    else
-                    {
-                        break; // no more data available, we are done
-                    }
-                }
-                if (!gotData && _advanceReader)
-                {
-                    _reader.Close();    // Need to close the reader if we are done reading
-                }
-            }
-            catch (Exception e)
-            {
-                if (_advanceReader && ADP.IsCatchableExceptionType(e))
-                {
-                    _reader.Close();
-                }
-                throw;
-            }
-
-            return intCount;
-        }
-
-        internal XmlReader ToXmlReader(bool async = false)
-        {
-            return SqlTypeWorkarounds.SqlXmlCreateSqlXmlReader(this, closeInput: true, async: async);
-        }
-
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override void SetLength(long value)
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            throw ADP.NotSupported();
-        }
-    }
-
-
-    // XmlTextReader does not read all the bytes off the network buffers, so we have to cache it here in the random access
-    // case. This causes double buffering and is a perf hit, but this is not the high perf way for accessing this type of data.
-    // In the case of sequential access, we do not have to do any buffering since the XmlTextReader we return can become
-    // invalid as soon as we move off the current column.
-    internal sealed class SqlCachedStream : Stream
-    {
-        private int _currentPosition;   // Position within the current array byte
-        private int _currentArrayIndex; // Index into the _cachedBytes List
-        private List<byte[]> _cachedBytes;
-        private long _totalLength;
-
-        // Reads off from the network buffer and caches bytes. Only reads one column value in the current row.
-        internal SqlCachedStream(SqlCachedBuffer sqlBuf)
-        {
-            _cachedBytes = sqlBuf.CachedBytes;
-        }
-
-        public override bool CanRead
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        public override bool CanSeek
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        public override bool CanWrite
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public override long Length
-        {
-            get
-            {
-                return TotalLength;
-            }
-        }
-
-        public override long Position
-        {
-            get
-            {
-                long pos = 0;
-                if (_currentArrayIndex > 0)
-                {
-                    for (int ii = 0; ii < _currentArrayIndex; ii++)
-                    {
-                        pos += _cachedBytes[ii].Length;
-                    }
-                }
-                pos += _currentPosition;
-                return pos;
-            }
-            set
-            {
-                if (null == _cachedBytes)
-                {
-                    throw ADP.StreamClosed(ADP.ParameterSetPosition);
-                }
-                SetInternalPosition(value, ADP.ParameterSetPosition);
-            }
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            try
-            {
-                if (disposing && _cachedBytes != null)
-                    _cachedBytes.Clear();
-                _cachedBytes = null;
-                _currentPosition = 0;
-                _currentArrayIndex = 0;
-                _totalLength = 0;
-            }
-            finally
-            {
-                base.Dispose(disposing);
-            }
-        }
-
-        public override void Flush()
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            int cb;
-            int intCount = 0;
-
-            if (null == _cachedBytes)
-            {
-                throw ADP.StreamClosed();
-            }
-
-            if (null == buffer)
-            {
-                throw ADP.ArgumentNull(nameof(buffer));
-            }
-
-            if ((offset < 0) || (count < 0))
-            {
-                throw ADP.ArgumentOutOfRange(string.Empty, (offset < 0 ? nameof(offset) : nameof(count)));
-            }
-
-            if (buffer.Length - offset < count)
-            {
-                throw ADP.ArgumentOutOfRange(nameof(count));
-            }
-
-            if (_cachedBytes.Count <= _currentArrayIndex)
-            {
-                return 0;       // Everything is read!
-            }
-
-            while (count > 0)
-            {
-                if (_cachedBytes[_currentArrayIndex].Length <= _currentPosition)
-                {
-                    _currentArrayIndex++;       // We are done reading this chunk, go to next
-                    if (_cachedBytes.Count > _currentArrayIndex)
-                    {
-                        _currentPosition = 0;
-                    }
-                    else
-                    {
-                        break;
-                    }
-                }
-                cb = _cachedBytes[_currentArrayIndex].Length - _currentPosition;
-                if (cb > count)
-                    cb = count;
-                Buffer.BlockCopy(_cachedBytes[_currentArrayIndex], _currentPosition, buffer, offset, cb);
-
-                _currentPosition += cb;
-                count -= (int)cb;
-                offset += (int)cb;
-                intCount += (int)cb;
-            }
-
-            return intCount;
-        }
-
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            long pos = 0;
-
-            if (null == _cachedBytes)
-            {
-                throw ADP.StreamClosed();
-            }
-
-            switch (origin)
-            {
-                case SeekOrigin.Begin:
-                    SetInternalPosition(offset, nameof(offset));
-                    break;
-
-                case SeekOrigin.Current:
-                    pos = offset + Position;
-                    SetInternalPosition(pos, nameof(offset));
-                    break;
-
-                case SeekOrigin.End:
-                    pos = TotalLength + offset;
-                    SetInternalPosition(pos, nameof(offset));
-                    break;
-
-                default:
-                    throw ADP.InvalidSeekOrigin(nameof(offset));
-            }
-            return pos;
-        }
-
-        public override void SetLength(long value)
-        {
-            throw ADP.NotSupported();
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            throw ADP.NotSupported();
-        }
-
-        private void SetInternalPosition(long lPos, string argumentName)
-        {
-            long pos = lPos;
-
-            if (pos < 0)
-            {
-                throw new ArgumentOutOfRangeException(argumentName);
-            }
-            for (int ii = 0; ii < _cachedBytes.Count; ii++)
-            {
-                if (pos > _cachedBytes[ii].Length)
-                {
-                    pos -= _cachedBytes[ii].Length;
-                }
-                else
-                {
-                    _currentArrayIndex = ii;
-                    _currentPosition = (int)pos;
-                    return;
-                }
-            }
-            if (pos > 0)
-                throw new ArgumentOutOfRangeException(argumentName);
-        }
-
-        private long TotalLength
-        {
-            get
-            {
-                if ((_totalLength == 0) && (_cachedBytes != null))
-                {
-                    long pos = 0;
-                    for (int ii = 0; ii < _cachedBytes.Count; ii++)
-                    {
-                        pos += _cachedBytes[ii].Length;
-                    }
-                    _totalLength = pos;
-                }
-                return _totalLength;
-            }
-        }
-    }
-
-    internal sealed class SqlStreamingXml
-    {
-        private readonly int _columnOrdinal;
-        private SqlDataReader _reader;
-        private XmlReader _xmlReader;
-        private XmlWriter _xmlWriter;
-        private StringWriter _strWriter;
-        private long _charsRemoved;
-
-        public SqlStreamingXml(int i, SqlDataReader reader)
-        {
-            _columnOrdinal = i;
-            _reader = reader;
-        }
-
-        public void Close()
-        {
-            ((IDisposable)_xmlWriter).Dispose();
-            ((IDisposable)_xmlReader).Dispose();
-            _reader = null;
-            _xmlReader = null;
-            _xmlWriter = null;
-            _strWriter = null;
-        }
-
-        public int ColumnOrdinal
-        {
-            get
-            {
-                return _columnOrdinal;
-            }
-        }
-
-        public long GetChars(long dataIndex, char[] buffer, int bufferIndex, int length)
-        {
-            if (_xmlReader == null)
-            {
-                SqlStream sqlStream = new SqlStream(_columnOrdinal, _reader, true /* addByteOrderMark */, false /* processAllRows*/, false /*advanceReader*/);
-                _xmlReader = sqlStream.ToXmlReader();
-                _strWriter = new StringWriter((System.IFormatProvider)null);
-                XmlWriterSettings writerSettings = new XmlWriterSettings();
-                writerSettings.CloseOutput = true;      // close the memory stream when done
-                writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
-                _xmlWriter = XmlWriter.Create(_strWriter, writerSettings);
-            }
-
-            int charsToSkip = 0;
-            int cnt = 0;
-            if (dataIndex < _charsRemoved)
-            {
-                throw ADP.NonSeqByteAccess(dataIndex, _charsRemoved, nameof(GetChars));
-            }
-            else if (dataIndex > _charsRemoved)
-            {
-                charsToSkip = (int)(dataIndex - _charsRemoved);
-            }
-
-            // If buffer parameter is null, we have to return -1 since there is no way for us to know the
-            // total size up front without reading and converting the XML.
-            if (buffer == null)
-            {
-                return (long)(-1);
-            }
-
-            StringBuilder strBldr = _strWriter.GetStringBuilder();
-            while (!_xmlReader.EOF)
-            {
-                if (strBldr.Length >= (length + charsToSkip))
-                {
-                    break;
-                }
-                // Can't call _xmlWriter.WriteNode here, since it reads all of the data in before returning the first char.
-                // Do own implementation of WriteNode instead that reads just enough data to return the required number of chars
-                //_xmlWriter.WriteNode(_xmlReader, true);
-                //  _xmlWriter.Flush();
-                WriteXmlElement();
-                if (charsToSkip > 0)
-                {
-                    // Aggressively remove the characters we want to skip to avoid growing StringBuilder size too much
-                    cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
-                    strBldr.Remove(0, cnt);
-                    charsToSkip -= cnt;
-                    _charsRemoved += (long)cnt;
-                }
-            }
-
-            if (charsToSkip > 0)
-            {
-                cnt = strBldr.Length < charsToSkip ? strBldr.Length : charsToSkip;
-                strBldr.Remove(0, cnt);
-                charsToSkip -= cnt;
-                _charsRemoved += (long)cnt;
-            }
-
-            if (strBldr.Length == 0)
-            {
-                return 0;
-            }
-            // At this point charsToSkip must be 0
-            Debug.Assert(charsToSkip == 0);
-
-            cnt = strBldr.Length < length ? strBldr.Length : length;
-            for (int i = 0; i < cnt; i++)
-            {
-                buffer[bufferIndex + i] = strBldr[i];
-            }
-            // Remove the characters we have already returned
-            strBldr.Remove(0, cnt);
-            _charsRemoved += (long)cnt;
-            return (long)cnt;
-        }
-
-        // This method duplicates the work of XmlWriter.WriteNode except that it reads one element at a time
-        // instead of reading the entire node like XmlWriter.
-        private void WriteXmlElement()
-        {
-            if (_xmlReader.EOF)
-                return;
-
-            bool canReadChunk = _xmlReader.CanReadValueChunk;
-            char[] writeNodeBuffer = null;
-
-            // Constants
-            const int WriteNodeBufferSize = 1024;
-
-            _xmlReader.Read();
-            switch (_xmlReader.NodeType)
-            {
-                case XmlNodeType.Element:
-                    _xmlWriter.WriteStartElement(_xmlReader.Prefix, _xmlReader.LocalName, _xmlReader.NamespaceURI);
-                    _xmlWriter.WriteAttributes(_xmlReader, true);
-                    if (_xmlReader.IsEmptyElement)
-                    {
-                        _xmlWriter.WriteEndElement();
-                        break;
-                    }
-                    break;
-                case XmlNodeType.Text:
-                    if (canReadChunk)
-                    {
-                        if (writeNodeBuffer == null)
-                        {
-                            writeNodeBuffer = new char[WriteNodeBufferSize];
-                        }
-                        int read;
-                        while ((read = _xmlReader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
-                        {
-                            _xmlWriter.WriteChars(writeNodeBuffer, 0, read);
-                        }
-                    }
-                    else
-                    {
-                        _xmlWriter.WriteString(_xmlReader.Value);
-                    }
-                    break;
-                case XmlNodeType.Whitespace:
-                case XmlNodeType.SignificantWhitespace:
-                    _xmlWriter.WriteWhitespace(_xmlReader.Value);
-                    break;
-                case XmlNodeType.CDATA:
-                    _xmlWriter.WriteCData(_xmlReader.Value);
-                    break;
-                case XmlNodeType.EntityReference:
-                    _xmlWriter.WriteEntityRef(_xmlReader.Name);
-                    break;
-                case XmlNodeType.XmlDeclaration:
-                case XmlNodeType.ProcessingInstruction:
-                    _xmlWriter.WriteProcessingInstruction(_xmlReader.Name, _xmlReader.Value);
-                    break;
-                case XmlNodeType.DocumentType:
-                    _xmlWriter.WriteDocType(_xmlReader.Name, _xmlReader.GetAttribute("PUBLIC"), _xmlReader.GetAttribute("SYSTEM"), _xmlReader.Value);
-                    break;
-                case XmlNodeType.Comment:
-                    _xmlWriter.WriteComment(_xmlReader.Value);
-                    break;
-                case XmlNodeType.EndElement:
-                    _xmlWriter.WriteFullEndElement();
-                    break;
-            }
-            _xmlWriter.Flush();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlTransaction.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlTransaction.cs
deleted file mode 100644 (file)
index cc30fbc..0000000
+++ /dev/null
@@ -1,309 +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.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    public sealed class SqlTransaction : DbTransaction
-    {
-        private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
-
-        internal readonly IsolationLevel _isolationLevel = IsolationLevel.ReadCommitted;
-
-        private SqlInternalTransaction _internalTransaction;
-        private readonly SqlConnection _connection;
-
-        private bool _isFromAPI;
-
-        internal SqlTransaction(SqlInternalConnection internalConnection, SqlConnection con,
-                                IsolationLevel iso, SqlInternalTransaction internalTransaction)
-        {
-            _isolationLevel = iso;
-            _connection = con;
-
-            if (internalTransaction == null)
-            {
-                _internalTransaction = new SqlInternalTransaction(internalConnection, TransactionType.LocalFromAPI, this);
-            }
-            else
-            {
-                Debug.Assert(internalConnection.CurrentTransaction == internalTransaction, "Unexpected Parser.CurrentTransaction state!");
-                _internalTransaction = internalTransaction;
-                _internalTransaction.InitParent(this);
-            }
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // PROPERTIES
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        public new SqlConnection Connection
-        {
-            get
-            {
-                if (IsZombied)
-                {
-                    return null;
-                }
-                else
-                {
-                    return _connection;
-                }
-            }
-        }
-
-        protected override DbConnection DbConnection
-        {
-            get
-            {
-                return Connection;
-            }
-        }
-
-        internal SqlInternalTransaction InternalTransaction
-        {
-            get
-            {
-                return _internalTransaction;
-            }
-        }
-
-        public override IsolationLevel IsolationLevel
-        {
-            get
-            {
-                ZombieCheck();
-                return _isolationLevel;
-            }
-        }
-
-        private bool IsYukonPartialZombie
-        {
-            get
-            {
-                return (null != _internalTransaction && _internalTransaction.IsCompleted);
-            }
-        }
-
-        internal bool IsZombied
-        {
-            get
-            {
-                return (null == _internalTransaction || _internalTransaction.IsCompleted);
-            }
-        }
-
-
-        internal SqlStatistics Statistics
-        {
-            get
-            {
-                if (null != _connection)
-                {
-                    if (_connection.StatisticsEnabled)
-                    {
-                        return _connection.Statistics;
-                    }
-                }
-                return null;
-            }
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // PUBLIC METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        public override void Commit()
-        {
-            Exception e = null;
-            Guid operationId = s_diagnosticListener.WriteTransactionCommitBefore(_isolationLevel, _connection);
-
-            ZombieCheck();
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                _isFromAPI = true;
-
-                _internalTransaction.Commit();
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                if (e != null)
-                {
-                    s_diagnosticListener.WriteTransactionCommitError(operationId, _isolationLevel, _connection, e);
-                }
-                else
-                {
-                    s_diagnosticListener.WriteTransactionCommitAfter(operationId, _isolationLevel, _connection);
-                }
-
-                _isFromAPI = false;
-
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        protected override void Dispose(bool disposing)
-        {
-            if (disposing)
-            {
-                if (!IsZombied && !IsYukonPartialZombie)
-                {
-                    _internalTransaction.Dispose();
-                }
-            }
-            base.Dispose(disposing);
-        }
-
-        public override void Rollback()
-        {
-            Exception e = null;
-            Guid operationId = s_diagnosticListener.WriteTransactionRollbackBefore(_isolationLevel, _connection, null);
-
-            if (IsYukonPartialZombie)
-            {
-                // Put something in the trace in case a customer has an issue
-                _internalTransaction = null; // yukon zombification
-            }
-            else
-            {
-                ZombieCheck();
-
-                SqlStatistics statistics = null;
-                try
-                {
-                    statistics = SqlStatistics.StartTimer(Statistics);
-
-                    _isFromAPI = true;
-
-                    _internalTransaction.Rollback();
-                }
-                catch (Exception ex)
-                {
-                    e = ex;
-                    throw;
-                }
-                finally
-                {
-                    if (e != null)
-                    {
-                        s_diagnosticListener.WriteTransactionRollbackError(operationId, _isolationLevel, _connection, null, e);
-                    }
-                    else
-                    {
-                        s_diagnosticListener.WriteTransactionRollbackAfter(operationId, _isolationLevel, _connection, null);
-                    }
-                    _isFromAPI = false;
-
-                    SqlStatistics.StopTimer(statistics);
-                }
-            }
-        }
-
-        public void Rollback(string transactionName)
-        {
-            Exception e = null;
-            Guid operationId = s_diagnosticListener.WriteTransactionRollbackBefore(_isolationLevel, _connection, transactionName);
-
-            ZombieCheck();
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                _isFromAPI = true;
-
-                _internalTransaction.Rollback(transactionName);
-            }
-            catch (Exception ex)
-            {
-                e = ex;
-                throw;
-            }
-            finally
-            {
-                if (e != null)
-                {
-                    s_diagnosticListener.WriteTransactionRollbackError(operationId, _isolationLevel, _connection, transactionName, e);
-                }
-                else
-                {
-                    s_diagnosticListener.WriteTransactionRollbackAfter(operationId, _isolationLevel, _connection, transactionName);
-                }
-
-                _isFromAPI = false;
-
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        public void Save(string savePointName)
-        {
-            ZombieCheck();
-
-            SqlStatistics statistics = null;
-            try
-            {
-                statistics = SqlStatistics.StartTimer(Statistics);
-
-                _internalTransaction.Save(savePointName);
-            }
-            finally
-            {
-                SqlStatistics.StopTimer(statistics);
-            }
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // INTERNAL METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        internal void Zombie()
-        {
-            // For Yukon, we have to defer "zombification" until
-            //                 we get past the users' next rollback, else we'll
-            //                 throw an exception there that is a breaking change.
-            //                 Of course, if the connection is already closed,
-            //                 then we're free to zombify...
-            SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection);
-            if (internalConnection == null || _isFromAPI)
-            {
-                _internalTransaction = null; // pre-yukon zombification
-            }
-        }
-
-        ////////////////////////////////////////////////////////////////////////////////////////
-        // PRIVATE METHODS
-        ////////////////////////////////////////////////////////////////////////////////////////
-
-        private void ZombieCheck()
-        {
-            // If this transaction has been completed, throw exception since it is unusable.
-            if (IsZombied)
-            {
-                if (IsYukonPartialZombie)
-                {
-                    _internalTransaction = null; // yukon zombification
-                }
-
-                throw ADP.TransactionZombied(this);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlUdtInfo.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlUdtInfo.cs
deleted file mode 100644 (file)
index 1567c28..0000000
+++ /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.Collections.Generic;
-using Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    internal class SqlUdtInfo
-    {
-        internal readonly Format SerializationFormat;
-        internal readonly bool IsByteOrdered;
-        internal readonly bool IsFixedLength;
-        internal readonly int MaxByteSize;
-        internal readonly string Name;
-        internal readonly string ValidationMethodName;
-
-        private SqlUdtInfo(SqlUserDefinedTypeAttribute attr)
-        {
-            SerializationFormat = attr.Format;
-            IsByteOrdered = attr.IsByteOrdered;
-            IsFixedLength = attr.IsFixedLength;
-            MaxByteSize = attr.MaxByteSize;
-            Name = attr.Name;
-            ValidationMethodName = attr.ValidationMethodName;
-        }
-
-        internal static SqlUdtInfo GetFromType(Type target)
-        {
-            SqlUdtInfo udtAttr = TryGetFromType(target);
-            if (udtAttr == null)
-            {
-                throw InvalidUdtException.Create(target, SR.SqlUdtReason_NoUdtAttribute);
-            }
-            return udtAttr;
-        }
-
-        // Improve UDT serialization performance by caching the resulting UDT type information using type-safe dictionary.
-        // Use a per-thread cache, so we do not need to synchronize access to it
-        [ThreadStatic]
-        private static Dictionary<Type, SqlUdtInfo> s_types2UdtInfo;
-
-        internal static SqlUdtInfo TryGetFromType(Type target)
-        {
-            if (s_types2UdtInfo == null)
-                s_types2UdtInfo = new Dictionary<Type, SqlUdtInfo>();
-
-            SqlUdtInfo udtAttr = null;
-            if (!s_types2UdtInfo.TryGetValue(target, out udtAttr))
-            {
-                // query SqlUserDefinedTypeAttribute first time and cache the result
-                object[] attr = target.GetCustomAttributes(typeof(SqlUserDefinedTypeAttribute), false);
-                if (attr != null && attr.Length == 1)
-                {
-                    udtAttr = new SqlUdtInfo((SqlUserDefinedTypeAttribute)attr[0]);
-                }
-                s_types2UdtInfo.Add(target, udtAttr);
-            }
-            return udtAttr;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs
deleted file mode 100644 (file)
index 5ceecca..0000000
+++ /dev/null
@@ -1,1280 +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.Data.Common;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.CompilerServices;
-using System.Runtime.ExceptionServices;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Reflection;
-using System.Transactions;
-
-namespace System.Data.SqlClient
-{
-    internal static class AsyncHelper
-    {
-        internal static Task CreateContinuationTask(Task task, Action onSuccess, Action<Exception> onFailure = null)
-        {
-            if (task == null)
-            {
-                onSuccess();
-                return null;
-            }
-            else
-            {
-                TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
-                ContinueTaskWithState(task, completion,
-                    state: Tuple.Create(onSuccess, onFailure, completion),
-                    onSuccess: (state) =>
-                    {
-                        var parameters = (Tuple<Action, Action<Exception>, TaskCompletionSource<object>>)state;
-                        Action success = parameters.Item1;
-                        TaskCompletionSource<object> taskCompletionSource = parameters.Item3;
-                        success();
-                        taskCompletionSource.SetResult(null);
-                    },
-                    onFailure: (exception, state) =>
-                    {
-                        var parameters = (Tuple<Action, Action<Exception>, TaskCompletionSource<object>>)state;
-                        Action<Exception> failure = parameters.Item2;
-                        failure?.Invoke(exception);
-                    }
-                );
-                return completion.Task;
-            }
-        }
-
-        internal static Task CreateContinuationTaskWithState(Task task, object state, Action<object> onSuccess, Action<Exception, object> onFailure = null)
-        {
-            if (task == null)
-            {
-                onSuccess(state);
-                return null;
-            }
-            else
-            {
-                var completion = new TaskCompletionSource<object>();
-                ContinueTaskWithState(task, completion, state,
-                    onSuccess: (continueState) =>
-                    {
-                        onSuccess(continueState);
-                        completion.SetResult(null);
-                    },
-                    onFailure: onFailure
-                );
-                return completion.Task;
-            }
-        }
-
-        internal static Task CreateContinuationTask<T1, T2>(Task task, Action<T1, T2> onSuccess, T1 arg1, T2 arg2, Action<Exception> onFailure = null)
-        {
-            return CreateContinuationTask(task, () => onSuccess(arg1, arg2), onFailure);
-        }
-
-
-        internal static void ContinueTask(Task task,
-                TaskCompletionSource<object> completion,
-                Action onSuccess,
-                Action<Exception> onFailure = null,
-                Action onCancellation = null,
-                Func<Exception, Exception> exceptionConverter = null
-            )
-        {
-            task.ContinueWith(
-                tsk =>
-                {
-                    if (tsk.Exception != null)
-                    {
-                        Exception exc = tsk.Exception.InnerException;
-                        if (exceptionConverter != null)
-                        {
-                            exc = exceptionConverter(exc);
-                        }
-                        try
-                        {
-                            onFailure?.Invoke(exc);
-                        }
-                        finally
-                        {
-                            completion.TrySetException(exc);
-                        }
-                    }
-                    else if (tsk.IsCanceled)
-                    {
-                        try
-                        {
-                            onCancellation?.Invoke();
-                        }
-                        finally
-                        {
-                            completion.TrySetCanceled();
-                        }
-                    }
-                    else
-                    {
-                        try
-                        {
-                            onSuccess();
-                        }
-                        catch (Exception e)
-                        {
-                            completion.SetException(e);
-                        }
-                    }
-                }, TaskScheduler.Default
-            );
-        }
-
-        // the same logic as ContinueTask but with an added state parameter to allow the caller to avoid the use of a closure
-        // the parameter allocation cannot be avoided here and using closure names is clearer than Tuple numbered properties
-        internal static void ContinueTaskWithState(Task task,
-            TaskCompletionSource<object> completion,
-            object state,
-            Action<object> onSuccess,
-            Action<Exception, object> onFailure = null,
-            Action<object> onCancellation = null,
-            Func<Exception, Exception> exceptionConverter = null
-        )
-        {
-            task.ContinueWith(
-                tsk =>
-                {
-                    if (tsk.Exception != null)
-                    {
-                        Exception exc = tsk.Exception.InnerException;
-                        if (exceptionConverter != null)
-                        {
-                            exc = exceptionConverter(exc);
-                        }
-                        try
-                        {
-                            onFailure?.Invoke(exc, state);
-                        }
-                        finally
-                        {
-                            completion.TrySetException(exc);
-                        }
-                    }
-                    else if (tsk.IsCanceled)
-                    {
-                        try
-                        {
-                            onCancellation?.Invoke(state);
-                        }
-                        finally
-                        {
-                            completion.TrySetCanceled();
-                        }
-                    }
-                    else
-                    {
-                        try
-                        {
-                            onSuccess(state);
-                        }
-                        catch (Exception e)
-                        {
-                            completion.SetException(e);
-                        }
-                    }
-                }, TaskScheduler.Default
-            );
-        }
-
-        internal static void WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions = true)
-        {
-            try
-            {
-                task.Wait(timeout > 0 ? (1000 * timeout) : Timeout.Infinite);
-            }
-            catch (AggregateException ae)
-            {
-                if (rethrowExceptions)
-                {
-                    Debug.Assert(ae.InnerExceptions.Count == 1, "There is more than one exception in AggregateException");
-                    ExceptionDispatchInfo.Capture(ae.InnerException).Throw();
-                }
-            }
-            if (!task.IsCompleted)
-            {
-                if (onTimeout != null)
-                {
-                    onTimeout();
-                }
-            }
-        }
-
-        internal static void SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken)
-        {
-            if (timeout > 0)
-            {
-                Task.Delay(timeout * 1000, ctoken).ContinueWith((tsk) =>
-                {
-                    if (!tsk.IsCanceled && !completion.Task.IsCompleted)
-                    {
-                        completion.TrySetException(exc());
-                    }
-                }, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
-            }
-        }
-    }
-
-
-    internal static class SQL
-    {
-        // The class SQL defines the exceptions that are specific to the SQL Adapter.
-        // The class contains functions that take the proper informational variables and then construct
-        // the appropriate exception with an error string obtained from the resource Framework.txt.
-        // The exception is then returned to the caller, so that the caller may then throw from its
-        // location so that the catcher of the exception will have the appropriate call stack.
-        // This class is used so that there will be compile time checking of error
-        // messages.  The resource Framework.txt will ensure proper string text based on the appropriate
-        // locale.
-
-        //
-        // SQL specific exceptions
-        //
-
-        //
-        // SQL.Connection
-        //
-        internal static Exception CannotGetDTCAddress()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_CannotGetDTCAddress));
-        }
-
-        internal static Exception InvalidInternalPacketSize(string str)
-        {
-            return ADP.ArgumentOutOfRange(str);
-        }
-        internal static Exception InvalidPacketSize()
-        {
-            return ADP.ArgumentOutOfRange(SR.GetString(SR.SQL_InvalidTDSPacketSize));
-        }
-        internal static Exception InvalidPacketSizeValue()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_InvalidPacketSizeValue));
-        }
-        internal static Exception InvalidSSPIPacketSize()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_InvalidSSPIPacketSize));
-        }
-        internal static Exception NullEmptyTransactionName()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_NullEmptyTransactionName));
-        }
-        internal static Exception UserInstanceFailoverNotCompatible()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_UserInstanceFailoverNotCompatible));
-        }
-        internal static Exception ParsingErrorLibraryType(ParsingErrorState state, int libraryType)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorAuthLibraryType, ((int)state).ToString(CultureInfo.InvariantCulture), libraryType));
-        }
-        internal static Exception InvalidSQLServerVersionUnknown()
-        {
-            return ADP.DataAdapter(SR.GetString(SR.SQL_InvalidSQLServerVersionUnknown));
-        }
-        internal static Exception SynchronousCallMayNotPend()
-        {
-            return new Exception(SR.GetString(SR.Sql_InternalError));
-        }
-        internal static Exception ConnectionLockedForBcpEvent()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ConnectionLockedForBcpEvent));
-        }
-        internal static Exception InstanceFailure()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_InstanceFailure));
-        }
-        internal static Exception ChangePasswordArgumentMissing(string argumentName)
-        {
-            return ADP.ArgumentNull(SR.GetString(SR.SQL_ChangePasswordArgumentMissing, argumentName));
-        }
-        internal static Exception ChangePasswordConflictsWithSSPI()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_ChangePasswordConflictsWithSSPI));
-        }
-        internal static Exception ChangePasswordRequiresYukon()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ChangePasswordRequiresYukon));
-        }
-        internal static Exception ChangePasswordUseOfUnallowedKey(string key)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ChangePasswordUseOfUnallowedKey, key));
-        }
-
-        //
-        // Global Transactions.
-        //
-        internal static Exception GlobalTransactionsNotEnabled()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.GT_Disabled));
-        }
-        internal static Exception UnknownSysTxIsolationLevel(Transactions.IsolationLevel isolationLevel)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString()));
-        }
-
-
-        internal static Exception InvalidPartnerConfiguration(string server, string database)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidPartnerConfiguration, server, database));
-        }
-        internal static Exception MARSUnspportedOnConnection()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_MarsUnsupportedOnConnection));
-        }
-
-        internal static Exception CannotModifyPropertyAsyncOperationInProgress([CallerMemberName] string property = "")
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_CannotModifyPropertyAsyncOperationInProgress, property));
-        }
-        internal static Exception NonLocalSSEInstance()
-        {
-            return ADP.NotSupported(SR.GetString(SR.SQL_NonLocalSSEInstance));
-        }
-        //
-        // SQL.DataCommand
-        //
-
-        internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value)
-        {
-            return ADP.ArgumentOutOfRange(SR.GetString(SR.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
-        }
-
-        internal static ArgumentOutOfRangeException NotSupportedCommandType(CommandType value)
-        {
-#if DEBUG
-            switch (value)
-            {
-                case CommandType.Text:
-                case CommandType.StoredProcedure:
-                    Debug.Fail("valid CommandType " + value.ToString());
-                    break;
-                case CommandType.TableDirect:
-                    break;
-                default:
-                    Debug.Fail("invalid CommandType " + value.ToString());
-                    break;
-            }
-#endif
-            return NotSupportedEnumerationValue(typeof(CommandType), (int)value);
-        }
-        internal static ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value)
-        {
-#if DEBUG
-            switch (value)
-            {
-                case IsolationLevel.Unspecified:
-                case IsolationLevel.ReadCommitted:
-                case IsolationLevel.ReadUncommitted:
-                case IsolationLevel.RepeatableRead:
-                case IsolationLevel.Serializable:
-                case IsolationLevel.Snapshot:
-                    Debug.Fail("valid IsolationLevel " + value.ToString());
-                    break;
-                case IsolationLevel.Chaos:
-                    break;
-                default:
-                    Debug.Fail("invalid IsolationLevel " + value.ToString());
-                    break;
-            }
-#endif
-            return NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value);
-        }
-
-        internal static Exception OperationCancelled()
-        {
-            Exception exception = ADP.InvalidOperation(SR.GetString(SR.SQL_OperationCancelled));
-            return exception;
-        }
-
-        internal static Exception PendingBeginXXXExists()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_PendingBeginXXXExists));
-        }
-
-        internal static ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param)
-        {
-            return ADP.ArgumentOutOfRange(SR.GetString(SR.SqlDependency_InvalidTimeout), param);
-        }
-
-        internal static Exception NonXmlResult()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_NonXmlResult));
-        }
-
-        //
-        // SQL.DataParameter
-        //
-        internal static Exception InvalidUdt3PartNameFormat()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_InvalidUdt3PartNameFormat));
-        }
-        internal static Exception InvalidParameterTypeNameFormat()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_InvalidParameterTypeNameFormat));
-        }
-        internal static Exception InvalidParameterNameLength(string value)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_InvalidParameterNameLength, value));
-        }
-        internal static Exception PrecisionValueOutOfRange(byte precision)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture)));
-        }
-        internal static Exception ScaleValueOutOfRange(byte scale)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
-        }
-        internal static Exception TimeScaleValueOutOfRange(byte scale)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
-        }
-        internal static Exception InvalidSqlDbType(SqlDbType value)
-        {
-            return ADP.InvalidEnumerationValue(typeof(SqlDbType), (int)value);
-        }
-        internal static Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName)
-        {
-            return ADP.NotSupported(SR.GetString(SR.SqlParameter_UnsupportedTVPOutputParameter,
-                        direction.ToString(), paramName));
-        }
-        internal static Exception DBNullNotSupportedForTVPValues(string paramName)
-        {
-            return ADP.NotSupported(SR.GetString(SR.SqlParameter_DBNullNotSupportedForTVP, paramName));
-        }
-        internal static Exception UnexpectedTypeNameForNonStructParams(string paramName)
-        {
-            return ADP.NotSupported(SR.GetString(SR.SqlParameter_UnexpectedTypeNameForNonStruct, paramName));
-        }
-        internal static Exception ParameterInvalidVariant(string paramName)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ParameterInvalidVariant, paramName));
-        }
-
-        internal static Exception MustSetTypeNameForParam(string paramType, string paramName)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_ParameterTypeNameRequired, paramType, paramName));
-        }
-        internal static Exception NullSchemaTableDataTypeNotSupported(string columnName)
-        {
-            return ADP.Argument(SR.GetString(SR.NullSchemaTableDataTypeNotSupported, columnName));
-        }
-        internal static Exception InvalidSchemaTableOrdinals()
-        {
-            return ADP.Argument(SR.GetString(SR.InvalidSchemaTableOrdinals));
-        }
-        internal static Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber));
-        }
-        internal static Exception EnumeratedRecordFieldCountChanged(int recordNumber)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_EnumeratedRecordFieldCountChanged, recordNumber));
-        }
-
-        //
-        // SQL.SqlDataAdapter
-        //
-
-        //
-        // SQL.TDSParser
-        //
-        internal static Exception InvalidTDSVersion()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidTDSVersion));
-        }
-        internal static Exception ParsingError()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingError));
-        }
-        internal static Exception ParsingError(ParsingErrorState state)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)));
-        }
-        internal static Exception ParsingErrorValue(ParsingErrorState state, int value)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorValue, ((int)state).ToString(CultureInfo.InvariantCulture), value));
-        }
-        internal static Exception ParsingErrorFeatureId(ParsingErrorState state, int featureId)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ParsingErrorFeatureId, ((int)state).ToString(CultureInfo.InvariantCulture), featureId));
-        }
-        internal static Exception MoneyOverflow(string moneyValue)
-        {
-            return ADP.Overflow(SR.GetString(SR.SQL_MoneyOverflow, moneyValue));
-        }
-        internal static Exception SmallDateTimeOverflow(string datetime)
-        {
-            return ADP.Overflow(SR.GetString(SR.SQL_SmallDateTimeOverflow, datetime));
-        }
-        internal static Exception SNIPacketAllocationFailure()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_SNIPacketAllocationFailure));
-        }
-        internal static Exception TimeOverflow(string time)
-        {
-            return ADP.Overflow(SR.GetString(SR.SQL_TimeOverflow, time));
-        }
-
-        //
-        // SQL.SqlDataReader
-        //
-        internal static Exception InvalidRead()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidRead));
-        }
-
-        internal static Exception NonBlobColumn(string columnName)
-        {
-            return ADP.InvalidCast(SR.GetString(SR.SQL_NonBlobColumn, columnName));
-        }
-
-        internal static Exception NonCharColumn(string columnName)
-        {
-            return ADP.InvalidCast(SR.GetString(SR.SQL_NonCharColumn, columnName));
-        }
-
-        internal static Exception StreamNotSupportOnColumnType(string columnName)
-        {
-            return ADP.InvalidCast(SR.GetString(SR.SQL_StreamNotSupportOnColumnType, columnName));
-        }
-
-        internal static Exception TextReaderNotSupportOnColumnType(string columnName)
-        {
-            return ADP.InvalidCast(SR.GetString(SR.SQL_TextReaderNotSupportOnColumnType, columnName));
-        }
-
-        internal static Exception XmlReaderNotSupportOnColumnType(string columnName)
-        {
-            return ADP.InvalidCast(SR.GetString(SR.SQL_XmlReaderNotSupportOnColumnType, columnName));
-        }
-
-        internal static Exception UDTUnexpectedResult(string exceptionText)
-        {
-            return ADP.TypeLoad(SR.GetString(SR.SQLUDT_Unexpected, exceptionText));
-        }
-
-        //
-        // SQL.SqlDependency
-        //
-        internal static Exception SqlCommandHasExistingSqlNotificationRequest()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQLNotify_AlreadyHasCommand));
-        }
-
-        internal static Exception SqlDepDefaultOptionsButNoStart()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DefaultOptionsButNoStart));
-        }
-
-        internal static Exception SqlDependencyDatabaseBrokerDisabled()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DatabaseBrokerDisabled));
-        }
-
-        internal static Exception SqlDependencyEventNoDuplicate()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_EventNoDuplicate));
-        }
-
-        internal static Exception SqlDependencyDuplicateStart()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_DuplicateStart));
-        }
-
-        internal static Exception SqlDependencyIdMismatch()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_IdMismatch));
-        }
-
-        internal static Exception SqlDependencyNoMatchingServerStart()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_NoMatchingServerStart));
-        }
-
-        internal static Exception SqlDependencyNoMatchingServerDatabaseStart()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlDependency_NoMatchingServerDatabaseStart));
-        }
-
-        //
-        // SQL.SqlDelegatedTransaction
-        //
-        internal static TransactionPromotionException PromotionFailed(Exception inner)
-        {
-            TransactionPromotionException e = new TransactionPromotionException(SR.GetString(SR.SqlDelegatedTransaction_PromotionFailed), inner);
-            ADP.TraceExceptionAsReturnValue(e);
-            return e;
-        }
-        //Failure while attempting to promote transaction.
-
-        //
-        // SQL.SqlMetaData
-        //
-        internal static Exception UnexpectedUdtTypeNameForNonUdtParams()
-        {
-            return ADP.Argument(SR.GetString(SR.SQLUDT_UnexpectedUdtTypeName));
-        }
-        internal static Exception MustSetUdtTypeNameForUdtParams()
-        {
-            return ADP.Argument(SR.GetString(SR.SQLUDT_InvalidUdtTypeName));
-        }
-        internal static Exception UDTInvalidSqlType(string typeName)
-        {
-            return ADP.Argument(SR.GetString(SR.SQLUDT_InvalidSqlType, typeName));
-        }
-        internal static Exception InvalidSqlDbTypeForConstructor(SqlDbType type)
-        {
-            return ADP.Argument(SR.GetString(SR.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString()));
-        }
-
-        internal static Exception NameTooLong(string parameterName)
-        {
-            return ADP.Argument(SR.GetString(SR.SqlMetaData_NameTooLong), parameterName);
-        }
-
-        internal static Exception InvalidSortOrder(SortOrder order)
-        {
-            return ADP.InvalidEnumerationValue(typeof(SortOrder), (int)order);
-        }
-
-        internal static Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal));
-        }
-
-        internal static Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName)
-        {
-            return ADP.Argument(SR.GetString(SR.SqlProvider_InvalidDataColumnType, columnName, typeName));
-        }
-        internal static Exception InvalidColumnMaxLength(string columnName, long maxLength)
-        {
-            return ADP.Argument(SR.GetString(SR.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength));
-        }
-        internal static Exception InvalidColumnPrecScale()
-        {
-            return ADP.Argument(SR.GetString(SR.SqlMisc_InvalidPrecScaleMessage));
-        }
-        internal static Exception NotEnoughColumnsInStructuredType()
-        {
-            return ADP.Argument(SR.GetString(SR.SqlProvider_NotEnoughColumnsInStructuredType));
-        }
-        internal static Exception DuplicateSortOrdinal(int sortOrdinal)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_DuplicateSortOrdinal, sortOrdinal));
-        }
-        internal static Exception MissingSortOrdinal(int sortOrdinal)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_MissingSortOrdinal, sortOrdinal));
-        }
-        internal static Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal));
-        }
-        internal static Exception IEnumerableOfSqlDataRecordHasNoRows()
-        {
-            return ADP.Argument(SR.GetString(SR.IEnumerableOfSqlDataRecordHasNoRows));
-        }
-
-
-
-
-        //
-        // SQL.BulkLoad
-        //
-        internal static Exception BulkLoadMappingInaccessible()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMappingInaccessible));
-        }
-        internal static Exception BulkLoadMappingsNamesOrOrdinalsOnly()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMappingsNamesOrOrdinalsOnly));
-        }
-        internal static Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, Exception e)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadCannotConvertValue, sourcetype.Name, metatype.TypeName), e);
-        }
-        internal static Exception BulkLoadNonMatchingColumnMapping()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNonMatchingColumnMapping));
-        }
-        internal static Exception BulkLoadNonMatchingColumnName(string columnName)
-        {
-            return BulkLoadNonMatchingColumnName(columnName, null);
-        }
-        internal static Exception BulkLoadNonMatchingColumnName(string columnName, Exception e)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNonMatchingColumnName, columnName), e);
-        }
-        internal static Exception BulkLoadStringTooLong()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadStringTooLong));
-        }
-        internal static Exception BulkLoadInvalidVariantValue()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidVariantValue));
-        }
-        internal static Exception BulkLoadInvalidTimeout(int timeout)
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture)));
-        }
-        internal static Exception BulkLoadExistingTransaction()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadExistingTransaction));
-        }
-        internal static Exception BulkLoadNoCollation()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNoCollation));
-        }
-        internal static Exception BulkLoadConflictingTransactionOption()
-        {
-            return ADP.Argument(SR.GetString(SR.SQL_BulkLoadConflictingTransactionOption));
-        }
-        internal static Exception BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName));
-        }
-        internal static Exception InvalidOperationInsideEvent()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidOperationInsideEvent));
-        }
-        internal static Exception BulkLoadMissingDestinationTable()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadMissingDestinationTable));
-        }
-        internal static Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadInvalidDestinationTable, tableName), inner);
-        }
-        internal static Exception BulkLoadBulkLoadNotAllowDBNull(string columnName)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadNotAllowDBNull, columnName));
-        }
-        internal static Exception BulkLoadPendingOperation()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BulkLoadPendingOperation));
-        }
-        internal static Exception InvalidTableDerivedPrecisionForTvp(string columnName, byte precision)
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlParameter_InvalidTableDerivedPrecisionForTvp, precision, columnName, System.Data.SqlTypes.SqlDecimal.MaxPrecision));
-        }
-
-        //
-        // transactions.
-        //
-        internal static Exception ConnectionDoomed()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_ConnectionDoomed));
-        }
-
-        internal static Exception OpenResultCountExceeded()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_OpenResultCountExceeded));
-        }
-
-        internal static Exception UnsupportedSysTxForGlobalTransactions()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_UnsupportedSysTxVersion));
-        }
-
-        internal static readonly byte[] AttentionHeader = new byte[] {
-            TdsEnums.MT_ATTN,               // Message Type
-            TdsEnums.ST_EOM,                // Status
-            TdsEnums.HEADER_LEN >> 8,       // length - upper byte
-            TdsEnums.HEADER_LEN & 0xff,     // length - lower byte
-            0,                              // spid
-            0,                              // spid
-            0,                              // packet (out of band)
-            0                               // window
-        };
-
-        //
-        // MultiSubnetFailover
-        //
-
-        /// <summary>
-        /// used to block two scenarios if MultiSubnetFailover is true:
-        /// * server-provided failover partner - raising SqlException in this case
-        /// * connection string with failover partner and MultiSubnetFailover=true - raising argument one in this case with the same message
-        /// </summary>
-        internal static Exception MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection)
-        {
-            string msg = SR.GetString(SR.SQLMSF_FailoverPartnerNotSupported);
-            if (serverProvidedFailoverPartner)
-            {
-                // Replacing InvalidOperation with SQL exception
-                SqlErrorCollection errors = new SqlErrorCollection();
-                errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, msg, "", 0));
-                SqlException exc = SqlException.CreateException(errors, null, internalConnection);
-                exc._doNotReconnect = true; // disable open retry logic on this error
-                return exc;
-            }
-            else
-            {
-                return ADP.Argument(msg);
-            }
-        }
-
-        internal static Exception MultiSubnetFailoverWithMoreThan64IPs()
-        {
-            string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs);
-            return ADP.InvalidOperation(msg);
-        }
-
-        internal static Exception MultiSubnetFailoverWithInstanceSpecified()
-        {
-            string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified);
-            return ADP.Argument(msg);
-        }
-
-        internal static Exception MultiSubnetFailoverWithNonTcpProtocol()
-        {
-            string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol);
-            return ADP.Argument(msg);
-        }
-
-        //
-        // Read-only routing
-        //
-
-        internal static Exception ROR_FailoverNotSupportedConnString()
-        {
-            return ADP.Argument(SR.GetString(SR.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, (SR.GetString(SR.SQLROR_FailoverNotSupported)), "", 0));
-            SqlException exc = SqlException.CreateException(errors, null, internalConnection);
-            exc._doNotReconnect = true;
-            return exc;
-        }
-
-        internal static Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_RecursiveRoutingNotSupported)), "", 0));
-            SqlException exc = SqlException.CreateException(errors, null, internalConnection);
-            exc._doNotReconnect = true;
-            return exc;
-        }
-
-        internal static Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_UnexpectedRoutingInfo)), "", 0));
-            SqlException exc = SqlException.CreateException(errors, null, internalConnection);
-            exc._doNotReconnect = true;
-            return exc;
-        }
-
-        internal static Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_InvalidRoutingInfo)), "", 0));
-            SqlException exc = SqlException.CreateException(errors, null, internalConnection);
-            exc._doNotReconnect = true;
-            return exc;
-        }
-
-        internal static Exception ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (SR.GetString(SR.SQLROR_TimeoutAfterRoutingInfo)), "", 0));
-            SqlException exc = SqlException.CreateException(errors, null, internalConnection);
-            exc._doNotReconnect = true;
-            return exc;
-        }
-
-        //
-        // Connection resiliency
-        //
-        internal static SqlException CR_ReconnectTimeout()
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.Timeout(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
-            SqlException exc = SqlException.CreateException(errors, "");
-            return exc;
-        }
-
-        internal static SqlException CR_ReconnectionCancelled()
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.OperationCancelled(), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "");
-            return exc;
-        }
-
-        internal static Exception CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SR.GetString(SR.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
-            return exc;
-        }
-
-        internal static Exception CR_EncryptionChanged(SqlInternalConnectionTds internalConnection)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_EncryptionChanged), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", internalConnection);
-            return exc;
-        }
-
-        internal static SqlException CR_AllAttemptsFailed(SqlException innerException, Guid connectionId)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SR.GetString(SR.SQLCR_AllAttemptsFailed), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
-            return exc;
-        }
-
-        internal static SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_NoCRAckAtReconnection), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", internalConnection);
-            return exc;
-        }
-
-        internal static SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internalConnection)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_TDSVestionNotPreserved), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", internalConnection);
-            return exc;
-        }
-
-        internal static SqlException CR_UnrecoverableServer(Guid connectionId)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_UnrecoverableServer), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", connectionId);
-            return exc;
-        }
-
-        internal static SqlException CR_UnrecoverableClient(Guid connectionId)
-        {
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQLCR_UnrecoverableClient), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", connectionId);
-            return exc;
-        }
-
-        internal static Exception StreamWriteNotSupported()
-        {
-            return ADP.NotSupported(SR.GetString(SR.SQL_StreamWriteNotSupported));
-        }
-        internal static Exception StreamReadNotSupported()
-        {
-            return ADP.NotSupported(SR.GetString(SR.SQL_StreamReadNotSupported));
-        }
-        internal static Exception StreamSeekNotSupported()
-        {
-            return ADP.NotSupported(SR.GetString(SR.SQL_StreamSeekNotSupported));
-        }
-        internal static System.Data.SqlTypes.SqlNullValueException SqlNullValue()
-        {
-            System.Data.SqlTypes.SqlNullValueException e = new System.Data.SqlTypes.SqlNullValueException();
-            return e;
-        }
-        internal static Exception SubclassMustOverride()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SqlMisc_SubclassMustOverride));
-        }
-
-        // ProjectK\CoreCLR specific errors
-        internal static Exception UnsupportedKeyword(string keyword)
-        {
-            return ADP.NotSupported(SR.GetString(SR.SQL_UnsupportedKeyword, keyword));
-        }
-        internal static Exception NetworkLibraryKeywordNotSupported()
-        {
-            return ADP.NotSupported(SR.GetString(SR.SQL_NetworkLibraryNotSupported));
-        }
-        internal static Exception UnsupportedFeatureAndToken(SqlInternalConnectionTds internalConnection, string token)
-        {
-            var innerException = ADP.NotSupported(SR.GetString(SR.SQL_UnsupportedToken, token));
-
-            SqlErrorCollection errors = new SqlErrorCollection();
-            errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, SR.GetString(SR.SQL_UnsupportedFeature), "", 0));
-            SqlException exc = SqlException.CreateException(errors, "", internalConnection, innerException);
-            return exc;
-        }
-
-        internal static Exception BatchedUpdatesNotAvailableOnContextConnection()
-        {
-            return ADP.InvalidOperation(SR.GetString(SR.SQL_BatchedUpdatesNotAvailableOnContextConnection));
-        }
-
-        /// <summary>
-        /// gets a message for SNI error (sniError must be valid, non-zero error code)
-        /// </summary>
-        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 SR.GetResourceString(errorMessageId, errorMessageId);
-        }
-
-        // Default values for SqlDependency and SqlNotificationRequest
-        internal const int SqlDependencyTimeoutDefault = 0;
-        internal const int SqlDependencyServerTimeout = 5 * 24 * 3600; // 5 days - used to compute default TTL of the dependency
-        internal const string SqlNotificationServiceDefault = "SqlQueryNotificationService";
-        internal const string SqlNotificationStoredProcedureDefault = "SqlQueryNotificationStoredProcedure";
-    }
-
-    internal sealed class SQLMessage
-    {
-        private SQLMessage() { /* prevent utility class from being instantiated*/ }
-
-        // The class SQLMessage defines the error messages that are specific to the SqlDataAdapter
-        // that are caused by a netlib error.  The functions will be called and then return the
-        // appropriate error message from the resource Framework.txt.  The SqlDataAdapter will then
-        // take the error message and then create a SqlError for the message and then place
-        // that into a SqlException that is either thrown to the user or cached for throwing at
-        // a later time.  This class is used so that there will be compile time checking of error
-        // messages.  The resource Framework.txt will ensure proper string text based on the appropriate
-        // locale.
-
-        internal static string CultureIdError()
-        {
-            return SR.GetString(SR.SQL_CultureIdError);
-        }
-        internal static string EncryptionNotSupportedByClient()
-        {
-            return SR.GetString(SR.SQL_EncryptionNotSupportedByClient);
-        }
-        internal static string EncryptionNotSupportedByServer()
-        {
-            return SR.GetString(SR.SQL_EncryptionNotSupportedByServer);
-        }
-        internal static string OperationCancelled()
-        {
-            return SR.GetString(SR.SQL_OperationCancelled);
-        }
-        internal static string SevereError()
-        {
-            return SR.GetString(SR.SQL_SevereError);
-        }
-        internal static string SSPIInitializeError()
-        {
-            return SR.GetString(SR.SQL_SSPIInitializeError);
-        }
-        internal static string SSPIGenerateError()
-        {
-            return SR.GetString(SR.SQL_SSPIGenerateError);
-        }
-        internal static string SqlServerBrowserNotAccessible()
-        {
-            return SR.GetString(SR.SQL_SqlServerBrowserNotAccessible);
-        }
-        internal static string KerberosTicketMissingError()
-        {
-            return SR.GetString(SR.SQL_KerberosTicketMissingError);
-        }
-        internal static string Timeout()
-        {
-            return SR.GetString(SR.SQL_Timeout);
-        }
-        internal static string Timeout_PreLogin_Begin()
-        {
-            return SR.GetString(SR.SQL_Timeout_PreLogin_Begin);
-        }
-        internal static string Timeout_PreLogin_InitializeConnection()
-        {
-            return SR.GetString(SR.SQL_Timeout_PreLogin_InitializeConnection);
-        }
-        internal static string Timeout_PreLogin_SendHandshake()
-        {
-            return SR.GetString(SR.SQL_Timeout_PreLogin_SendHandshake);
-        }
-        internal static string Timeout_PreLogin_ConsumeHandshake()
-        {
-            return SR.GetString(SR.SQL_Timeout_PreLogin_ConsumeHandshake);
-        }
-        internal static string Timeout_Login_Begin()
-        {
-            return SR.GetString(SR.SQL_Timeout_Login_Begin);
-        }
-        internal static string Timeout_Login_ProcessConnectionAuth()
-        {
-            return SR.GetString(SR.SQL_Timeout_Login_ProcessConnectionAuth);
-        }
-        internal static string Timeout_PostLogin()
-        {
-            return SR.GetString(SR.SQL_Timeout_PostLogin);
-        }
-        internal static string Timeout_FailoverInfo()
-        {
-            return SR.GetString(SR.SQL_Timeout_FailoverInfo);
-        }
-        internal static string Timeout_RoutingDestination()
-        {
-            return SR.GetString(SR.SQL_Timeout_RoutingDestinationInfo);
-        }
-        internal static string Duration_PreLogin_Begin(long PreLoginBeginDuration)
-        {
-            return SR.GetString(SR.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration);
-        }
-        internal static string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration)
-        {
-            return SR.GetString(SR.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration);
-        }
-        internal static string Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration)
-        {
-            return SR.GetString(SR.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration);
-        }
-        internal static string Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration)
-        {
-            return SR.GetString(SR.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration);
-        }
-        internal static string Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration)
-        {
-            return SR.GetString(SR.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration);
-        }
-        internal static string UserInstanceFailure()
-        {
-            return SR.GetString(SR.SQL_UserInstanceFailure);
-        }
-        internal static string PreloginError()
-        {
-            return SR.GetString(SR.Snix_PreLogin);
-        }
-        internal static string ExClientConnectionId()
-        {
-            return SR.GetString(SR.SQL_ExClientConnectionId);
-        }
-        internal static string ExErrorNumberStateClass()
-        {
-            return SR.GetString(SR.SQL_ExErrorNumberStateClass);
-        }
-        internal static string ExOriginalClientConnectionId()
-        {
-            return SR.GetString(SR.SQL_ExOriginalClientConnectionId);
-        }
-        internal static string ExRoutingDestination()
-        {
-            return SR.GetString(SR.SQL_ExRoutingDestination);
-        }
-    }
-
-    /// <summary>
-    /// This class holds helper methods to escape Microsoft SQL Server identifiers, such as table, schema, database or other names
-    /// </summary>
-    internal static class SqlServerEscapeHelper
-    {
-        /// <summary>
-        /// Escapes the identifier with square brackets. The input has to be in unescaped form, like the parts received from MultipartIdentifier.ParseMultipartIdentifier.
-        /// </summary>
-        /// <param name="name">name of the identifier, in unescaped form</param>
-        /// <returns>escapes the name with [], also escapes the last close bracket with double-bracket</returns>
-        internal static string EscapeIdentifier(string name)
-        {
-            Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed");
-            return "[" + name.Replace("]", "]]") + "]";
-        }
-
-        /// <summary>
-        /// Same as above EscapeIdentifier, except that output is written into StringBuilder
-        /// </summary>
-        internal static void EscapeIdentifier(StringBuilder builder, string name)
-        {
-            Debug.Assert(builder != null, "builder cannot be null");
-            Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed");
-
-            builder.Append("[");
-            builder.Append(name.Replace("]", "]]"));
-            builder.Append("]");
-        }
-
-        /// <summary>
-        ///  Escape a string to be used inside TSQL literal, such as N'somename' or 'somename'
-        /// </summary>
-        internal static string EscapeStringAsLiteral(string input)
-        {
-            Debug.Assert(input != null, "input string cannot be null");
-            return input.Replace("'", "''");
-        }
-
-        /// <summary>
-        /// Escape a string as a TSQL literal, wrapping it around with single quotes.
-        /// Use this method to escape input strings to prevent SQL injection
-        /// and to get correct behavior for embedded quotes.
-        /// </summary>
-        /// <param name="input">unescaped string</param>
-        /// <returns>escaped and quoted literal string</returns>
-        internal static string MakeStringLiteral(string input)
-        {
-            if (string.IsNullOrEmpty(input))
-            {
-                return "''";
-            }
-            else
-            {
-                return "'" + EscapeStringAsLiteral(input) + "'";
-            }
-        }
-    }
-
-    /// <summary>
-    /// This class holds methods invoked on System.Transactions through reflection for Global Transactions
-    /// </summary>
-    internal static class SysTxForGlobalTransactions
-    {
-        private static readonly Lazy<MethodInfo> _enlistPromotableSinglePhase = new Lazy<MethodInfo>(() =>
-            typeof(Transaction).GetMethod("EnlistPromotableSinglePhase", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) }));
-
-        private static readonly Lazy<MethodInfo> _setDistributedTransactionIdentifier = new Lazy<MethodInfo>(() =>
-            typeof(Transaction).GetMethod("SetDistributedTransactionIdentifier", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) }));
-
-        private static readonly Lazy<MethodInfo> _getPromotedToken = new Lazy<MethodInfo>(() =>
-            typeof(Transaction).GetMethod("GetPromotedToken"));
-
-        /// <summary>
-        /// Enlists the given IPromotableSinglePhaseNotification and Non-MSDTC Promoter type into a transaction
-        /// </summary>
-        /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
-        public static MethodInfo EnlistPromotableSinglePhase
-        {
-            get
-            {
-                return _enlistPromotableSinglePhase.Value;
-            }
-        }
-
-        /// <summary>
-        /// Sets the given DistributedTransactionIdentifier for a Transaction instance.
-        /// Needs to be invoked when using a Non-MSDTC Promoter type
-        /// </summary>
-        /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
-        public static MethodInfo SetDistributedTransactionIdentifier
-        {
-            get
-            {
-                return _setDistributedTransactionIdentifier.Value;
-            }
-        }
-
-        /// <summary>
-        /// Gets the Promoted Token for a Transaction
-        /// </summary>
-        /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
-        public static MethodInfo GetPromotedToken
-        {
-            get
-            {
-                return _getPromotedToken.Value;
-            }
-        }
-    }
-}//namespace
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs
deleted file mode 100644 (file)
index 5fed20c..0000000
+++ /dev/null
@@ -1,973 +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;
-
-namespace System.Data.SqlClient
-{
-    /// <devdoc> Class of variables for the Tds connection.
-    /// </devdoc>
-    internal static class TdsEnums
-    {
-        // internal tdsparser constants
-
-
-        public const string SQL_PROVIDER_NAME = Common.DbConnectionStringDefaults.ApplicationName;
-
-        public static readonly decimal SQL_SMALL_MONEY_MIN = new decimal(-214748.3648);
-        public static readonly decimal SQL_SMALL_MONEY_MAX = new decimal(214748.3647);
-
-
-        // HACK!!!
-        // Constant for SqlDbType.SmallVarBinary... store internal variable here instead of on
-        // SqlDbType so that it is not surfaced to the user!!!  Related to dtc and the fact that
-        // the TransactionManager TDS stream is the only token left that uses VarBinarys instead of
-        // BigVarBinarys.
-        public const SqlDbType SmallVarBinary = (SqlDbType)(SqlDbType.Variant) + 1;
-
-        // network protocol string constants
-        public const string TCP = "tcp";
-        public const string NP = "np";
-        public const string RPC = "rpc";
-        public const string BV = "bv";
-        public const string ADSP = "adsp";
-        public const string SPX = "spx";
-        public const string VIA = "via";
-        public const string LPC = "lpc";
-        public const string ADMIN = "admin";
-
-        // network function string constants
-        public const string INIT_SSPI_PACKAGE = "InitSSPIPackage";
-        public const string INIT_SESSION = "InitSession";
-        public const string CONNECTION_GET_SVR_USER = "ConnectionGetSvrUser";
-        public const string GEN_CLIENT_CONTEXT = "GenClientContext";
-
-        // tdsparser packet handling constants
-        public const byte SOFTFLUSH = 0;
-        public const byte HARDFLUSH = 1;
-        public const byte IGNORE = 2;
-
-        // header constants
-        public const int HEADER_LEN = 8;
-        public const int HEADER_LEN_FIELD_OFFSET = 2;
-        public const int YUKON_HEADER_LEN = 12; //Yukon headers also include a MARS session id
-        public const int MARS_ID_OFFSET = 8;
-        public const int HEADERTYPE_QNOTIFICATION = 1;
-        public const int HEADERTYPE_MARS = 2;
-        public const int HEADERTYPE_TRACE = 3;
-
-        // other various constants
-        public const int SUCCEED = 1;
-        public const int FAIL = 0;
-        public const short TYPE_SIZE_LIMIT = 8000;
-        public const int MIN_PACKET_SIZE = 512;
-        // Login packet can be no greater than 4k until server sends us env-change
-        // increasing packet size.
-        public const int DEFAULT_LOGIN_PACKET_SIZE = 4096;
-        public const int MAX_PRELOGIN_PAYLOAD_LENGTH = 1024;
-        public const int MAX_PACKET_SIZE = 32768;
-        public const int MAX_SERVER_USER_NAME = 256;  // obtained from luxor
-
-        // Severity  0 - 10 indicates informational (non-error) messages
-        // Severity 11 - 16 indicates errors that can be corrected by user (syntax errors, etc...)
-        // Severity 17 - 19 indicates failure due to insufficient resources in the server
-        //      (max locks exceeded, not enough memory, other internal server limits reached, etc..)
-        // Severity 20 - 25 Severe problems with the server, connection terminated.
-        public const byte MIN_ERROR_CLASS = 11;   // webdata 100667: This should actually be 11
-        public const byte MAX_USER_CORRECTABLE_ERROR_CLASS = 16;
-        public const byte FATAL_ERROR_CLASS = 20;
-
-        //    Message types
-        public const byte MT_SQL = 1;    // SQL command batch
-        public const byte MT_LOGIN = 2;    // Login message for pre-Sphinx (before version 7.0)
-        public const byte MT_RPC = 3;    // Remote procedure call
-        public const byte MT_TOKENS = 4;    // Table response data stream
-        public const byte MT_BINARY = 5;    // Unformatted binary response data (UNUSED)
-        public const byte MT_ATTN = 6;    // Attention (break) signal
-        public const byte MT_BULK = 7;    // Bulk load data
-        public const byte MT_OPEN = 8;    // Set up subchannel   (UNUSED)
-        public const byte MT_CLOSE = 9;    // Close subchannel   (UNUSED)
-        public const byte MT_ERROR = 10;   // Protocol error detected
-        public const byte MT_ACK = 11;   // Protocol acknowledgement   (UNUSED)
-        public const byte MT_ECHO = 12;   // Echo data  (UNUSED)
-        public const byte MT_LOGOUT = 13;   // Logout message (UNUSED)
-        public const byte MT_TRANS = 14;   // Transaction Manager Interface
-        public const byte MT_OLEDB = 15;   // ? (UNUSED)
-        public const byte MT_LOGIN7 = 16;   // Login message for Sphinx (version 7) or later
-        public const byte MT_SSPI = 17;   // SSPI message
-        public const byte MT_PRELOGIN = 18;   // Pre-login handshake
-
-        // Message status bits
-        public const byte ST_EOM = 0x1; // Packet is end-of-message
-        public const byte ST_AACK = 0x2; // Packet acknowledges attention (server to client)
-        public const byte ST_IGNORE = 0x2; // Ignore this event (client to server)
-        public const byte ST_BATCH = 0x4; // Message is part of a batch.
-        public const byte ST_RESET_CONNECTION = 0x8; // Exec sp_reset_connection prior to processing message
-        public const byte ST_RESET_CONNECTION_PRESERVE_TRANSACTION = 0x10;  // reset prior to processing, with preserving local tx
-
-        // TDS control tokens
-        public const byte SQLCOLFMT = 0xa1;
-        public const byte SQLPROCID = 0x7c;
-        public const byte SQLCOLNAME = 0xa0;
-        public const byte SQLTABNAME = 0xa4;
-        public const byte SQLCOLINFO = 0xa5;
-        public const byte SQLALTNAME = 0xa7;
-        public const byte SQLALTFMT = 0xa8;
-        public const byte SQLERROR = 0xaa;
-        public const byte SQLINFO = 0xab;
-        public const byte SQLRETURNVALUE = 0xac;
-        public const byte SQLRETURNSTATUS = 0x79;
-        public const byte SQLRETURNTOK = 0xdb;
-        public const byte SQLALTCONTROL = 0xaf;
-        public const byte SQLROW = 0xd1;
-        public const byte SQLNBCROW = 0xd2;    // same as ROW with null-bit-compression support
-        public const byte SQLALTROW = 0xd3;
-        public const byte SQLDONE = 0xfd;
-        public const byte SQLDONEPROC = 0xfe;
-        public const byte SQLDONEINPROC = 0xff;
-        public const byte SQLOFFSET = 0x78;
-        public const byte SQLORDER = 0xa9;
-        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 SQLENVCHANGE = 0xe3;    // Environment change notification
-        public const byte SQLSECLEVEL = 0xed;    // Security level token ???
-        public const byte SQLROWCRC = 0x39;    // ROWCRC datastream???
-        public const byte SQLCOLMETADATA = 0x81;    // Column metadata including name
-        public const byte SQLALTMETADATA = 0x88;    // Alt column metadata including name
-        public const byte SQLSSPI = 0xed;    // SSPI data
-
-        // Environment change notification streams
-        // TYPE on TDS ENVCHANGE token stream (from sql\ntdbms\include\odsapi.h)
-        //
-        public const byte ENV_DATABASE = 1;  // Database changed
-        public const byte ENV_LANG = 2;  // Language changed
-        public const byte ENV_CHARSET = 3;  // Character set changed
-        public const byte ENV_PACKETSIZE = 4;  // Packet size changed
-        public const byte ENV_LOCALEID = 5;  // Unicode data sorting locale id
-        public const byte ENV_COMPFLAGS = 6;  // Unicode data sorting comparison flags
-        public const byte ENV_COLLATION = 7;  // SQL Collation
-        // The following are environment change tokens valid for Yukon or later.
-        public const byte ENV_BEGINTRAN = 8;  // Transaction began
-        public const byte ENV_COMMITTRAN = 9;  // Transaction committed
-        public const byte ENV_ROLLBACKTRAN = 10; // Transaction rolled back
-        public const byte ENV_ENLISTDTC = 11; // Enlisted in Distributed Transaction
-        public const byte ENV_DEFECTDTC = 12; // Defected from Distributed Transaction
-        public const byte ENV_LOGSHIPNODE = 13; // Realtime Log shipping primary node
-        public const byte ENV_PROMOTETRANSACTION = 15; // Promote Transaction
-        public const byte ENV_TRANSACTIONMANAGERADDRESS = 16; // Transaction Manager Address
-        public const byte ENV_TRANSACTIONENDED = 17; // Transaction Ended
-        public const byte ENV_SPRESETCONNECTIONACK = 18; // SP_Reset_Connection ack
-        public const byte ENV_USERINSTANCE = 19; // User Instance
-        public const byte ENV_ROUTING = 20; // Routing (ROR) information
-
-        public enum EnvChangeType : byte
-        {
-            ENVCHANGE_DATABASE = ENV_DATABASE,
-            ENVCHANGE_LANG = ENV_LANG,
-            ENVCHANGE_CHARSET = ENV_CHARSET,
-            ENVCHANGE_PACKETSIZE = ENV_PACKETSIZE,
-            ENVCHANGE_LOCALEID = ENV_LOCALEID,
-            ENVCHANGE_COMPFLAGS = ENV_COMPFLAGS,
-            ENVCHANGE_COLLATION = ENV_COLLATION,
-            ENVCHANGE_BEGINTRAN = ENV_BEGINTRAN,
-            ENVCHANGE_COMMITTRAN = ENV_COMMITTRAN,
-            ENVCHANGE_ROLLBACKTRAN = ENV_ROLLBACKTRAN,
-            ENVCHANGE_ENLISTDTC = ENV_ENLISTDTC,
-            ENVCHANGE_DEFECTDTC = ENV_DEFECTDTC,
-            ENVCHANGE_LOGSHIPNODE = ENV_LOGSHIPNODE,
-            ENVCHANGE_PROMOTETRANSACTION = ENV_PROMOTETRANSACTION,
-            ENVCHANGE_TRANSACTIONMANAGERADDRESS = ENV_TRANSACTIONMANAGERADDRESS,
-            ENVCHANGE_TRANSACTIONENDED = ENV_TRANSACTIONENDED,
-            ENVCHANGE_SPRESETCONNECTIONACK = ENV_SPRESETCONNECTIONACK,
-            ENVCHANGE_USERINSTANCE = ENV_USERINSTANCE,
-            ENVCHANGE_ROUTING = ENV_ROUTING
-        }
-
-        // done status stream bit masks
-        public const int DONE_MORE = 0x0001; // more command results coming
-        public const int DONE_ERROR = 0x0002; // error in command batch
-        public const int DONE_INXACT = 0x0004; // transaction in progress
-        public const int DONE_PROC = 0x0008; // done from stored proc
-        public const int DONE_COUNT = 0x0010; // count in done info
-        public const int DONE_ATTN = 0x0020; // oob ack
-        public const int DONE_INPROC = 0x0040; // like DONE_PROC except proc had error
-        public const int DONE_RPCINBATCH = 0x0080; // Done from RPC in batch
-        public const int DONE_SRVERROR = 0x0100; // Severe error in which resultset should be discarded
-        public const int DONE_FMTSENT = 0x8000; // fmt message sent, done_inproc req'd
-
-        // Feature Extension
-        public const byte FEATUREEXT_TERMINATOR = 0xFF;
-        public const byte FEATUREEXT_SRECOVERY = 0x01;
-        public const byte FEATUREEXT_FEDAUTH = 0x02;
-        public const byte FEATUREEXT_GLOBALTRANSACTIONS = 0x05;
-        public const byte FEATUREEXT_UTF8SUPPORT = 0x0A;
-
-        [Flags]
-        public enum FeatureExtension : uint
-        {
-            None = 0,
-            SessionRecovery = 1,
-            FedAuth = 2,
-            GlobalTransactions = 16,
-            UTF8Support = 512,
-        }
-
-        public const uint UTF8_IN_TDSCOLLATION = 0x4000000;
-
-        public const byte FEDAUTHLIB_LIVEID = 0X00;
-        public const byte FEDAUTHLIB_SECURITYTOKEN = 0x01;
-        public const byte FEDAUTHLIB_ADAL = 0x02;
-        public const byte FEDAUTHLIB_RESERVED = 0X7F;
-
-        public enum FedAuthLibrary : byte
-        {
-            LiveId = FEDAUTHLIB_LIVEID,
-            SecurityToken = FEDAUTHLIB_SECURITYTOKEN,
-            ADAL = FEDAUTHLIB_ADAL, // For later support
-            Default = FEDAUTHLIB_RESERVED
-        }
-
-        //    Loginrec defines
-        public const byte MAX_LOG_NAME = 30;              // TDS 4.2 login rec max name length
-        public const byte MAX_PROG_NAME = 10;              // max length of loginrec program name
-        public const byte SEC_COMP_LEN = 8;               // length of security compartments
-        public const byte MAX_PK_LEN = 6;               // max length of TDS packet size
-        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 YUKON_LOG_REC_FIXED_LEN = 0x5e;
-        // misc
-        public const int TEXT_TIME_STAMP_LEN = 8;
-        public const int COLLATION_INFO_LEN = 4;
-
-        /*
-                public const byte INT4_LSB_HI   = 0;     // lsb is low byte (e.g. 68000)
-                //    public const byte INT4_LSB_LO   = 1;     // lsb is low byte (e.g. VAX)
-                public const byte INT2_LSB_HI   = 2;     // lsb is low byte (e.g. 68000)
-                //    public const byte INT2_LSB_LO   = 3;     // lsb is low byte (e.g. VAX)
-                public const byte FLT_IEEE_HI   = 4;     // lsb is low byte (e.g. 68000)
-                public const byte CHAR_ASCII    = 6;     // ASCII character set
-                public const byte TWO_I4_LSB_HI = 8;     // lsb is low byte (e.g. 68000
-                //    public const byte TWO_I4_LSB_LO = 9;     // lsb is low byte (e.g. VAX)
-                //    public const byte FLT_IEEE_LO   = 10;    // lsb is low byte (e.g. MSDOS)
-                public const byte FLT4_IEEE_HI  = 12;    // IEEE 4-byte floating point -lsb is high byte
-                //    public const byte FLT4_IEEE_LO  = 13;    // IEEE 4-byte floating point -lsb is low byte
-                public const byte TWO_I2_LSB_HI = 16;    // lsb is high byte
-                //    public const byte TWO_I2_LSB_LO = 17;    // lsb is low byte
-
-                public const byte LDEFSQL     = 0;    // server sends its default
-                public const byte LDEFUSER    = 0;    // regular old user
-                public const byte LINTEGRATED = 8;    // integrated security login
-        */
-
-        /* Versioning scheme table:
-
-            Client sends:
-            0x70000000 -> Sphinx
-            0x71000000 -> Shiloh RTM
-            0x71000001 -> Shiloh SP1
-            0x72xx0002 -> Yukon RTM
-
-            Server responds:
-            0x07000000 -> Sphinx     // Notice server response format is different for bwd compat
-            0x07010000 -> Shiloh RTM // Notice server response format is different for bwd compat
-            0x71000001 -> Shiloh SP1
-            0x72xx0002 -> Yukon RTM
-        */
-
-
-        // Shiloh SP1 and beyond versioning scheme:
-
-        // Majors:
-        public const int YUKON_MAJOR = 0x72;     // the high-byte is sufficient to distinguish later versions
-        public const int KATMAI_MAJOR = 0x73;
-        public const int DENALI_MAJOR = 0x74;
-
-        // Increments:
-        public const int YUKON_INCREMENT = 0x09;
-        public const int KATMAI_INCREMENT = 0x0b;
-        public const int DENALI_INCREMENT = 0x00;
-
-        // Minors:
-        public const int YUKON_RTM_MINOR = 0x0002;
-        public const int KATMAI_MINOR = 0x0003;
-        public const int DENALI_MINOR = 0x0004;
-
-        public const int ORDER_68000 = 1;
-        public const int USE_DB_ON = 1;
-        public const int INIT_DB_FATAL = 1;
-        public const int SET_LANG_ON = 1;
-        public const int INIT_LANG_FATAL = 1;
-        public const int ODBC_ON = 1;
-        public const int SSPI_ON = 1;
-        public const int REPL_ON = 3;
-
-
-        // send the read-only intent to the server
-        public const int READONLY_INTENT_ON = 1;
-
-        // Token masks
-        public const byte SQLLenMask = 0x30;    // mask to check for length tokens
-        public const byte SQLFixedLen = 0x30;    // Mask to check for fixed token
-        public const byte SQLVarLen = 0x20;    // Value to check for variable length token
-        public const byte SQLZeroLen = 0x10;    // Value to check for zero length token
-        public const byte SQLVarCnt = 0x00;    // Value to check for variable count token
-
-        // Token masks for COLINFO status
-        public const byte SQLDifferentName = 0x20; // column name different than select list name
-        public const byte SQLExpression = 0x4;     // column was result of an expression
-        public const byte SQLKey = 0x8;            // column is part of the key for the table
-        public const byte SQLHidden = 0x10;        // column not part of select list but added because part of key
-
-        // Token masks for COLMETADATA flags
-        //   first byte
-        public const byte Nullable = 0x1;
-        public const byte Identity = 0x10;
-        public const byte Updatability = 0xb;   // mask off bits 3 and 4
-        //   second byte
-        public const byte ClrFixedLen = 0x1;    // Fixed length CLR type
-        public const byte IsColumnSet = 0x4;    // Column is an XML representation of an aggregation of other columns
-
-        // null values
-        public const uint VARLONGNULL = 0xffffffff; // null value for text and image types
-        public const int VARNULL = 0xffff;    // null value for character and binary types
-        public const int MAXSIZE = 8000; // max size for any column
-        public const byte FIXEDNULL = 0;
-        public const ulong UDTNULL = 0xffffffffffffffff;
-
-        // SQL Server Data Type Tokens.
-        public const int SQLVOID = 0x1f;
-        public const int SQLTEXT = 0x23;
-        public const int SQLVARBINARY = 0x25;
-        public const int SQLINTN = 0x26;
-        public const int SQLVARCHAR = 0x27;
-        public const int SQLBINARY = 0x2d;
-        public const int SQLIMAGE = 0x22;
-        public const int SQLCHAR = 0x2f;
-        public const int SQLINT1 = 0x30;
-        public const int SQLBIT = 0x32;
-        public const int SQLINT2 = 0x34;
-        public const int SQLINT4 = 0x38;
-        public const int SQLMONEY = 0x3c;
-        public const int SQLDATETIME = 0x3d;
-        public const int SQLFLT8 = 0x3e;
-        public const int SQLFLTN = 0x6d;
-        public const int SQLMONEYN = 0x6e;
-        public const int SQLDATETIMN = 0x6f;
-        public const int SQLFLT4 = 0x3b;
-        public const int SQLMONEY4 = 0x7a;
-        public const int SQLDATETIM4 = 0x3a;
-        public const int SQLDECIMALN = 0x6a;
-        public const int SQLNUMERICN = 0x6c;
-        public const int SQLUNIQUEID = 0x24;
-        public const int SQLBIGCHAR = 0xaf;
-        public const int SQLBIGVARCHAR = 0xa7;
-        public const int SQLBIGBINARY = 0xad;
-        public const int SQLBIGVARBINARY = 0xa5;
-        public const int SQLBITN = 0x68;
-        public const int SQLNCHAR = 0xef;
-        public const int SQLNVARCHAR = 0xe7;
-        public const int SQLNTEXT = 0x63;
-        public const int SQLUDT = 0xF0;
-
-        // aggregate operator type TDS tokens, used by compute statements:
-        public const int AOPCNTB = 0x09;
-        public const int AOPSTDEV = 0x30;
-        public const int AOPSTDEVP = 0x31;
-        public const int AOPVAR = 0x32;
-        public const int AOPVARP = 0x33;
-
-        public const int AOPCNT = 0x4b;
-        public const int AOPSUM = 0x4d;
-        public const int AOPAVG = 0x4f;
-        public const int AOPMIN = 0x51;
-        public const int AOPMAX = 0x52;
-        public const int AOPANY = 0x53;
-        public const int AOPNOOP = 0x56;
-
-        // SQL Server user-defined type tokens we care about
-        public const int SQLTIMESTAMP = 0x50;
-
-        public const int MAX_NUMERIC_LEN = 0x11; // 17 bytes of data for max numeric/decimal length
-        public const int DEFAULT_NUMERIC_PRECISION = 0x1D; // 29 is the default max numeric precision(Decimal.MaxValue) if not user set
-        public const int SPHINX_DEFAULT_NUMERIC_PRECISION = 0x1C; // 28 is the default max numeric precision for Sphinx(Decimal.MaxValue doesn't work for sphinx)
-        public const int MAX_NUMERIC_PRECISION = 0x26; // 38 is max numeric precision;
-        public const byte UNKNOWN_PRECISION_SCALE = 0xff; // -1 is value for unknown precision or scale
-
-        // The following datatypes are specific to SHILOH (version 8) and later.
-        public const int SQLINT8 = 0x7f;
-        public const int SQLVARIANT = 0x62;
-
-        // The following datatypes are specific to Yukon (version 9) or later
-        public const int SQLXMLTYPE = 0xf1;
-        public const int XMLUNICODEBOM = 0xfeff;
-        public static readonly byte[] XMLUNICODEBOMBYTES = { 0xff, 0xfe };
-
-        // The following datatypes are specific to Katmai (version 10) or later
-        public const int SQLTABLE = 0xf3;
-        public const int SQLDATE = 0x28;
-        public const int SQLTIME = 0x29;
-        public const int SQLDATETIME2 = 0x2a;
-        public const int SQLDATETIMEOFFSET = 0x2b;
-
-        public const int DEFAULT_VARTIME_SCALE = 7;
-
-        //Partially length prefixed datatypes constants. These apply to XMLTYPE, BIGVARCHRTYPE,
-        // NVARCHARTYPE, and BIGVARBINTYPE. Valid for Yukon or later
-
-        public const ulong SQL_PLP_NULL = 0xffffffffffffffff;        // Represents null value
-        public const ulong SQL_PLP_UNKNOWNLEN = 0xfffffffffffffffe;  // Data coming in chunks, total length unknown
-        public const int SQL_PLP_CHUNK_TERMINATOR = 0x00000000;     // Represents end of chunked data.
-        public const ushort SQL_USHORTVARMAXLEN = 0xffff;          // Second ushort in TDS stream is this value if one of max types
-
-        // TVPs require some new in-value control tokens:
-        public const byte TVP_ROWCOUNT_ESTIMATE = 0x12;
-        public const byte TVP_ROW_TOKEN = 0x01;
-        public const byte TVP_END_TOKEN = 0x00;
-        public const ushort TVP_NOMETADATA_TOKEN = 0xFFFF;
-        public const byte TVP_ORDER_UNIQUE_TOKEN = 0x10;
-
-        // TvpColumnMetaData flags
-        public const int TVP_DEFAULT_COLUMN = 0x200;
-
-        // TVP_ORDER_UNIQUE_TOKEN flags
-        public const byte TVP_ORDERASC_FLAG = 0x1;
-        public const byte TVP_ORDERDESC_FLAG = 0x2;
-        public const byte TVP_UNIQUE_FLAG = 0x4;
-
-
-        // RPC function names
-        public const string SP_EXECUTESQL = "sp_executesql";       // used against 7.0 servers
-        public const string SP_PREPEXEC = "sp_prepexec";         // used against 7.5 servers
-
-        public const string SP_PREPARE = "sp_prepare";          // used against 7.0 servers
-        public const string SP_EXECUTE = "sp_execute";
-        public const string SP_UNPREPARE = "sp_unprepare";
-        public const string SP_PARAMS = "sp_procedure_params_rowset";
-        public const string SP_PARAMS_MANAGED = "sp_procedure_params_managed";
-        public const string SP_PARAMS_MGD10 = "sp_procedure_params_100_managed";
-
-        // RPC ProcID's
-        // NOTE: It is more efficient to call these procs using ProcID's instead of names
-        public const ushort RPC_PROCID_CURSOR = 1;
-        public const ushort RPC_PROCID_CURSOROPEN = 2;
-        public const ushort RPC_PROCID_CURSORPREPARE = 3;
-        public const ushort RPC_PROCID_CURSOREXECUTE = 4;
-        public const ushort RPC_PROCID_CURSORPREPEXEC = 5;
-        public const ushort RPC_PROCID_CURSORUNPREPARE = 6;
-        public const ushort RPC_PROCID_CURSORFETCH = 7;
-        public const ushort RPC_PROCID_CURSOROPTION = 8;
-        public const ushort RPC_PROCID_CURSORCLOSE = 9;
-        public const ushort RPC_PROCID_EXECUTESQL = 10;
-        public const ushort RPC_PROCID_PREPARE = 11;
-        public const ushort RPC_PROCID_EXECUTE = 12;
-        public const ushort RPC_PROCID_PREPEXEC = 13;
-        public const ushort RPC_PROCID_PREPEXECRPC = 14;
-        public const ushort RPC_PROCID_UNPREPARE = 15;
-
-        // For Transactions
-        public const string TRANS_BEGIN = "BEGIN TRANSACTION";
-        public const string TRANS_COMMIT = "COMMIT TRANSACTION";
-        public const string TRANS_ROLLBACK = "ROLLBACK TRANSACTION";
-        public const string TRANS_IF_ROLLBACK = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION";
-        public const string TRANS_SAVE = "SAVE TRANSACTION";
-
-        // For Transactions - isolation levels
-        public const string TRANS_READ_COMMITTED = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
-        public const string TRANS_READ_UNCOMMITTED = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
-        public const string TRANS_REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ";
-        public const string TRANS_SERIALIZABLE = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE";
-        public const string TRANS_SNAPSHOT = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT";
-
-        // Batch RPC flags
-        public const byte SHILOH_RPCBATCHFLAG = 0x80;
-        public const byte YUKON_RPCBATCHFLAG = 0xFF;
-
-        // RPC flags
-        public const byte RPC_RECOMPILE = 0x1;
-        public const byte RPC_NOMETADATA = 0x2;
-
-        // RPC parameter class
-        public const byte RPC_PARAM_BYREF = 0x1;
-        public const byte RPC_PARAM_DEFAULT = 0x2;
-        public const byte RPC_PARAM_IS_LOB_COOKIE = 0x8;
-
-        // SQL parameter list text
-        public const string PARAM_OUTPUT = "output";
-
-        // SQL Parameter constants
-        public const int MAX_PARAMETER_NAME_LENGTH = 128;
-
-        // metadata options (added around an existing sql statement)
-
-        // prefixes
-        public const string FMTONLY_ON = " SET FMTONLY ON;";
-        public const string FMTONLY_OFF = " SET FMTONLY OFF;";
-        // suffixes
-        public const string BROWSE_ON = " SET NO_BROWSETABLE ON;";
-        public const string BROWSE_OFF = " SET NO_BROWSETABLE OFF;";
-
-        // generic table name
-        public const string TABLE = "Table";
-
-        public const int EXEC_THRESHOLD = 0x3; // if the number of commands we execute is > than this threshold, than do prep/exec/unprep instead
-        // of executesql.
-
-        // dbnetlib error values
-        public const short TIMEOUT_EXPIRED = -2;
-        public const short ENCRYPTION_NOT_SUPPORTED = 20;
-        // CAUTION: These are not error codes returned by SNI. This is used for backward compatibility
-        // since netlib (now removed from sqlclient) returned these codes.
-
-        // SQL error values (from sqlerrorcodes.h)
-        public const int LOGON_FAILED = 18456;
-        public const int PASSWORD_EXPIRED = 18488;
-        public const int IMPERSONATION_FAILED = 1346;
-        public const int P_TOKENTOOLONG = 103;
-
-        // SNI\Win32 error values
-        // NOTE: these are simply windows system error codes, not SNI specific
-        public const uint SNI_UNINITIALIZED = unchecked((uint)-1);
-        public const uint SNI_SUCCESS = 0;        // The operation completed successfully.
-        public const uint SNI_ERROR = 1;          // Error
-        public const uint SNI_WAIT_TIMEOUT = 258;      // The wait operation timed out.
-        public const uint SNI_SUCCESS_IO_PENDING = 997;      // Overlapped I/O operation is in progress.
-
-        // Windows Sockets Error Codes
-        public const short SNI_WSAECONNRESET = 10054;    // An existing connection was forcibly closed by the remote host.
-
-        // SNI internal errors (shouldn't overlap with Win32 / socket errors)
-        public const uint SNI_QUEUE_FULL = 1048576;         // Packet queue is full
-
-        // SNI flags
-        public const uint SNI_SSL_VALIDATE_CERTIFICATE = 1;   // This enables validation of server certificate
-        public const uint SNI_SSL_USE_SCHANNEL_CACHE = 2;     // This enables schannel session cache
-        public const uint SNI_SSL_IGNORE_CHANNEL_BINDINGS = 0x10; // Used with SSL Provider, sent to SNIAddProvider in case of SQL Authentication & Encrypt.
-
-        public const string DEFAULT_ENGLISH_CODE_PAGE_STRING = "iso_1";
-        public const short DEFAULT_ENGLISH_CODE_PAGE_VALUE = 1252;
-        public const short CHARSET_CODE_PAGE_OFFSET = 2;
-        internal const int MAX_SERVERNAME = 255;
-
-        // Sql Statement Tokens in the DONE packet
-        // (see ntdbms\ntinc\tokens.h)
-        //
-        internal const ushort SELECT = 0xc1;
-        internal const ushort INSERT = 0xc3;
-        internal const ushort DELETE = 0xc4;
-        internal const ushort UPDATE = 0xc5;
-        internal const ushort ABORT = 0xd2;
-        internal const ushort BEGINXACT = 0xd4;
-        internal const ushort ENDXACT = 0xd5;
-        internal const ushort BULKINSERT = 0xf0;
-        internal const ushort OPENCURSOR = 0x20;
-        internal const ushort MERGE = 0x117;
-
-
-        // Login data validation Rules
-        //
-        internal const ushort MAXLEN_HOSTNAME = 128; // the client machine name
-        internal const ushort MAXLEN_USERNAME = 128; // the client user id
-        internal const ushort MAXLEN_PASSWORD = 128; // the password supplied by the client
-        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
-        internal const ushort MAXLEN_LANGUAGE = 128; // the initial language
-        internal const ushort MAXLEN_DATABASE = 128; // the initial database
-        internal const ushort MAXLEN_ATTACHDBFILE = 260; // the filename for a database that is to be attached during the connection process
-        internal const ushort MAXLEN_NEWPASSWORD = 128; // new password for the specified login.
-
-
-        // array copied directly from tdssort.h from luxor
-        public static readonly ushort[] CODE_PAGE_FROM_SORT_ID = {
-            0,      /*   0 */
-            0,      /*   1 */
-            0,      /*   2 */
-            0,      /*   3 */
-            0,      /*   4 */
-            0,      /*   5 */
-            0,      /*   6 */
-            0,      /*   7 */
-            0,      /*   8 */
-            0,      /*   9 */
-            0,      /*  10 */
-            0,      /*  11 */
-            0,      /*  12 */
-            0,      /*  13 */
-            0,      /*  14 */
-            0,      /*  15 */
-            0,      /*  16 */
-            0,      /*  17 */
-            0,      /*  18 */
-            0,      /*  19 */
-            0,      /*  20 */
-            0,      /*  21 */
-            0,      /*  22 */
-            0,      /*  23 */
-            0,      /*  24 */
-            0,      /*  25 */
-            0,      /*  26 */
-            0,      /*  27 */
-            0,      /*  28 */
-            0,      /*  29 */
-            437,    /*  30 */
-            437,    /*  31 */
-            437,    /*  32 */
-            437,    /*  33 */
-            437,    /*  34 */
-            0,      /*  35 */
-            0,      /*  36 */
-            0,      /*  37 */
-            0,      /*  38 */
-            0,      /*  39 */
-            850,    /*  40 */
-            850,    /*  41 */
-            850,    /*  42 */
-            850,    /*  43 */
-            850,    /*  44 */
-            0,      /*  45 */
-            0,      /*  46 */
-            0,      /*  47 */
-            0,      /*  48 */
-            850,    /*  49 */
-            1252,   /*  50 */
-            1252,   /*  51 */
-            1252,   /*  52 */
-            1252,   /*  53 */
-            1252,   /*  54 */
-            850,    /*  55 */
-            850,    /*  56 */
-            850,    /*  57 */
-            850,    /*  58 */
-            850,    /*  59 */
-            850,    /*  60 */
-            850,    /*  61 */
-            0,      /*  62 */
-            0,      /*  63 */
-            0,      /*  64 */
-            0,      /*  65 */
-            0,      /*  66 */
-            0,      /*  67 */
-            0,      /*  68 */
-            0,      /*  69 */
-            0,      /*  70 */
-            1252,   /*  71 */
-            1252,   /*  72 */
-            1252,   /*  73 */
-            1252,   /*  74 */
-            1252,   /*  75 */
-            0,      /*  76 */
-            0,      /*  77 */
-            0,      /*  78 */
-            0,      /*  79 */
-            1250,   /*  80 */
-            1250,   /*  81 */
-            1250,   /*  82 */
-            1250,   /*  83 */
-            1250,   /*  84 */
-            1250,   /*  85 */
-            1250,   /*  86 */
-            1250,   /*  87 */
-            1250,   /*  88 */
-            1250,   /*  89 */
-            1250,   /*  90 */
-            1250,   /*  91 */
-            1250,   /*  92 */
-            1250,   /*  93 */
-            1250,   /*  94 */
-            1250,   /*  95 */
-            1250,   /*  96 */
-            1250,   /*  97 */
-            1250,   /*  98 */
-            0,      /*  99 */
-            0,      /* 100 */
-            0,      /* 101 */
-            0,      /* 102 */
-            0,      /* 103 */
-            1251,   /* 104 */
-            1251,   /* 105 */
-            1251,   /* 106 */
-            1251,   /* 107 */
-            1251,   /* 108 */
-            0,      /* 109 */
-            0,      /* 110 */
-            0,      /* 111 */
-            1253,   /* 112 */
-            1253,   /* 113 */
-            1253,   /* 114 */
-            0,      /* 115 */
-            0,      /* 116 */
-            0,      /* 117 */
-            0,      /* 118 */
-            0,      /* 119 */
-            1253,   /* 120 */
-            1253,   /* 121 */
-            1253,   /* 122 */
-            0,      /* 123 */
-            1253,   /* 124 */
-            0,      /* 125 */
-            0,      /* 126 */
-            0,      /* 127 */
-            1254,   /* 128 */
-            1254,   /* 129 */
-            1254,   /* 130 */
-            0,      /* 131 */
-            0,      /* 132 */
-            0,      /* 133 */
-            0,      /* 134 */
-            0,      /* 135 */
-            1255,   /* 136 */
-            1255,   /* 137 */
-            1255,   /* 138 */
-            0,      /* 139 */
-            0,      /* 140 */
-            0,      /* 141 */
-            0,      /* 142 */
-            0,      /* 143 */
-            1256,   /* 144 */
-            1256,   /* 145 */
-            1256,   /* 146 */
-            0,      /* 147 */
-            0,      /* 148 */
-            0,      /* 149 */
-            0,      /* 150 */
-            0,      /* 151 */
-            1257,   /* 152 */
-            1257,   /* 153 */
-            1257,   /* 154 */
-            1257,   /* 155 */
-            1257,   /* 156 */
-            1257,   /* 157 */
-            1257,   /* 158 */
-            1257,   /* 159 */
-            1257,   /* 160 */
-            0,      /* 161 */
-            0,      /* 162 */
-            0,      /* 163 */
-            0,      /* 164 */
-            0,      /* 165 */
-            0,      /* 166 */
-            0,      /* 167 */
-            0,      /* 168 */
-            0,      /* 169 */
-            0,      /* 170 */
-            0,      /* 171 */
-            0,      /* 172 */
-            0,      /* 173 */
-            0,      /* 174 */
-            0,      /* 175 */
-            0,      /* 176 */
-            0,      /* 177 */
-            0,      /* 178 */
-            0,      /* 179 */
-            0,      /* 180 */
-            0,      /* 181 */
-            0,      /* 182 */
-            1252,   /* 183 */
-            1252,   /* 184 */
-            1252,   /* 185 */
-            1252,   /* 186 */
-            0,      /* 187 */
-            0,      /* 188 */
-            0,      /* 189 */
-            0,      /* 190 */
-            0,      /* 191 */
-            932,    /* 192 */
-            932,    /* 193 */
-            949,    /* 194 */
-            949,    /* 195 */
-            950,    /* 196 */
-            950,    /* 197 */
-            936,    /* 198 */
-            936,    /* 199 */
-            932,    /* 200 */
-            949,    /* 201 */
-            950,    /* 202 */
-            936,    /* 203 */
-            874,    /* 204 */
-            874,    /* 205 */
-            874,    /* 206 */
-            0,      /* 207 */
-            0,      /* 208 */
-            0,      /* 209 */
-            1252,   /* 210 */
-            1252,   /* 211 */
-            1252,   /* 212 */
-            1252,   /* 213 */
-            1252,   /* 214 */
-            1252,   /* 215 */
-            1252,   /* 216 */
-            1252,   /* 217 */
-            0,      /* 218 */
-            0,      /* 219 */
-            0,      /* 220 */
-            0,      /* 221 */
-            0,      /* 222 */
-            0,      /* 223 */
-            0,      /* 224 */
-            0,      /* 225 */
-            0,      /* 226 */
-            0,      /* 227 */
-            0,      /* 228 */
-            0,      /* 229 */
-            0,      /* 230 */
-            0,      /* 231 */
-            0,      /* 232 */
-            0,      /* 233 */
-            0,      /* 234 */
-            0,      /* 235 */
-            0,      /* 236 */
-            0,      /* 237 */
-            0,      /* 238 */
-            0,      /* 239 */
-            0,      /* 240 */
-            0,      /* 241 */
-            0,      /* 242 */
-            0,      /* 243 */
-            0,      /* 244 */
-            0,      /* 245 */
-            0,      /* 246 */
-            0,      /* 247 */
-            0,      /* 248 */
-            0,      /* 249 */
-            0,      /* 250 */
-            0,      /* 251 */
-            0,      /* 252 */
-            0,      /* 253 */
-            0,      /* 254 */
-            0,      /* 255 */
-        };
-
-
-        internal enum TransactionManagerRequestType
-        {
-            GetDTCAddress = 0,
-            Propagate = 1,
-            Begin = 5,
-            Promote = 6,
-            Commit = 7,
-            Rollback = 8,
-            Save = 9
-        };
-
-        internal enum TransactionManagerIsolationLevel
-        {
-            Unspecified = 0x00,
-            ReadUncommitted = 0x01,
-            ReadCommitted = 0x02,
-            RepeatableRead = 0x03,
-            Serializable = 0x04,
-            Snapshot = 0x05
-        }
-
-        internal enum GenericType
-        {
-            MultiSet = 131,
-        };
-
-        // Date, Time, DateTime2, DateTimeOffset specific constants
-        internal static readonly long[] TICKS_FROM_SCALE = {
-            10000000,
-            1000000,
-            100000,
-            10000,
-            1000,
-            100,
-            10,
-            1,
-        };
-
-        internal const int WHIDBEY_DATE_LENGTH = 10;
-        internal static readonly int[] WHIDBEY_TIME_LENGTH = { 8, 10, 11, 12, 13, 14, 15, 16 };
-        internal static readonly int[] WHIDBEY_DATETIME2_LENGTH = { 19, 21, 22, 23, 24, 25, 26, 27 };
-        internal static readonly int[] WHIDBEY_DATETIMEOFFSET_LENGTH = { 26, 28, 29, 30, 31, 32, 33, 34 };
-
-        // Needed for UapAot, since we cannot use Enum.GetName() on SniContext.
-        // Enum.GetName() uses reflection, which is blocked on UapAot for internal types
-        // like SniContext.
-        internal static string GetSniContextEnumName(SniContext sniContext)
-        {
-            switch (sniContext)
-            {
-                case SniContext.Undefined:
-                    return "Undefined";
-                case SniContext.Snix_Connect:
-                    return "Snix_Connect";
-                case SniContext.Snix_PreLoginBeforeSuccessfulWrite:
-                    return "Snix_PreLoginBeforeSuccessfulWrite";
-                case SniContext.Snix_PreLogin:
-                    return "Snix_PreLogin";
-                case SniContext.Snix_LoginSspi:
-                    return "Snix_LoginSspi";
-                case SniContext.Snix_ProcessSspi:
-                    return "Snix_ProcessSspi";
-                case SniContext.Snix_Login:
-                    return "Snix_Login";
-                case SniContext.Snix_EnableMars:
-                    return "Snix_EnableMars";
-                case SniContext.Snix_AutoEnlist:
-                    return "Snix_AutoEnlist";
-                case SniContext.Snix_GetMarsSession:
-                    return "Snix_GetMarsSession";
-                case SniContext.Snix_Execute:
-                    return "Snix_Execute";
-                case SniContext.Snix_Read:
-                    return "Snix_Read";
-                case SniContext.Snix_Close:
-                    return "Snix_Close";
-                case SniContext.Snix_SendRows:
-                    return "Snix_SendRows";
-                default:
-                    Debug.Fail($"Received unknown SniContext enum. Value: {sniContext}");
-                    return null;
-            }
-        }
-    }
-
-    internal enum SniContext
-    {
-        Undefined = 0,
-        Snix_Connect,
-        Snix_PreLoginBeforeSuccessfulWrite,
-        Snix_PreLogin,
-        Snix_LoginSspi,
-        Snix_ProcessSspi,
-        Snix_Login,
-        Snix_EnableMars,
-        Snix_AutoEnlist,
-        Snix_GetMarsSession,
-        Snix_Execute,
-        Snix_Read,
-        Snix_Close,
-        Snix_SendRows,
-    }
-
-    internal enum ParsingErrorState
-    {
-        Undefined = 0,
-        FedAuthInfoLengthTooShortForCountOfInfoIds = 1,
-        FedAuthInfoLengthTooShortForData = 2,
-        FedAuthInfoFailedToReadCountOfInfoIds = 3,
-        FedAuthInfoFailedToReadTokenStream = 4,
-        FedAuthInfoInvalidOffset = 5,
-        FedAuthInfoFailedToReadData = 6,
-        FedAuthInfoDataNotUnicode = 7,
-        FedAuthInfoDoesNotContainStsurlAndSpn = 8,
-        FedAuthInfoNotReceived = 9,
-        FedAuthNotAcknowledged = 10,
-        FedAuthFeatureAckContainsExtraData = 11,
-        FedAuthFeatureAckUnknownLibraryType = 12,
-        UnrequestedFeatureAckReceived = 13,
-        UnknownFeatureAck = 14,
-        InvalidTdsTokenReceived = 15,
-        SessionStateLengthTooShort = 16,
-        SessionStateInvalidStatus = 17,
-        CorruptedTdsStream = 18,
-        ProcessSniPacketFailed = 19,
-        FedAuthRequiredPreLoginResponseInvalidValue = 20,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParameterSetter.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParameterSetter.cs
deleted file mode 100644 (file)
index dde66a7..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-
-
-
-//------------------------------------------------------------------------------
-
-using System.Diagnostics;
-
-using Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    // Simple Getter/Setter for structured parameters to allow using common ValueUtilsSmi code.
-    //  This is a stand-in to having a true SmiRequestExecutor class for TDS.
-    internal class TdsParameterSetter : SmiTypedGetterSetter
-    {
-        #region Private fields
-
-        private readonly TdsRecordBufferSetter _target;
-
-        #endregion
-
-        #region ctor & control
-
-        internal TdsParameterSetter(TdsParserStateObject stateObj, SmiMetaData md)
-        {
-            _target = new TdsRecordBufferSetter(stateObj, md);
-        }
-
-        #endregion
-
-        #region TypedGetterSetter overrides
-        // Are calls to Get methods allowed?
-        internal override bool CanGet
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        // Are calls to Set methods allowed?
-        internal override bool CanSet
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        // valid for structured types
-        //  This method called for both get and set.
-        internal override SmiTypedGetterSetter GetTypedGetterSetter(SmiEventSink sink, int ordinal)
-        {
-            Debug.Assert(0 == ordinal, "TdsParameterSetter only supports 0 for ordinal.  Actual = " + ordinal);
-            return _target;
-        }
-
-        // Set value to null
-        //  valid for all types
-        public override void SetDBNull(SmiEventSink sink, int ordinal)
-        {
-            Debug.Assert(0 == ordinal, "TdsParameterSetter only supports 0 for ordinal.  Actual = " + ordinal);
-
-            _target.EndElements(sink);
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.NetCoreApp.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.NetCoreApp.cs
deleted file mode 100644 (file)
index 733b8c1..0000000
+++ /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;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class TdsParser
-    {
-        internal static void FillGuidBytes(Guid guid, Span<byte> buffer) => guid.TryWriteBytes(buffer);
-
-        internal static void FillDoubleBytes(double value, Span<byte> buffer) => BitConverter.TryWriteBytes(buffer, value);
-
-        internal static void FillFloatBytes(float v, Span<byte> buffer) => BitConverter.TryWriteBytes(buffer, v);
-
-        internal static Guid ConstructGuid(ReadOnlySpan<byte> bytes)
-        {
-            Debug.Assert(bytes.Length >= 16, "not enough bytes to set guid");
-            return new Guid(bytes);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.NetStandard.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.NetStandard.cs
deleted file mode 100644 (file)
index 29626d5..0000000
+++ /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.Diagnostics;
-using System.Buffers;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class TdsParser
-    {
-        internal static void FillGuidBytes(Guid guid, Span<byte> buffer)
-        {
-            byte[] bytes = guid.ToByteArray();
-            bytes.AsSpan().CopyTo(buffer);
-        }
-
-        internal static void FillDoubleBytes(double value, Span<byte> buffer)
-        {
-            byte[] bytes = BitConverter.GetBytes(value);
-            bytes.AsSpan().CopyTo(buffer);
-        }
-
-        internal static void FillFloatBytes(float value, Span<byte> buffer)
-        {
-            byte[] bytes = BitConverter.GetBytes(value);
-            bytes.AsSpan().CopyTo(buffer);
-        }
-
-        internal static Guid ConstructGuid(ReadOnlySpan<byte> bytes)
-        {
-            Debug.Assert(bytes.Length >= 16, "not enough bytes to set guid");
-            byte[] temp = ArrayPool<byte>.Shared.Rent(16);
-            bytes.CopyTo(temp.AsSpan());
-            Guid retval = new Guid(temp);
-            ArrayPool<byte>.Shared.Return(temp);
-            return retval;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.RegisterEncoding.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.RegisterEncoding.cs
deleted file mode 100644 (file)
index 7cb54c6..0000000
+++ /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.Text;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class TdsParser
-    {
-        static TdsParser()
-        {
-            // For CoreCLR, we need to register the ANSI Code Page encoding provider before attempting to get an Encoding from a CodePage
-            // For a default installation of SqlServer the encoding exchanged during Login is 1252. This encoding is not loaded by default
-            // See Remarks at https://msdn.microsoft.com/en-us/library/system.text.encodingprovider(v=vs.110).aspx
-            // SqlClient needs to register the encoding providers to make sure that even basic scenarios work with Sql Server.
-            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.Unix.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.Unix.cs
deleted file mode 100644 (file)
index b0fc7bc..0000000
+++ /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.Diagnostics;
-using System.Data.SqlClient.SNI;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class TdsParser
-    {
-        internal void PostReadAsyncForMars()
-        {
-            // No-Op
-        }
-
-        private void LoadSSPILibrary()
-        {
-            // No - Op
-        }
-
-        private void WaitForSSLHandShakeToComplete(ref uint error)
-        {
-            // No - Op
-
-        }
-
-        private SNIErrorDetails GetSniErrorDetails()
-        {
-            SNIErrorDetails details;
-            SNIError sniError = SNIProxy.Singleton.GetLastError();
-            details.sniErrorNumber = sniError.sniError;
-            details.errorMessage = sniError.errorMessage;
-            details.nativeError = sniError.nativeError;
-            details.provider = (int)sniError.provider;
-            details.lineNumber = sniError.lineNumber;
-            details.function = sniError.function;
-            details.exception = sniError.exception;
-
-            return details;
-        }
-
-    }    // tdsparser
-}//namespace
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.Windows.cs
deleted file mode 100644 (file)
index cf28575..0000000
+++ /dev/null
@@ -1,124 +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.Data.SqlClient.SNI;
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class TdsParser
-    {
-        private static readonly object s_tdsParserLock = new object();
-        private static volatile bool s_fSSPILoaded = false; // bool to indicate whether library has been loaded
-
-        internal void PostReadAsyncForMars()
-        {
-            if (TdsParserStateObjectFactory.UseManagedSNI)
-                return;
-
-            // HACK HACK HACK - for Async only
-            // Have to post read to initialize MARS - will get callback on this when connection goes
-            // down or is closed.
-
-            PacketHandle temp = default;
-            uint error = TdsEnums.SNI_SUCCESS;
-
-            _pMarsPhysicalConObj.IncrementPendingCallbacks();
-            SessionHandle handle = _pMarsPhysicalConObj.SessionHandle;
-            temp = _pMarsPhysicalConObj.ReadAsync(handle, out error);
-
-            Debug.Assert(temp.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
-
-            if (temp.NativePointer != IntPtr.Zero)
-            {
-                // Be sure to release packet, otherwise it will be leaked by native.
-                _pMarsPhysicalConObj.ReleasePacket(temp);
-            }
-
-            Debug.Assert(IntPtr.Zero == temp.NativePointer, "unexpected syncReadPacket without corresponding SNIPacketRelease");
-            if (TdsEnums.SNI_SUCCESS_IO_PENDING != error)
-            {
-                Debug.Assert(TdsEnums.SNI_SUCCESS != error, "Unexpected successful read async on physical connection before enabling MARS!");
-                _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-                ThrowExceptionAndWarning(_physicalStateObj);
-            }
-        }
-
-        private void LoadSSPILibrary()
-        {
-            if (TdsParserStateObjectFactory.UseManagedSNI)
-                return;
-            // Outer check so we don't acquire lock once it's loaded.
-            if (!s_fSSPILoaded)
-            {
-                lock (s_tdsParserLock)
-                {
-                    // re-check inside lock
-                    if (!s_fSSPILoaded)
-                    {
-                        // use local for ref param to defer setting s_maxSSPILength until we know the call succeeded.
-                        uint maxLength = 0;
-
-                        if (0 != SNINativeMethodWrapper.SNISecInitPackage(ref maxLength))
-                            SSPIError(SQLMessage.SSPIInitializeError(), TdsEnums.INIT_SSPI_PACKAGE);
-
-                        s_maxSSPILength = maxLength;
-                        s_fSSPILoaded = true;
-                    }
-                }
-            }
-
-            if (s_maxSSPILength > int.MaxValue)
-            {
-                throw SQL.InvalidSSPIPacketSize();   // SqlBu 332503
-            }
-        }
-
-        private void WaitForSSLHandShakeToComplete(ref uint error)
-        {
-            if (TdsParserStateObjectFactory.UseManagedSNI)
-                return;
-            // in the case where an async connection is made, encryption is used and Windows Authentication is used,
-            // wait for SSL handshake to complete, so that the SSL context is fully negotiated before we try to use its
-            // Channel Bindings as part of the Windows Authentication context build (SSL handshake must complete
-            // before calling SNISecGenClientContext).
-            error = _physicalStateObj.WaitForSSLHandShakeToComplete();
-            if (error != TdsEnums.SNI_SUCCESS)
-            {
-                _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-                ThrowExceptionAndWarning(_physicalStateObj);
-            }
-        }
-
-        private SNIErrorDetails GetSniErrorDetails()
-        {
-            SNIErrorDetails details = default;
-
-            if (TdsParserStateObjectFactory.UseManagedSNI)
-            {
-                SNIError sniError = SNIProxy.Singleton.GetLastError();
-                details.sniErrorNumber = sniError.sniError;
-                details.errorMessage = sniError.errorMessage;
-                details.nativeError = sniError.nativeError;
-                details.provider = (int)sniError.provider;
-                details.lineNumber = sniError.lineNumber;
-                details.function = sniError.function;
-                details.exception = sniError.exception;
-            }
-            else
-            {
-                SNINativeMethodWrapper.SNI_Error sniError;
-                SNINativeMethodWrapper.SNIGetLastError(out sniError);
-                details.sniErrorNumber = sniError.sniError;
-                details.errorMessage = sniError.errorMessage;
-                details.nativeError = sniError.nativeError;
-                details.provider = (int)sniError.provider;
-                details.lineNumber = sniError.lineNumber;
-                details.function = sniError.function;
-            }
-            return details;
-        }
-
-    }    // tdsparser
-}//namespace
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs
deleted file mode 100644 (file)
index 892c7c0..0000000
+++ /dev/null
@@ -1,10070 +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.Generic;
-using System.Buffers;
-using System.Data.Common;
-using System.Data.Sql;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-using Microsoft.SqlServer.Server;
-using MSS = Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    internal struct SNIErrorDetails
-    {
-        public string errorMessage;
-        public uint nativeError;
-        public uint sniErrorNumber;
-        public int provider;
-        public uint lineNumber;
-        public string function;
-        public Exception exception;
-    }
-
-    // The TdsParser Object controls reading/writing to the netlib, parsing the tds,
-    // and surfacing objects to the user.
-    internal sealed partial class TdsParser
-    {
-        // Default state object for parser
-        internal TdsParserStateObject _physicalStateObj = null; // Default stateObj and connection for Dbnetlib and non-MARS SNI.
-
-        // Also, default logical stateObj and connection for MARS over SNI.
-        internal TdsParserStateObject _pMarsPhysicalConObj = null; // With MARS enabled, cached physical stateObj and connection.
-
-        // Must keep this around - especially for callbacks on pre-MARS
-        // ReadAsync which will return if physical connection broken!
-        //
-        // Per Instance TDS Parser variables
-        //
-
-        // Constants
-        private const int constBinBufferSize = 4096; // Size of the buffer used to read input parameter of type Stream
-        private const int constTextBufferSize = 4096; // Size of the buffer (in chars) user to read input parameter of type TextReader
-
-        // State variables
-        internal TdsParserState _state = TdsParserState.Closed; // status flag for connection
-
-        private string _server = "";                            // name of server that the parser connects to
-
-        internal volatile bool _fResetConnection = false;                 // flag to denote whether we are needing to call sp_reset
-        internal volatile bool _fPreserveTransaction = false;             // flag to denote whether we need to preserve the transaction when reseting
-
-        private SqlCollation _defaultCollation;                         // default collation from the server
-
-        private int _defaultCodePage;
-
-        private int _defaultLCID;
-
-        internal Encoding _defaultEncoding = null;                  // for sql character data
-
-        private static readonly EncryptionOptions s_sniSupportedEncryptionOption = TdsParserStateObjectFactory.Singleton.EncryptionOptions;
-
-        private EncryptionOptions _encryptionOption = s_sniSupportedEncryptionOption;
-
-        private SqlInternalTransaction _currentTransaction;
-        private SqlInternalTransaction _pendingTransaction;    // pending transaction for Yukon and beyond.
-
-        //  need to hold on to the transaction id if distributed transaction merely rolls back without defecting.
-        private long _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
-
-        // This counter is used for the entire connection to track the open result count for all
-        // operations not under a transaction.
-        private int _nonTransactedOpenResultCount = 0;
-
-        // Connection reference
-        private SqlInternalConnectionTds _connHandler;
-
-        // Async/Mars variables
-        private bool _fMARS = false;
-
-        internal bool _loginWithFailover = false; // set to true while connect in failover mode so parser state object can adjust its logic
-
-        internal AutoResetEvent _resetConnectionEvent = null;  // Used to serialize executes and call reset on first execute only.
-
-        internal TdsParserSessionPool _sessionPool = null;  // initialized only when we're a MARS parser.
-
-        // Version variables
-
-        private bool _isYukon = false; // set to true if speaking to Yukon or later
-
-        private bool _isKatmai = false;
-
-        private bool _isDenali = false;
-
-        private byte[] _sniSpnBuffer = null;
-
-        // SqlStatistics
-        private SqlStatistics _statistics = null;
-
-        private bool _statisticsIsInTransaction = false;
-
-        //
-        // STATIC TDS Parser variables
-        //
-
-        // NIC address caching
-        private static byte[] s_nicAddress;             // cache the NIC address from the registry
-
-        // SSPI variables
-
-        private static volatile uint s_maxSSPILength = 0;     // variable to hold max SSPI data size, keep for token from server
-
-        // textptr sequence
-        private static readonly byte[] s_longDataHeader = { 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
-
-        // XML metadata substitute sequence
-        private static readonly byte[] s_xmlMetadataSubstituteSequence = { 0xe7, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
-        // size of Guid  (e.g. _clientConnectionId, ActivityId.Id)
-        private const int GUID_SIZE = 16;
-
-        // NOTE: You must take the internal connection's _parserLock before modifying this
-        internal bool _asyncWrite = false;
-
-        internal TdsParser(bool MARS, bool fAsynchronous)
-        {
-            _fMARS = MARS; // may change during Connect to pre Yukon servers
-
-            _physicalStateObj = TdsParserStateObjectFactory.Singleton.CreateTdsParserStateObject(this);
-        }
-
-        internal SqlInternalConnectionTds Connection
-        {
-            get
-            {
-                return _connHandler;
-            }
-        }
-
-        internal SqlInternalTransaction CurrentTransaction
-        {
-            get
-            {
-                return _currentTransaction;
-            }
-            set
-            {
-                Debug.Assert(value == _currentTransaction
-                          || null == _currentTransaction
-                          || null == value
-                          || (null != _currentTransaction && !_currentTransaction.IsLocal), "attempting to change current transaction?");
-
-                // If there is currently a transaction active, we don't want to
-                // change it; this can occur when there is a delegated transaction
-                // and the user attempts to do an API begin transaction; in these
-                // cases, it's safe to ignore the set.
-                if ((null == _currentTransaction && null != value)
-                  || (null != _currentTransaction && null == value))
-                {
-                    _currentTransaction = value;
-                }
-            }
-        }
-
-        internal int DefaultLCID
-        {
-            get
-            {
-                return _defaultLCID;
-            }
-        }
-
-        internal EncryptionOptions EncryptionOptions
-        {
-            get
-            {
-                return _encryptionOption;
-            }
-            set
-            {
-                _encryptionOption = value;
-            }
-        }
-
-        internal bool IsKatmaiOrNewer
-        {
-            get
-            {
-                return _isKatmai;
-            }
-        }
-
-        internal bool MARSOn
-        {
-            get
-            {
-                return _fMARS;
-            }
-        }
-
-        internal SqlInternalTransaction PendingTransaction
-        {
-            get
-            {
-                return _pendingTransaction;
-            }
-            set
-            {
-                Debug.Assert(null != value, "setting a non-null PendingTransaction?");
-                _pendingTransaction = value;
-            }
-        }
-
-        internal string Server
-        {
-            get
-            {
-                return _server;
-            }
-        }
-
-        internal TdsParserState State
-        {
-            get
-            {
-                return _state;
-            }
-            set
-            {
-                _state = value;
-            }
-        }
-
-        internal SqlStatistics Statistics
-        {
-            get
-            {
-                return _statistics;
-            }
-            set
-            {
-                _statistics = value;
-            }
-        }
-
-
-
-        internal int IncrementNonTransactedOpenResultCount()
-        {
-            // IMPORTANT - this increments the connection wide open result count for all
-            // operations not under a transaction!  Do not call if you intend to modify the
-            // count for a transaction!
-            Debug.Assert(_nonTransactedOpenResultCount >= 0, "Unexpected result count state");
-            int result = Interlocked.Increment(ref _nonTransactedOpenResultCount);
-            return result;
-        }
-
-        internal void DecrementNonTransactedOpenResultCount()
-        {
-            // IMPORTANT - this decrements the connection wide open result count for all
-            // operations not under a transaction!  Do not call if you intend to modify the
-            // count for a transaction!
-            Interlocked.Decrement(ref _nonTransactedOpenResultCount);
-            Debug.Assert(_nonTransactedOpenResultCount >= 0, "Unexpected result count state");
-        }
-
-        internal void ProcessPendingAck(TdsParserStateObject stateObj)
-        {
-            if (stateObj._attentionSent)
-            {
-                ProcessAttention(stateObj);
-            }
-        }
-
-        internal void Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, bool ignoreSniOpenTimeout, long timerExpire, bool encrypt, bool trustServerCert, bool integratedSecurity, bool withFailover)
-        {
-            if (_state != TdsParserState.Closed)
-            {
-                Debug.Fail("TdsParser.Connect called on non-closed connection!");
-                return;
-            }
-
-            _connHandler = connHandler;
-            _loginWithFailover = withFailover;
-
-            uint sniStatus = TdsParserStateObjectFactory.Singleton.SNIStatus;
-
-            if (sniStatus != TdsEnums.SNI_SUCCESS)
-            {
-                _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-                _physicalStateObj.Dispose();
-                ThrowExceptionAndWarning(_physicalStateObj);
-                Debug.Fail("SNI returned status != success, but no error thrown?");
-            }
-
-            _sniSpnBuffer = null;
-
-            if (integratedSecurity)
-            {
-                LoadSSPILibrary();
-            }
-
-            byte[] instanceName = null;
-
-            Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point.");
-            _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin);
-            _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection);
-
-            bool fParallel = _connHandler.ConnectionOptions.MultiSubnetFailover;
-
-            _physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire,
-                        out instanceName, ref _sniSpnBuffer, false, true, fParallel, integratedSecurity);
-
-            if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status)
-            {
-                _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-
-                // Since connect failed, free the unmanaged connection memory.
-                // HOWEVER - only free this after the netlib error was processed - if you
-                // 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();
-                ThrowExceptionAndWarning(_physicalStateObj);
-                Debug.Fail("SNI returned status != success, but no error thrown?");
-            }
-
-            _server = serverInfo.ResolvedServerName;
-
-            if (null != connHandler.PoolGroupProviderInfo)
-            {
-                // If we are pooling, check to see if we were processing an
-                // alias which has changed, which means we need to clean out
-                // the pool. See Webdata 104293.
-                // This should not apply to routing, as it is not an alias change, routed connection
-                // should still use VNN of AlwaysOn cluster as server for pooling purposes.
-                connHandler.PoolGroupProviderInfo.AliasCheck(serverInfo.PreRoutingServerName == null ?
-                    serverInfo.ResolvedServerName : serverInfo.PreRoutingServerName);
-            }
-            _state = TdsParserState.OpenNotLoggedIn;
-            _physicalStateObj.SniContext = SniContext.Snix_PreLoginBeforeSuccessfulWrite;
-            _physicalStateObj.TimeoutTime = timerExpire;
-
-            bool marsCapable = false;
-
-            _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection);
-            _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
-
-            uint result = _physicalStateObj.SniGetConnectionId(ref _connHandler._clientConnectionId);
-            Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
-
-            SendPreLoginHandshake(instanceName, encrypt);
-
-            _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
-            _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake);
-
-            _physicalStateObj.SniContext = SniContext.Snix_PreLogin;
-
-            PreLoginHandshakeStatus status = ConsumePreLoginHandshake(encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired);
-
-            if (status == PreLoginHandshakeStatus.InstanceFailure)
-            {
-                _physicalStateObj.Dispose(); // Close previous connection
-
-                // On Instance failure re-connect and flush SNI named instance cache.
-                _physicalStateObj.SniContext = SniContext.Snix_Connect;
-
-                _physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire, out instanceName, ref _sniSpnBuffer, true, true, fParallel, integratedSecurity);
-
-                if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status)
-                {
-                    _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-                    ThrowExceptionAndWarning(_physicalStateObj);
-                }
-
-                uint retCode = _physicalStateObj.SniGetConnectionId(ref _connHandler._clientConnectionId);
-
-                Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
-
-                SendPreLoginHandshake(instanceName, encrypt);
-                status = ConsumePreLoginHandshake(encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired);
-
-                // Don't need to check for Sphinx failure, since we've already consumed
-                // one pre-login packet and know we are connecting to Shiloh.
-                if (status == PreLoginHandshakeStatus.InstanceFailure)
-                {
-                    throw SQL.InstanceFailure();
-                }
-            }
-
-            if (_fMARS && marsCapable)
-            {
-                // if user explicitly disables mars or mars not supported, don't create the session pool
-                _sessionPool = new TdsParserSessionPool(this);
-            }
-            else
-            {
-                _fMARS = false;
-            }
-            return;
-        }
-
-        internal void RemoveEncryption()
-        {
-            Debug.Assert(_encryptionOption == EncryptionOptions.LOGIN, "Invalid encryption option state");
-
-            uint error = _physicalStateObj.DisabeSsl();
-
-            if (error != TdsEnums.SNI_SUCCESS)
-            {
-                _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-                ThrowExceptionAndWarning(_physicalStateObj);
-            }
-
-            // create a new packet encryption changes the internal packet size
-            _physicalStateObj.ClearAllWritePackets();
-
-        }
-
-        internal void EnableMars()
-        {
-            if (_fMARS)
-            {
-                // Cache physical stateObj and connection.
-                _pMarsPhysicalConObj = _physicalStateObj;
-
-                if (TdsParserStateObjectFactory.UseManagedSNI)
-                    _pMarsPhysicalConObj.IncrementPendingCallbacks();
-
-                uint info = 0;
-                uint error = _pMarsPhysicalConObj.EnableMars(ref info);
-
-                if (error != TdsEnums.SNI_SUCCESS)
-                {
-                    _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-                    ThrowExceptionAndWarning(_physicalStateObj);
-                }
-
-                PostReadAsyncForMars();
-
-                _physicalStateObj = CreateSession(); // Create and open default MARS stateObj and connection.
-            }
-        }
-
-        internal TdsParserStateObject CreateSession()
-        {
-            return TdsParserStateObjectFactory.Singleton.CreateSessionObject(this, _pMarsPhysicalConObj, true);
-        }
-
-        internal TdsParserStateObject GetSession(object owner)
-        {
-            TdsParserStateObject session = null;
-            if (MARSOn)
-            {
-                session = _sessionPool.GetSession(owner);
-
-                Debug.Assert(!session._pendingData, "pending data on a pooled MARS session");
-            }
-            else
-            {
-                session = _physicalStateObj;
-            }
-            Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1");
-            return session;
-        }
-
-        internal void PutSession(TdsParserStateObject session)
-        {
-            session.AssertStateIsClean();
-
-            if (MARSOn)
-            {
-                // This will take care of disposing if the parser is closed
-                _sessionPool.PutSession(session);
-            }
-            else if ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))
-            {
-                // Parser is closed\broken - dispose the stateObj
-                Debug.Assert(session == _physicalStateObj, "MARS is off, but session to close is not the _physicalStateObj");
-                _physicalStateObj.SniContext = SniContext.Snix_Close;
-#if DEBUG
-                _physicalStateObj.InvalidateDebugOnlyCopyOfSniContext();
-#endif
-                _physicalStateObj.Dispose();
-            }
-            else
-            {
-                // Non-MARS, and session is ok - remove its owner
-                _physicalStateObj.Owner = null;
-            }
-        }
-
-
-        private void SendPreLoginHandshake(byte[] instanceName, bool encrypt)
-        {
-            // PreLoginHandshake buffer consists of:
-            // 1) Standard header, with type = MT_PRELOGIN
-            // 2) Consecutive 5 bytes for each option, (1 byte length, 2 byte offset, 2 byte payload length)
-            // 3) Consecutive data blocks for each option
-
-            // NOTE: packet data needs to be big endian - not the standard little endian used by
-            // the rest of the parser.
-
-            _physicalStateObj._outputMessageType = TdsEnums.MT_PRELOGIN;
-
-            // Initialize option offset into payload buffer
-            // 5 bytes for each option (1 byte length, 2 byte offset, 2 byte payload length)
-            int offset = (int)PreLoginOptions.NUMOPT * 5 + 1;
-
-            byte[] payload = new byte[(int)PreLoginOptions.NUMOPT * 5 + TdsEnums.MAX_PRELOGIN_PAYLOAD_LENGTH];
-            int payloadLength = 0;
-
-            for (int option = (int)PreLoginOptions.VERSION; option < (int)PreLoginOptions.NUMOPT; option++)
-            {
-                int optionDataSize = 0;
-
-                // Fill in the option
-                _physicalStateObj.WriteByte((byte)option);
-
-                // Fill in the offset of the option data
-                _physicalStateObj.WriteByte((byte)((offset & 0xff00) >> 8)); // send upper order byte
-                _physicalStateObj.WriteByte((byte)(offset & 0x00ff)); // send lower order byte
-
-                switch (option)
-                {
-                    case (int)PreLoginOptions.VERSION:
-                        Version systemDataVersion = ADP.GetAssemblyVersion();
-
-                        // Major and minor
-                        payload[payloadLength++] = (byte)(systemDataVersion.Major & 0xff);
-                        payload[payloadLength++] = (byte)(systemDataVersion.Minor & 0xff);
-
-                        // Build (Big Endian)
-                        payload[payloadLength++] = (byte)((systemDataVersion.Build & 0xff00) >> 8);
-                        payload[payloadLength++] = (byte)(systemDataVersion.Build & 0xff);
-
-                        // Sub-build (Little Endian)
-                        payload[payloadLength++] = (byte)(systemDataVersion.Revision & 0xff);
-                        payload[payloadLength++] = (byte)((systemDataVersion.Revision & 0xff00) >> 8);
-                        offset += 6;
-                        optionDataSize = 6;
-                        break;
-
-                    case (int)PreLoginOptions.ENCRYPT:
-                        if (_encryptionOption == EncryptionOptions.NOT_SUP)
-                        {
-                            // If OS doesn't support encryption, inform server not supported.
-                            payload[payloadLength] = (byte)EncryptionOptions.NOT_SUP;
-                        }
-                        else
-                        {
-                            // Else, inform server of user request.
-                            if (encrypt)
-                            {
-                                payload[payloadLength] = (byte)EncryptionOptions.ON;
-                                _encryptionOption = EncryptionOptions.ON;
-                            }
-                            else
-                            {
-                                payload[payloadLength] = (byte)EncryptionOptions.OFF;
-                                _encryptionOption = EncryptionOptions.OFF;
-                            }
-                        }
-
-                        payloadLength += 1;
-                        offset += 1;
-                        optionDataSize = 1;
-                        break;
-
-                    case (int)PreLoginOptions.INSTANCE:
-                        int i = 0;
-
-                        while (instanceName[i] != 0)
-                        {
-                            payload[payloadLength] = instanceName[i];
-                            payloadLength++;
-                            i++;
-                        }
-
-                        payload[payloadLength] = 0; // null terminate
-                        payloadLength++;
-                        i++;
-
-                        offset += i;
-                        optionDataSize = i;
-                        break;
-
-                    case (int)PreLoginOptions.THREADID:
-                        int threadID = TdsParserStaticMethods.GetCurrentThreadIdForTdsLoginOnly();
-
-                        payload[payloadLength++] = (byte)((0xff000000 & threadID) >> 24);
-                        payload[payloadLength++] = (byte)((0x00ff0000 & threadID) >> 16);
-                        payload[payloadLength++] = (byte)((0x0000ff00 & threadID) >> 8);
-                        payload[payloadLength++] = (byte)(0x000000ff & threadID);
-                        offset += 4;
-                        optionDataSize = 4;
-                        break;
-
-                    case (int)PreLoginOptions.MARS:
-                        payload[payloadLength++] = (byte)(_fMARS ? 1 : 0);
-                        offset += 1;
-                        optionDataSize += 1;
-                        break;
-
-                    case (int)PreLoginOptions.TRACEID:
-                        FillGuidBytes(_connHandler._clientConnectionId, payload.AsSpan(payloadLength, GUID_SIZE));
-                        payloadLength += GUID_SIZE;
-                        offset += GUID_SIZE;
-                        optionDataSize = GUID_SIZE;
-
-                        ActivityCorrelator.ActivityId actId = ActivityCorrelator.Next();
-                        FillGuidBytes(actId.Id, payload.AsSpan(payloadLength, GUID_SIZE));
-                        payloadLength += GUID_SIZE;
-                        payload[payloadLength++] = (byte)(0x000000ff & actId.Sequence);
-                        payload[payloadLength++] = (byte)((0x0000ff00 & actId.Sequence) >> 8);
-                        payload[payloadLength++] = (byte)((0x00ff0000 & actId.Sequence) >> 16);
-                        payload[payloadLength++] = (byte)((0xff000000 & actId.Sequence) >> 24);
-                        int actIdSize = GUID_SIZE + sizeof(uint);
-                        offset += actIdSize;
-                        optionDataSize += actIdSize;
-                        break;
-
-                    case (int)PreLoginOptions.FEDAUTHREQUIRED:
-                        payload[payloadLength++] = 0x01;
-                        offset += 1;
-                        optionDataSize += 1;
-                        break;
-
-                    default:
-                        Debug.Fail("UNKNOWN option in SendPreLoginHandshake");
-                        break;
-                }
-
-                // Write data length
-                _physicalStateObj.WriteByte((byte)((optionDataSize & 0xff00) >> 8));
-                _physicalStateObj.WriteByte((byte)(optionDataSize & 0x00ff));
-            }
-
-            // Write out last option - to let server know the second part of packet completed
-            _physicalStateObj.WriteByte((byte)PreLoginOptions.LASTOPT);
-
-            // Write out payload
-            _physicalStateObj.WriteByteArray(payload, payloadLength, 0);
-
-            // Flush packet
-            _physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
-        }
-
-        private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trustServerCert, bool integratedSecurity, out bool marsCapable, out bool fedAuthRequired)
-        {
-            marsCapable = _fMARS; // Assign default value
-            fedAuthRequired = false;
-            bool isYukonOrLater = false;
-            Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = _physicalStateObj.TryReadNetworkPacket();
-            if (!result)
-            { throw SQL.SynchronousCallMayNotPend(); }
-
-            if (_physicalStateObj._inBytesRead == 0)
-            {
-                // If the server did not respond then something has gone wrong and we need to close the connection
-                _physicalStateObj.AddError(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.PreloginError(), "", 0));
-                _physicalStateObj.Dispose();
-                ThrowExceptionAndWarning(_physicalStateObj);
-            }
-
-            if (!_physicalStateObj.TryProcessHeader())
-            { throw SQL.SynchronousCallMayNotPend(); }
-
-            if (_physicalStateObj._inBytesPacket > TdsEnums.MAX_PACKET_SIZE || _physicalStateObj._inBytesPacket <= 0)
-            {
-                throw SQL.ParsingError();
-            }
-            byte[] payload = new byte[_physicalStateObj._inBytesPacket];
-
-            Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            result = _physicalStateObj.TryReadByteArray(payload, payload.Length);
-            if (!result)
-            { throw SQL.SynchronousCallMayNotPend(); }
-
-            if (payload[0] == 0xaa)
-            {
-                // If the first byte is 0xAA, we are connecting to a 6.5 or earlier server, which
-                // is not supported.
-                throw SQL.InvalidSQLServerVersionUnknown();
-            }
-
-            int offset = 0;
-            int payloadOffset = 0;
-            int payloadLength = 0;
-            int option = payload[offset++];
-
-            while (option != (byte)PreLoginOptions.LASTOPT)
-            {
-                switch (option)
-                {
-                    case (int)PreLoginOptions.VERSION:
-                        payloadOffset = payload[offset++] << 8 | payload[offset++];
-                        payloadLength = payload[offset++] << 8 | payload[offset++];
-
-                        byte majorVersion = payload[payloadOffset];
-                        isYukonOrLater = majorVersion >= 9;
-                        if (!isYukonOrLater)
-                        {
-                            marsCapable = false;            // If pre-Yukon, MARS not supported.
-                        }
-
-                        break;
-
-                    case (int)PreLoginOptions.ENCRYPT:
-                        payloadOffset = payload[offset++] << 8 | payload[offset++];
-                        payloadLength = payload[offset++] << 8 | payload[offset++];
-
-                        EncryptionOptions serverOption = (EncryptionOptions)payload[payloadOffset];
-
-                        /* internal enum EncryptionOptions {
-                            OFF,
-                            ON,
-                            NOT_SUP,
-                            REQ,
-                            LOGIN
-                        } */
-
-                        switch (_encryptionOption)
-                        {
-                            case (EncryptionOptions.ON):
-                                if (serverOption == EncryptionOptions.NOT_SUP)
-                                {
-                                    _physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByServer(), "", 0));
-                                    _physicalStateObj.Dispose();
-                                    ThrowExceptionAndWarning(_physicalStateObj);
-                                }
-
-                                break;
-
-                            case (EncryptionOptions.OFF):
-                                if (serverOption == EncryptionOptions.OFF)
-                                {
-                                    // Only encrypt login.
-                                    _encryptionOption = EncryptionOptions.LOGIN;
-                                }
-                                else if (serverOption == EncryptionOptions.REQ)
-                                {
-                                    // Encrypt all.
-                                    _encryptionOption = EncryptionOptions.ON;
-                                }
-
-                                break;
-
-                            case (EncryptionOptions.NOT_SUP):
-                                if (serverOption == EncryptionOptions.REQ)
-                                {
-                                    _physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByClient(), "", 0));
-                                    _physicalStateObj.Dispose();
-                                    ThrowExceptionAndWarning(_physicalStateObj);
-                                }
-
-                                break;
-
-                            default:
-                                Debug.Fail("Invalid client encryption option detected");
-                                break;
-                        }
-
-                        if (_encryptionOption == EncryptionOptions.ON ||
-                            _encryptionOption == EncryptionOptions.LOGIN)
-                        {
-                            uint error = 0;
-                            // If we're using legacy server certificate validation behavior (not using access token), then validate if Encrypt=true and Trust Sever Certificate = false.
-                            // If using access token, validate if Trust Server Certificate=false.
-                            bool shouldValidateServerCert = (encrypt && !trustServerCert) || (_connHandler._accessTokenInBytes != null && !trustServerCert);
-                            uint info = (shouldValidateServerCert ? TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE : 0)
-                                | (isYukonOrLater ? TdsEnums.SNI_SSL_USE_SCHANNEL_CACHE : 0);
-
-                            if (encrypt && !integratedSecurity)
-                            {
-                                // optimization: in case of SQL Authentication and encryption, set SNI_SSL_IGNORE_CHANNEL_BINDINGS to let SNI
-                                // know that it does not need to allocate/retrieve the Channel Bindings from the SSL context.
-                                // This applies to Native SNI
-                                info |= TdsEnums.SNI_SSL_IGNORE_CHANNEL_BINDINGS;
-                            }
-
-                            error = _physicalStateObj.EnableSsl(ref info);
-
-                            if (error != TdsEnums.SNI_SUCCESS)
-                            {
-                                _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
-                                ThrowExceptionAndWarning(_physicalStateObj);
-                            }
-
-                            WaitForSSLHandShakeToComplete(ref error);
-
-                            // create a new packet encryption changes the internal packet size
-                            _physicalStateObj.ClearAllWritePackets();
-                        }
-
-                        break;
-
-                    case (int)PreLoginOptions.INSTANCE:
-                        payloadOffset = payload[offset++] << 8 | payload[offset++];
-                        payloadLength = payload[offset++] << 8 | payload[offset++];
-
-                        byte ERROR_INST = 0x1;
-                        byte instanceResult = payload[payloadOffset];
-
-                        if (instanceResult == ERROR_INST)
-                        {
-                            // Check if server says ERROR_INST. That either means the cached info
-                            // we used to connect is not valid or we connected to a named instance
-                            // listening on default params.
-                            return PreLoginHandshakeStatus.InstanceFailure;
-                        }
-
-                        break;
-
-                    case (int)PreLoginOptions.THREADID:
-                        // DO NOTHING FOR THREADID
-                        offset += 4;
-                        break;
-
-                    case (int)PreLoginOptions.MARS:
-                        payloadOffset = payload[offset++] << 8 | payload[offset++];
-                        payloadLength = payload[offset++] << 8 | payload[offset++];
-
-                        marsCapable = (payload[payloadOffset] == 0 ? false : true);
-
-                        Debug.Assert(payload[payloadOffset] == 0 || payload[payloadOffset] == 1, "Value for Mars PreLoginHandshake option not equal to 1 or 0!");
-                        break;
-
-                    case (int)PreLoginOptions.TRACEID:
-                        // DO NOTHING FOR TRACEID
-                        offset += 4;
-                        break;
-
-                    case (int)PreLoginOptions.FEDAUTHREQUIRED:
-                        payloadOffset = payload[offset++] << 8 | payload[offset++];
-                        payloadLength = payload[offset++] << 8 | payload[offset++];
-
-                        // Only 0x00 and 0x01 are accepted values from the server.
-                        if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01)
-                        {
-                            throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]);
-                        }
-
-                        // We must NOT use the response for the FEDAUTHREQUIRED PreLogin option, if AccessToken is not null, meaning token based authentication is used.
-                        if (_connHandler.ConnectionOptions != null || _connHandler._accessTokenInBytes != null)
-                        {
-                            fedAuthRequired = payload[payloadOffset] == 0x01 ? true : false;
-                        }
-                        break;
-
-                    default:
-                        Debug.Fail("UNKNOWN option in ConsumePreLoginHandshake, option:" + option);
-
-                        // DO NOTHING FOR THESE UNKNOWN OPTIONS
-                        offset += 4;
-
-                        break;
-                }
-
-                if (offset < payload.Length)
-                {
-                    option = payload[offset++];
-                }
-                else
-                {
-                    break;
-                }
-            }
-
-            return PreLoginHandshakeStatus.Successful;
-        }
-
-        internal void Deactivate(bool connectionIsDoomed)
-        {
-            // Called when the connection that owns us is deactivated.
-
-
-            if (MARSOn)
-            {
-                _sessionPool.Deactivate();
-            }
-
-            Debug.Assert(connectionIsDoomed || null == _pendingTransaction, "pending transaction at disconnect?");
-
-            if (!connectionIsDoomed && null != _physicalStateObj)
-            {
-                if (_physicalStateObj._pendingData)
-                {
-                    DrainData(_physicalStateObj);
-                }
-
-                if (_physicalStateObj.HasOpenResult)
-                { // Need to decrement openResultCount for all pending operations.
-                    _physicalStateObj.DecrementOpenResultCount();
-                }
-            }
-
-            // Any active, non-distributed transaction must be rolled back.  We
-            // need to wait for distributed transactions to be completed by the
-            // transaction manager -- we don't want to automatically roll them
-            // back.
-            //
-            // Note that when there is a transaction delegated to this connection,
-            // we will defer the deactivation of this connection until the
-            // transaction manager completes the transaction.
-            SqlInternalTransaction currentTransaction = CurrentTransaction;
-
-            if (null != currentTransaction && currentTransaction.HasParentTransaction)
-            {
-                currentTransaction.CloseFromConnection();
-                Debug.Assert(null == CurrentTransaction, "rollback didn't clear current transaction?");
-            }
-
-            Statistics = null; // must come after CleanWire or we won't count the stuff that happens there...
-        }
-
-        // Used to close the connection and then free the memory allocated for the netlib connection.
-        internal void Disconnect()
-        {
-            if (null != _sessionPool)
-            {
-                // MARSOn may be true, but _sessionPool not yet created
-                _sessionPool.Dispose();
-            }
-
-            // Can close the connection if its open or broken
-            if (_state != TdsParserState.Closed)
-            {
-                //benign assert - the user could close the connection before consuming all the data
-                //Debug.Assert(_physicalStateObj._inBytesUsed == _physicalStateObj._inBytesRead && _physicalStateObj._outBytesUsed == _physicalStateObj._inputHeaderLen, "TDSParser closed with data not fully sent or consumed.");
-
-                _state = TdsParserState.Closed;
-
-                try
-                {
-                    // If the _physicalStateObj has an owner, we will delay the disposal until the owner is finished with it
-                    if (!_physicalStateObj.HasOwner)
-                    {
-                        _physicalStateObj.SniContext = SniContext.Snix_Close;
-#if DEBUG
-                        _physicalStateObj.InvalidateDebugOnlyCopyOfSniContext();
-#endif
-                        _physicalStateObj.Dispose();
-                    }
-                    else
-                    {
-                        // Remove the "initial" callback (this will allow the stateObj to be GC collected if need be)
-                        _physicalStateObj.DecrementPendingCallbacks(false);
-                    }
-
-                    // Not allocated until MARS is actually enabled in SNI.
-                    if (null != _pMarsPhysicalConObj)
-                    {
-                        _pMarsPhysicalConObj.Dispose();
-                    }
-                }
-                finally
-                {
-                    _pMarsPhysicalConObj = null;
-                }
-            }
-
-            _resetConnectionEvent?.Dispose();
-            _resetConnectionEvent = null;
-
-            _defaultEncoding = null;
-            _defaultCollation = null;
-        }
-
-        // Fires a single InfoMessageEvent
-        private void FireInfoMessageEvent(SqlConnection connection, TdsParserStateObject stateObj, SqlError error)
-        {
-            string serverVersion = null;
-
-            Debug.Assert(connection != null && _connHandler.Connection == connection);
-
-            if (_state == TdsParserState.OpenLoggedIn)
-            {
-                serverVersion = _connHandler.ServerVersion;
-            }
-
-            SqlErrorCollection sqlErs = new SqlErrorCollection();
-
-            sqlErs.Add(error);
-
-            SqlException exc = SqlException.CreateException(sqlErs, serverVersion, _connHandler);
-
-            bool notified;
-            connection.OnInfoMessage(new SqlInfoMessageEventArgs(exc), out notified);
-            if (notified)
-            {
-                // observable side-effects, no retry
-                stateObj._syncOverAsync = true;
-            }
-            return;
-        }
-
-        internal void DisconnectTransaction(SqlInternalTransaction internalTransaction)
-        {
-            Debug.Assert(_currentTransaction != null && _currentTransaction == internalTransaction, "disconnecting different transaction");
-
-            if (_currentTransaction != null && _currentTransaction == internalTransaction)
-            {
-                _currentTransaction = null;
-            }
-        }
-
-        internal void RollbackOrphanedAPITransactions()
-        {
-            // Any active, non-distributed transaction must be rolled back.
-            SqlInternalTransaction currentTransaction = CurrentTransaction;
-
-            if (null != currentTransaction && currentTransaction.HasParentTransaction && currentTransaction.IsOrphaned)
-            {
-                currentTransaction.CloseFromConnection();
-                Debug.Assert(null == CurrentTransaction, "rollback didn't clear current transaction?");
-            }
-        }
-
-        internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool callerHasConnectionLock = false, bool asyncClose = false)
-        {
-            Debug.Assert(!callerHasConnectionLock || _connHandler._parserLock.ThreadMayHaveLock(), "Caller claims to have lock, but connection lock is not taken");
-
-            SqlException exception = null;
-            bool breakConnection;
-
-            // This function should only be called when there was an error or warning.  If there aren't any
-            // errors, the handler will be called for the warning(s).  If there was an error, the warning(s) will
-            // 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)
-            SqlErrorCollection temp = stateObj.GetFullErrorAndWarningCollection(out breakConnection);
-
-            Debug.Assert(temp != null, "TdsParser::ThrowExceptionAndWarning: null errors collection!");
-            Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!");
-            Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!");
-
-            // Don't break the connection if it is already closed
-            breakConnection &= (TdsParserState.Closed != _state);
-            if (breakConnection)
-            {
-                if ((_state == TdsParserState.OpenNotLoggedIn) && (_connHandler.ConnectionOptions.MultiSubnetFailover || _loginWithFailover) && (temp.Count == 1) && ((temp[0].Number == TdsEnums.TIMEOUT_EXPIRED) || (temp[0].Number == TdsEnums.SNI_WAIT_TIMEOUT)))
-                {
-                    // For Multisubnet Failover we slice the timeout to make reconnecting faster (with the assumption that the server will not failover instantaneously)
-                    // However, when timeout occurs we need to not doom the internal connection and also to mark the TdsParser as closed such that the login will be will retried
-                    breakConnection = false;
-                    Disconnect();
-                }
-                else
-                {
-                    _state = TdsParserState.Broken;
-                }
-            }
-
-            if (temp != null && temp.Count > 0)
-            {
-                // Construct the exception now that we've collected all the errors
-                string serverVersion = null;
-                if (_state == TdsParserState.OpenLoggedIn)
-                {
-                    serverVersion = _connHandler.ServerVersion;
-                }
-
-                if (temp.Count == 1 && temp[0].Exception != null)
-                {
-                    exception = SqlException.CreateException(temp, serverVersion, _connHandler, temp[0].Exception);
-                }
-                else
-                {
-                    exception = SqlException.CreateException(temp, serverVersion, _connHandler);
-                }
-            }
-
-            // call OnError outside of _ErrorCollectionLock to avoid deadlock
-            if (exception != null)
-            {
-                if (breakConnection)
-                {
-                    // report exception to pending async operation
-                    // before OnConnectionClosed overrides the exception
-                    // due to connection close notification through references
-                    var taskSource = stateObj._networkPacketTaskSource;
-                    if (taskSource != null)
-                    {
-                        taskSource.TrySetException(ADP.ExceptionWithStackTrace(exception));
-                    }
-                }
-
-                if (asyncClose)
-                {
-                    // Wait until we have the parser lock, then try to close
-                    var connHandler = _connHandler;
-                    Action<Action> wrapCloseAction = closeAction =>
-                    {
-                        Task.Run(() =>
-                        {
-                            connHandler._parserLock.Wait(canReleaseFromAnyThread: false);
-                            connHandler.ThreadHasParserLockForClose = true;
-                            try
-                            {
-                                closeAction();
-                            }
-                            finally
-                            {
-                                connHandler.ThreadHasParserLockForClose = false;
-                                connHandler._parserLock.Release();
-                            }
-                        });
-                    };
-
-                    _connHandler.OnError(exception, breakConnection, wrapCloseAction);
-                }
-                else
-                {
-                    // Let close know that we already have the _parserLock
-                    bool threadAlreadyHadParserLockForClose = _connHandler.ThreadHasParserLockForClose;
-                    if (callerHasConnectionLock)
-                    {
-                        _connHandler.ThreadHasParserLockForClose = true;
-                    }
-                    try
-                    {
-                        // the following handler will throw an exception or generate a warning event
-                        _connHandler.OnError(exception, breakConnection);
-                    }
-                    finally
-                    {
-                        if (callerHasConnectionLock)
-                        {
-                            _connHandler.ThreadHasParserLockForClose = threadAlreadyHadParserLockForClose;
-                        }
-                    }
-                }
-            }
-        }
-
-        internal SqlError ProcessSNIError(TdsParserStateObject stateObj)
-        {
-#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");
-#endif
-            SNIErrorDetails details = GetSniErrorDetails();
-
-            if (details.sniErrorNumber != 0)
-            {
-                // handle special SNI error codes that are converted into exception which is not a SqlException.
-                switch (details.sniErrorNumber)
-                {
-                    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.
-                        throw SQL.MultiSubnetFailoverWithMoreThan64IPs();
-
-                    case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified:
-                        // 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.
-                        throw SQL.MultiSubnetFailoverWithNonTcpProtocol();
-                        // continue building SqlError instance
-                }
-            }
-            // PInvoke code automatically sets the length of the string for us
-            // So no need to look for \0
-            string errorMessage = details.errorMessage;
-
-            //  Format SNI errors and add Context Information
-            //
-            //  General syntax is:
-            //  <sqlclient message>
-            //  (provider:<SNIx provider>, error: <SNIx error code> - <SNIx error message>)
-            //
-            // errorMessage | sniError |
-            // -------------------------------------------
-            // ==null       | x        | must never happen
-            // !=null       | != 0     | retrieve corresponding errorMessage from resources
-            // !=null       | == 0     | replace text left of errorMessage
-            //
-
-            if (TdsParserStateObjectFactory.UseManagedSNI)
-                Debug.Assert(!string.IsNullOrEmpty(details.errorMessage) || details.sniErrorNumber != 0, "Empty error message received from SNI");
-            else
-                Debug.Assert(!string.IsNullOrEmpty(details.errorMessage), "Empty error message received from SNI");
-
-            string sniContextEnumName = TdsEnums.GetSniContextEnumName(stateObj.SniContext);
-
-            string sqlContextInfo = SR.GetResourceString(sniContextEnumName, sniContextEnumName);
-            string providerRid = string.Format("SNI_PN{0}", details.provider);
-            string providerName = SR.GetResourceString(providerRid, providerRid);
-            Debug.Assert(!string.IsNullOrEmpty(providerName), $"invalid providerResourceId '{providerRid}'");
-            uint win32ErrorCode = details.nativeError;
-
-            if (details.sniErrorNumber == 0)
-            {
-                // Provider error. The message from provider is preceded with non-localizable info from SNI
-                // strip provider info from SNI
-                //
-                int iColon = errorMessage.IndexOf(':');
-                Debug.Assert(0 <= iColon, "':' character missing in sni errorMessage");
-                Debug.Assert(errorMessage.Length > iColon + 1 && errorMessage[iColon + 1] == ' ', "Expecting a space after the ':' character");
-
-                // extract the message excluding the colon and trailing cr/lf chars
-                if (0 <= iColon)
-                {
-                    int len = errorMessage.Length;
-                    len -= Environment.NewLine.Length; // exclude newline sequence
-                    iColon += 2;  // skip over ": " sequence
-                    len -= iColon;
-                    /*
-                        The error message should come back in the following format: "TCP Provider: MESSAGE TEXT"
-                        If the message is received on a Win9x OS, the error message will not contain MESSAGE TEXT
-                        If we get an error message with no message text, just return the entire message otherwise
-                        return just the message text.
-                    */
-                    if (len > 0)
-                    {
-                        errorMessage = errorMessage.Substring(iColon, len);
-                    }
-                }
-            }
-            else
-            {
-
-                if (TdsParserStateObjectFactory.UseManagedSNI)
-                {
-                    // SNI error. Append additional error message info if available.
-                    //
-                    string sniLookupMessage = SQL.GetSNIErrorMessage((int)details.sniErrorNumber);
-                    errorMessage = (errorMessage != string.Empty) ?
-                                    (sniLookupMessage + ": " + errorMessage) :
-                                    sniLookupMessage;
-                }
-                else
-                {
-                    // SNI error. Replace the entire message.
-                    //
-                    errorMessage = SQL.GetSNIErrorMessage((int)details.sniErrorNumber);
-
-                    // If its a LocalDB error, then nativeError actually contains a LocalDB-specific error code, not a win32 error code
-                    if (details.sniErrorNumber == (int)SNINativeMethodWrapper.SniSpecialErrors.LocalDBErrorCode)
-                    {
-                        errorMessage += LocalDBAPI.GetLocalDBMessage((int)details.nativeError);
-                        win32ErrorCode = 0;
-                    }
-                }
-            }
-            errorMessage = string.Format("{0} (provider: {1}, error: {2} - {3})",
-                sqlContextInfo, providerName, (int)details.sniErrorNumber, errorMessage);
-
-            return new SqlError((int)details.nativeError, 0x00, TdsEnums.FATAL_ERROR_CLASS,
-                                _server, errorMessage, details.function, (int)details.lineNumber, details.nativeError, details.exception);
-        }
-
-        internal void CheckResetConnection(TdsParserStateObject stateObj)
-        {
-            if (_fResetConnection && !stateObj._fResetConnectionSent)
-            {
-                Debug.Assert(stateObj._outputPacketNumber == 1 || stateObj._outputPacketNumber == 2, "In ResetConnection logic unexpectedly!");
-                try
-                {
-                    if (_fMARS && !stateObj._fResetEventOwned)
-                    {
-                        // If using Async & MARS and we do not own ResetEvent - grab it.  We need to not grab lock here
-                        // for case where multiple packets are sent to server from one execute.
-                        stateObj._fResetEventOwned = _resetConnectionEvent.WaitOne(stateObj.GetTimeoutRemaining());
-
-                        if (stateObj._fResetEventOwned)
-                        {
-                            if (stateObj.TimeoutHasExpired)
-                            {
-                                // We didn't timeout on the WaitOne, but we timed out by the time we decremented stateObj._timeRemaining.
-                                stateObj._fResetEventOwned = !_resetConnectionEvent.Set();
-                                stateObj.TimeoutTime = 0;
-                            }
-                        }
-
-                        if (!stateObj._fResetEventOwned)
-                        {
-                            // We timed out waiting for ResetEvent.  Throw timeout exception and reset
-                            // the buffer.  Nothing else to do since we did not actually send anything
-                            // to the server.
-                            stateObj.ResetBuffer();
-                            Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point.");
-                            stateObj.AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _server, _connHandler.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
-                            Debug.Assert(_connHandler._parserLock.ThreadMayHaveLock(), "Thread is writing without taking the connection lock");
-                            ThrowExceptionAndWarning(stateObj, callerHasConnectionLock: true);
-                        }
-                    }
-
-                    if (_fResetConnection)
-                    {
-                        // Check again to see if we need to send reset.
-
-                        Debug.Assert(!stateObj._fResetConnectionSent, "Unexpected state for sending reset connection");
-
-                        if (_fPreserveTransaction)
-                        {
-                            // if we are reseting, set bit in header by or'ing with other value
-                            stateObj._outBuff[1] = (byte)(stateObj._outBuff[1] | TdsEnums.ST_RESET_CONNECTION_PRESERVE_TRANSACTION);
-                        }
-                        else
-                        {
-                            // if we are reseting, set bit in header by or'ing with other value
-                            stateObj._outBuff[1] = (byte)(stateObj._outBuff[1] | TdsEnums.ST_RESET_CONNECTION);
-                        }
-
-                        if (!_fMARS)
-                        {
-                            _fResetConnection = false; // If not MARS, can turn off flag now.
-                            _fPreserveTransaction = false;
-                        }
-                        else
-                        {
-                            stateObj._fResetConnectionSent = true; // Otherwise set flag so we don't resend on multiple packet execute.
-                        }
-                    }
-                    else if (_fMARS && stateObj._fResetEventOwned)
-                    {
-                        Debug.Assert(!stateObj._fResetConnectionSent, "Unexpected state on WritePacket ResetConnection");
-
-                        // Otherwise if Yukon and we grabbed the event, free it.  Another execute grabbed the event and
-                        // took care of sending the reset.
-                        stateObj._fResetEventOwned = !_resetConnectionEvent.Set();
-                        Debug.Assert(!stateObj._fResetEventOwned, "Invalid AutoResetEvent state!");
-                    }
-                }
-                catch (Exception)
-                {
-                    if (_fMARS && stateObj._fResetEventOwned)
-                    {
-                        // If exception thrown, and we are on Yukon and own the event, release it!
-                        stateObj._fResetConnectionSent = false;
-                        stateObj._fResetEventOwned = !_resetConnectionEvent.Set();
-                        Debug.Assert(!stateObj._fResetEventOwned, "Invalid AutoResetEvent state!");
-                    }
-
-                    throw;
-                }
-            }
-#if DEBUG
-            else
-            {
-                Debug.Assert(!_fResetConnection ||
-                             (_fResetConnection && stateObj._fResetConnectionSent && stateObj._fResetEventOwned),
-                             "Unexpected state on else ResetConnection block in WritePacket");
-            }
-#endif
-        }
-
-        //
-        // Takes a 16 bit short and writes it.
-        //
-        internal void WriteShort(int v, TdsParserStateObject stateObj)
-        {
-            if ((stateObj._outBytesUsed + 2) > stateObj._outBuff.Length)
-            {
-                // if all of the short doesn't fit into the buffer
-                stateObj.WriteByte((byte)(v & 0xff));
-                stateObj.WriteByte((byte)((v >> 8) & 0xff));
-            }
-            else
-            {
-                // all of the short fits into the buffer
-                stateObj._outBuff[stateObj._outBytesUsed] = (byte)(v & 0xff);
-                stateObj._outBuff[stateObj._outBytesUsed + 1] = (byte)((v >> 8) & 0xff);
-                stateObj._outBytesUsed += 2;
-            }
-        }
-
-        internal void WriteUnsignedShort(ushort us, TdsParserStateObject stateObj)
-        {
-            WriteShort((short)us, stateObj);
-        }
-
-        //
-        // Takes a long and writes out an unsigned int
-        //
-        internal void WriteUnsignedInt(uint i, TdsParserStateObject stateObj)
-        {
-            WriteInt((int)i, stateObj);
-        }
-
-        //
-        // Takes an int and writes it as an int.
-        //
-        internal void WriteInt(int v, TdsParserStateObject stateObj)
-        {
-            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)
-                {
-                    stateObj.WriteByte((byte)((v >> shiftValue) & 0xff));
-                }
-            }
-            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);
-                stateObj._outBytesUsed += 4;
-            }
-        }
-
-        //
-        // Takes a float and writes it as a 32 bit float.
-        //
-        internal void WriteFloat(float v, TdsParserStateObject stateObj)
-        {
-            Span<byte> bytes = stackalloc byte[sizeof(float)];
-            FillFloatBytes(v, bytes);
-            stateObj.WriteByteSpan(bytes);
-        }
-
-        //
-        // Takes a long and writes it as a long.
-        //
-        internal void WriteLong(long v, TdsParserStateObject stateObj)
-        {
-            if ((stateObj._outBytesUsed + 8) > stateObj._outBuff.Length)
-            {
-                // if all of the long doesn't fit into the buffer
-                for (int shiftValue = 0; shiftValue < sizeof(long) * 8; shiftValue += 8)
-                {
-                    stateObj.WriteByte((byte)((v >> shiftValue) & 0xff));
-                }
-            }
-            else
-            {
-                // all of the long 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);
-                stateObj._outBuff[stateObj._outBytesUsed + 4] = (byte)((v >> 32) & 0xff);
-                stateObj._outBuff[stateObj._outBytesUsed + 5] = (byte)((v >> 40) & 0xff);
-                stateObj._outBuff[stateObj._outBytesUsed + 6] = (byte)((v >> 48) & 0xff);
-                stateObj._outBuff[stateObj._outBytesUsed + 7] = (byte)((v >> 56) & 0xff);
-                stateObj._outBytesUsed += 8;
-            }
-        }
-
-        //
-        // Takes a long and writes part of it
-        //
-        internal void WritePartialLong(long v, int length, TdsParserStateObject stateObj)
-        {
-            Debug.Assert(length <= 8, "Length specified is longer than the size of a long");
-            Debug.Assert(length >= 0, "Length should not be negative");
-
-            if ((stateObj._outBytesUsed + length) > stateObj._outBuff.Length)
-            {
-                // if all of the long doesn't fit into the buffer
-                for (int shiftValue = 0; shiftValue < length * 8; shiftValue += 8)
-                {
-                    stateObj.WriteByte((byte)((v >> shiftValue) & 0xff));
-                }
-            }
-            else
-            {
-                // all of the long fits into the buffer
-                for (int index = 0; index < length; index++)
-                {
-                    stateObj._outBuff[stateObj._outBytesUsed + index] = (byte)((v >> (index * 8)) & 0xff);
-                }
-                stateObj._outBytesUsed += length;
-            }
-        }
-
-        //
-        // Takes a ulong and writes it as a ulong.
-        //
-        internal void WriteUnsignedLong(ulong uv, TdsParserStateObject stateObj)
-        {
-            WriteLong((long)uv, stateObj);
-        }
-
-        //
-        // Takes a double and writes it as a 64 bit double.
-        //
-        internal void WriteDouble(double v, TdsParserStateObject stateObj)
-        {
-            Span<byte> bytes = stackalloc byte[sizeof(double)];
-            FillDoubleBytes(v, bytes);
-            stateObj.WriteByteSpan(bytes);
-
-        }
-
-        internal void PrepareResetConnection(bool preserveTransaction)
-        {
-            // Set flag to reset connection upon next use - only for use on shiloh!
-            _fResetConnection = true;
-            _fPreserveTransaction = preserveTransaction;
-        }
-
-
-
-        internal bool Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
-        {
-            bool syncOverAsync = stateObj._syncOverAsync;
-            try
-            {
-                stateObj._syncOverAsync = true;
-
-                bool dataReady;
-                bool result = TryRun(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj, out dataReady);
-                Debug.Assert(result == true, "Should never return false when _syncOverAsync is set");
-                return dataReady;
-            }
-            finally
-            {
-                stateObj._syncOverAsync = syncOverAsync;
-            }
-        }
-
-        /// <summary>
-        /// Checks if the given token is a valid TDS token
-        /// </summary>
-        /// <param name="token">Token to check</param>
-        /// <returns>True if the token is a valid TDS token, otherwise false</returns>
-        internal static bool IsValidTdsToken(byte token)
-        {
-            return (
-                token == TdsEnums.SQLERROR ||
-                token == TdsEnums.SQLINFO ||
-                token == TdsEnums.SQLLOGINACK ||
-                token == TdsEnums.SQLENVCHANGE ||
-                token == TdsEnums.SQLRETURNVALUE ||
-                token == TdsEnums.SQLRETURNSTATUS ||
-                token == TdsEnums.SQLCOLNAME ||
-                token == TdsEnums.SQLCOLFMT ||
-                token == TdsEnums.SQLCOLMETADATA ||
-                token == TdsEnums.SQLALTMETADATA ||
-                token == TdsEnums.SQLTABNAME ||
-                token == TdsEnums.SQLCOLINFO ||
-                token == TdsEnums.SQLORDER ||
-                token == TdsEnums.SQLALTROW ||
-                token == TdsEnums.SQLROW ||
-                token == TdsEnums.SQLNBCROW ||
-                token == TdsEnums.SQLDONE ||
-                token == TdsEnums.SQLDONEPROC ||
-                token == TdsEnums.SQLDONEINPROC ||
-                token == TdsEnums.SQLROWCRC ||
-                token == TdsEnums.SQLSECLEVEL ||
-                token == TdsEnums.SQLPROCID ||
-                token == TdsEnums.SQLOFFSET ||
-                token == TdsEnums.SQLSSPI ||
-                token == TdsEnums.SQLFEATUREEXTACK ||
-                token == TdsEnums.SQLSESSIONSTATE);
-        }
-
-        // Main parse loop for the top-level tds tokens, calls back into the I*Handler interfaces
-        internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, out bool dataReady)
-        {
-            Debug.Assert((SniContext.Undefined != stateObj.SniContext) &&       // SniContext must not be Undefined
-                ((stateObj._attentionSent) || ((SniContext.Snix_Execute != stateObj.SniContext) && (SniContext.Snix_SendRows != stateObj.SniContext))),  // SniContext should not be Execute or SendRows unless attention was sent (and, therefore, we are looking for an ACK)
-                        $"Unexpected SniContext on call to TryRun; SniContext={stateObj.SniContext}");
-
-            if (TdsParserState.Broken == State || TdsParserState.Closed == State)
-            {
-                dataReady = true;
-                return true; // Just in case this is called in a loop, expecting data to be returned.
-            }
-
-            dataReady = false;
-
-            do
-            {
-                // If there is data ready, but we didn't exit the loop, then something is wrong
-                Debug.Assert(!dataReady, "dataReady not expected - did we forget to skip the row?");
-
-                if (stateObj._internalTimeout)
-                {
-                    runBehavior = RunBehavior.Attention;
-                }
-
-                if (TdsParserState.Broken == State || TdsParserState.Closed == State)
-                    break; // jump out of the loop if the state is already broken or closed.
-
-                if (!stateObj._accumulateInfoEvents && (stateObj._pendingInfoEvents != null))
-                {
-                    if (RunBehavior.Clean != (RunBehavior.Clean & runBehavior))
-                    {
-                        SqlConnection connection = null;
-                        if (_connHandler != null)
-                            connection = _connHandler.Connection; // SqlInternalConnection holds the user connection object as a weak ref
-                        // We are omitting checks for error.Class in the code below (see processing of INFO) since we know (and assert) that error class
-                        // error.Class < TdsEnums.MIN_ERROR_CLASS for info message.
-                        // Also we know that TdsEnums.MIN_ERROR_CLASS<TdsEnums.MAX_USER_CORRECTABLE_ERROR_CLASS
-                        if ((connection != null) && connection.FireInfoMessageEventOnUserErrors)
-                        {
-                            foreach (SqlError error in stateObj._pendingInfoEvents)
-                                FireInfoMessageEvent(connection, stateObj, error);
-                        }
-                        else
-                            foreach (SqlError error in stateObj._pendingInfoEvents)
-                                stateObj.AddWarning(error);
-                    }
-                    stateObj._pendingInfoEvents = null;
-                }
-
-                byte token;
-                if (!stateObj.TryReadByte(out token))
-                {
-                    return false;
-                }
-
-                if (!IsValidTdsToken(token))
-                {
-                    Debug.Fail($"unexpected token; token = {token,-2:X2}");
-                    _state = TdsParserState.Broken;
-                    _connHandler.BreakConnection();
-                    throw SQL.ParsingError();
-                }
-
-                int tokenLength;
-                if (!TryGetTokenLength(token, stateObj, out tokenLength))
-                {
-                    return false;
-                }
-
-                switch (token)
-                {
-                    case TdsEnums.SQLERROR:
-                    case TdsEnums.SQLINFO:
-                        {
-                            if (token == TdsEnums.SQLERROR)
-                            {
-                                stateObj._errorTokenReceived = true; // Keep track of the fact error token was received - for Done processing.
-                            }
-
-                            SqlError error;
-                            if (!TryProcessError(token, stateObj, out error))
-                            {
-                                return false;
-                            }
-
-                            if (token == TdsEnums.SQLINFO && stateObj._accumulateInfoEvents)
-                            {
-                                Debug.Assert(error.Class < TdsEnums.MIN_ERROR_CLASS, "INFO with class > TdsEnums.MIN_ERROR_CLASS");
-
-                                if (stateObj._pendingInfoEvents == null)
-                                    stateObj._pendingInfoEvents = new List<SqlError>();
-                                stateObj._pendingInfoEvents.Add(error);
-                                stateObj._syncOverAsync = true;
-                                break;
-                            }
-
-                            if (RunBehavior.Clean != (RunBehavior.Clean & runBehavior))
-                            {
-                                // If FireInfoMessageEventOnUserErrors is true, we have to fire event without waiting.
-                                // Otherwise we can go ahead and add it to errors/warnings collection.
-                                SqlConnection connection = null;
-                                if (_connHandler != null)
-                                    connection = _connHandler.Connection; // SqlInternalConnection holds the user connection object as a weak ref
-
-                                if ((connection != null) &&
-                                    (connection.FireInfoMessageEventOnUserErrors == true) &&
-                                    (error.Class <= TdsEnums.MAX_USER_CORRECTABLE_ERROR_CLASS))
-                                {
-                                    // Fire SqlInfoMessage here
-                                    FireInfoMessageEvent(connection, stateObj, error);
-                                }
-                                else
-                                {
-                                    // insert error/info into the appropriate exception - warning if info, exception if error
-                                    if (error.Class < TdsEnums.MIN_ERROR_CLASS)
-                                    {
-                                        stateObj.AddWarning(error);
-                                    }
-                                    else if (error.Class < TdsEnums.FATAL_ERROR_CLASS)
-                                    {
-                                        // Continue results processing for all non-fatal errors (<20)
-
-                                        stateObj.AddError(error);
-
-                                        // Add it to collection - but do NOT change run behavior UNLESS
-                                        // we are in an ExecuteReader call - at which time we will be throwing
-                                        // anyways so we need to consume all errors.  This is not the case
-                                        // if we have already given out a reader.  If we have already given out
-                                        // a reader we need to throw the error but not halt further processing.  We used to
-                                        // halt processing.
-
-                                        if (null != dataStream)
-                                        {
-                                            if (!dataStream.IsInitialized)
-                                            {
-                                                runBehavior = RunBehavior.UntilDone;
-                                            }
-                                        }
-                                    }
-                                    else
-                                    {
-                                        stateObj.AddError(error);
-
-                                        // Else we have a fatal error and we need to change the behavior
-                                        // since we want the complete error information in the exception.
-                                        // Besides - no further results will be received.
-                                        runBehavior = RunBehavior.UntilDone;
-                                    }
-                                }
-                            }
-                            else if (error.Class >= TdsEnums.FATAL_ERROR_CLASS)
-                            {
-                                stateObj.AddError(error);
-                            }
-                            break;
-                        }
-
-                    case TdsEnums.SQLCOLINFO:
-                        {
-                            if (null != dataStream)
-                            {
-                                _SqlMetaDataSet metaDataSet;
-                                if (!TryProcessColInfo(dataStream.MetaData, dataStream, stateObj, out metaDataSet))
-                                {
-                                    return false;
-                                }
-                                if (!dataStream.TrySetMetaData(metaDataSet, false))
-                                {
-                                    return false;
-                                }
-                                dataStream.BrowseModeInfoConsumed = true;
-                            }
-                            else
-                            { // no dataStream
-                                if (!stateObj.TrySkipBytes(tokenLength))
-                                {
-                                    return false;
-                                }
-                            }
-                            break;
-                        }
-
-                    case TdsEnums.SQLDONE:
-                    case TdsEnums.SQLDONEPROC:
-                    case TdsEnums.SQLDONEINPROC:
-                        {
-                            // RunBehavior can be modified
-                            if (!TryProcessDone(cmdHandler, dataStream, ref runBehavior, stateObj))
-                            {
-                                return false;
-                            }
-                            if ((token == TdsEnums.SQLDONEPROC) && (cmdHandler != null))
-                            {
-                                cmdHandler.OnDoneProc();
-                            }
-
-                            break;
-                        }
-
-                    case TdsEnums.SQLORDER:
-                        {
-                            // don't do anything with the order token so read off the pipe
-                            if (!stateObj.TrySkipBytes(tokenLength))
-                            {
-                                return false;
-                            }
-                            break;
-                        }
-
-                    case TdsEnums.SQLALTMETADATA:
-                        {
-                            stateObj.CloneCleanupAltMetaDataSetArray();
-
-                            if (stateObj._cleanupAltMetaDataSetArray == null)
-                            {
-                                // create object on demand (lazy creation)
-                                stateObj._cleanupAltMetaDataSetArray = new _SqlMetaDataSetCollection();
-                            }
-
-                            _SqlMetaDataSet cleanupAltMetaDataSet;
-                            if (!TryProcessAltMetaData(tokenLength, stateObj, out cleanupAltMetaDataSet))
-                            {
-                                return false;
-                            }
-
-                            stateObj._cleanupAltMetaDataSetArray.SetAltMetaData(cleanupAltMetaDataSet);
-                            if (null != dataStream)
-                            {
-                                byte metadataConsumedByte;
-                                if (!stateObj.TryPeekByte(out metadataConsumedByte))
-                                {
-                                    return false;
-                                }
-                                if (!dataStream.TrySetAltMetaDataSet(cleanupAltMetaDataSet, (TdsEnums.SQLALTMETADATA != metadataConsumedByte)))
-                                {
-                                    return false;
-                                }
-                            }
-
-                            break;
-                        }
-
-                    case TdsEnums.SQLALTROW:
-                        {
-                            if (!stateObj.TryStartNewRow(isNullCompressed: false))
-                            { // altrows are not currently null compressed
-                                return false;
-                            }
-
-                            // read will call run until dataReady. Must not read any data if returnimmetiately set
-                            if (RunBehavior.ReturnImmediately != (RunBehavior.ReturnImmediately & runBehavior))
-                            {
-                                ushort altRowId;
-                                if (!stateObj.TryReadUInt16(out altRowId))
-                                { // get altRowId
-                                    return false;
-                                }
-
-                                if (!TrySkipRow(stateObj._cleanupAltMetaDataSetArray.GetAltMetaData(altRowId), stateObj))
-                                { // skip altRow
-                                    return false;
-                                }
-                            }
-                            else
-                            {
-                                dataReady = true;
-                            }
-
-                            break;
-                        }
-
-                    case TdsEnums.SQLENVCHANGE:
-                        {
-                            // ENVCHANGE must be processed synchronously (since it can modify the state of many objects)
-                            stateObj._syncOverAsync = true;
-
-                            SqlEnvChange env;
-                            if (!TryProcessEnvChange(tokenLength, stateObj, out env))
-                            {
-                                return false;
-                            }
-
-                            while (env != null)
-                            {
-                                if (!this.Connection.IgnoreEnvChange)
-                                {
-                                    switch (env.type)
-                                    {
-                                        case TdsEnums.ENV_BEGINTRAN:
-                                        case TdsEnums.ENV_ENLISTDTC:
-                                            // When we get notification from the server of a new
-                                            // transaction, we move any pending transaction over to
-                                            // the current transaction, then we store the token in it.
-                                            // if there isn't a pending transaction, then it's either
-                                            // a TSQL transaction or a distributed transaction.
-                                            Debug.Assert(null == _currentTransaction, "non-null current transaction with an ENV Change");
-                                            _currentTransaction = _pendingTransaction;
-                                            _pendingTransaction = null;
-
-                                            if (null != _currentTransaction)
-                                            {
-                                                _currentTransaction.TransactionId = env.newLongValue;   // this is defined as a ULongLong in the server and in the TDS Spec.
-                                            }
-                                            else
-                                            {
-                                                TransactionType transactionType = (TdsEnums.ENV_BEGINTRAN == env.type) ? TransactionType.LocalFromTSQL : TransactionType.Distributed;
-                                                _currentTransaction = new SqlInternalTransaction(_connHandler, transactionType, null, env.newLongValue);
-                                            }
-                                            if (null != _statistics && !_statisticsIsInTransaction)
-                                            {
-                                                _statistics.SafeIncrement(ref _statistics._transactions);
-                                            }
-                                            _statisticsIsInTransaction = true;
-                                            _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
-                                            break;
-                                        case TdsEnums.ENV_DEFECTDTC:
-                                        case TdsEnums.ENV_TRANSACTIONENDED:
-                                        case TdsEnums.ENV_COMMITTRAN:
-                                            //  Must clear the retain id if the server-side transaction ends by anything other
-                                            //  than rollback.
-                                            _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
-                                            goto case TdsEnums.ENV_ROLLBACKTRAN;
-                                        case TdsEnums.ENV_ROLLBACKTRAN:
-                                            // When we get notification of a completed transaction
-                                            // we null out the current transaction.
-                                            if (null != _currentTransaction)
-                                            {
-#if DEBUG
-                                                // Check null for case where Begin and Rollback obtained in the same message.
-                                                if (SqlInternalTransaction.NullTransactionId != _currentTransaction.TransactionId)
-                                                {
-                                                    Debug.Assert(_currentTransaction.TransactionId != env.newLongValue, "transaction id's are not equal!");
-                                                }
-#endif
-
-                                                if (TdsEnums.ENV_COMMITTRAN == env.type)
-                                                {
-                                                    _currentTransaction.Completed(TransactionState.Committed);
-                                                }
-                                                else if (TdsEnums.ENV_ROLLBACKTRAN == env.type)
-                                                {
-                                                    //  Hold onto transaction id if distributed tran is rolled back.  This must
-                                                    //  be sent to the server on subsequent executions even though the transaction
-                                                    //  is considered to be rolled back.
-                                                    if (_currentTransaction.IsDistributed && _currentTransaction.IsActive)
-                                                    {
-                                                        _retainedTransactionId = env.oldLongValue;
-                                                    }
-                                                    _currentTransaction.Completed(TransactionState.Aborted);
-                                                }
-                                                else
-                                                {
-                                                    _currentTransaction.Completed(TransactionState.Unknown);
-                                                }
-                                                _currentTransaction = null;
-                                            }
-                                            _statisticsIsInTransaction = false;
-                                            break;
-
-                                        default:
-                                            _connHandler.OnEnvChange(env);
-                                            break;
-                                    }
-                                }
-                                SqlEnvChange head = env;
-                                env = env.Next;
-                                head.Clear();
-                                head = null;
-                            }
-                            break;
-                        }
-                    case TdsEnums.SQLLOGINACK:
-                        {
-                            SqlLoginAck ack;
-                            if (!TryProcessLoginAck(stateObj, out ack))
-                            {
-                                return false;
-                            }
-
-                            _connHandler.OnLoginAck(ack);
-                            break;
-                        }
-                    case TdsEnums.SQLFEATUREEXTACK:
-                        {
-                            if (!TryProcessFeatureExtAck(stateObj))
-                            {
-                                return false;
-                            }
-                            break;
-                        }
-                    case TdsEnums.SQLSESSIONSTATE:
-                        {
-                            if (!TryProcessSessionState(stateObj, tokenLength, _connHandler._currentSessionData))
-                            {
-                                return false;
-                            }
-                            break;
-                        }
-                    case TdsEnums.SQLCOLMETADATA:
-                        {
-                            if (tokenLength != TdsEnums.VARNULL)
-                            {
-                                _SqlMetaDataSet metadata;
-                                if (!TryProcessMetaData(tokenLength, stateObj, out metadata))
-                                {
-                                    return false;
-                                }
-                                stateObj._cleanupMetaData = metadata;
-                            }
-                            else
-                            {
-                                if (cmdHandler != null)
-                                {
-                                    stateObj._cleanupMetaData = cmdHandler.MetaData;
-                                }
-                            }
-
-                            if (null != dataStream)
-                            {
-                                byte peekedToken;
-                                if (!stateObj.TryPeekByte(out peekedToken))
-                                { // temporarily cache next byte
-                                    return false;
-                                }
-
-                                if (!dataStream.TrySetMetaData(stateObj._cleanupMetaData, (TdsEnums.SQLTABNAME == peekedToken || TdsEnums.SQLCOLINFO == peekedToken)))
-                                {
-                                    return false;
-                                }
-                            }
-                            else if (null != bulkCopyHandler)
-                            {
-                                bulkCopyHandler.SetMetaData(stateObj._cleanupMetaData);
-                            }
-                            break;
-                        }
-                    case TdsEnums.SQLROW:
-                    case TdsEnums.SQLNBCROW:
-                        {
-                            Debug.Assert(stateObj._cleanupMetaData != null, "Reading a row, but the metadata is null");
-
-                            if (token == TdsEnums.SQLNBCROW)
-                            {
-                                if (!stateObj.TryStartNewRow(isNullCompressed: true, nullBitmapColumnsCount: stateObj._cleanupMetaData.Length))
-                                {
-                                    return false;
-                                }
-                            }
-                            else
-                            {
-                                if (!stateObj.TryStartNewRow(isNullCompressed: false))
-                                {
-                                    return false;
-                                }
-                            }
-
-                            if (null != bulkCopyHandler)
-                            {
-                                if (!TryProcessRow(stateObj._cleanupMetaData, bulkCopyHandler.CreateRowBuffer(), bulkCopyHandler.CreateIndexMap(), stateObj))
-                                {
-                                    return false;
-                                }
-                            }
-                            else if (RunBehavior.ReturnImmediately != (RunBehavior.ReturnImmediately & runBehavior))
-                            {
-                                if (!TrySkipRow(stateObj._cleanupMetaData, stateObj))
-                                { // skip rows
-                                    return false;
-                                }
-                            }
-                            else
-                            {
-                                dataReady = true;
-                            }
-
-                            if (_statistics != null)
-                            {
-                                _statistics.WaitForDoneAfterRow = true;
-                            }
-                            break;
-                        }
-                    case TdsEnums.SQLRETURNSTATUS:
-                        int status;
-                        if (!stateObj.TryReadInt32(out status))
-                        {
-                            return false;
-                        }
-                        if (cmdHandler != null)
-                        {
-                            cmdHandler.OnReturnStatus(status);
-                        }
-                        break;
-                    case TdsEnums.SQLRETURNVALUE:
-                        {
-                            SqlReturnValue returnValue;
-                            if (!TryProcessReturnValue(tokenLength, stateObj, out returnValue))
-                            {
-                                return false;
-                            }
-                            if (cmdHandler != null)
-                            {
-                                cmdHandler.OnReturnValue(returnValue, stateObj);
-                            }
-                            break;
-                        }
-                    case TdsEnums.SQLSSPI:
-                        {
-                            // token length is length of SSPI data - call ProcessSSPI with it
-
-                            Debug.Assert(stateObj._syncOverAsync, "ProcessSSPI does not support retry, do not attempt asynchronously");
-                            stateObj._syncOverAsync = true;
-
-                            ProcessSSPI(tokenLength);
-                            break;
-                        }
-                    case TdsEnums.SQLTABNAME:
-                        {
-                            if (null != dataStream)
-                            {
-                                MultiPartTableName[] tableNames;
-                                if (!TryProcessTableName(tokenLength, stateObj, out tableNames))
-                                {
-                                    return false;
-                                }
-                                dataStream.TableNames = tableNames;
-                            }
-                            else
-                            {
-                                if (!stateObj.TrySkipBytes(tokenLength))
-                                {
-                                    return false;
-                                }
-                            }
-                            break;
-                        }
-
-                    default:
-                        Debug.Fail("Unhandled token:  " + token.ToString(CultureInfo.InvariantCulture));
-                        break;
-                }
-
-                Debug.Assert(stateObj._pendingData || !dataReady, "dataReady is set, but there is no pending data");
-            }
-
-            // Loop while data pending & runbehavior not return immediately, OR
-            // if in attention case, loop while no more pending data & attention has not yet been
-            // received.
-            while ((stateObj._pendingData &&
-                    (RunBehavior.ReturnImmediately != (RunBehavior.ReturnImmediately & runBehavior))) ||
-                (!stateObj._pendingData && stateObj._attentionSent && !stateObj._attentionReceived));
-
-#if DEBUG
-            if ((stateObj._pendingData) && (!dataReady))
-            {
-                byte token;
-                if (!stateObj.TryPeekByte(out token))
-                {
-                    return false;
-                }
-                Debug.Assert(IsValidTdsToken(token), $"DataReady is false, but next token is not valid: {token,-2:X2}");
-            }
-#endif
-
-            if (!stateObj._pendingData)
-            {
-                if (null != CurrentTransaction)
-                {
-                    CurrentTransaction.Activate();
-                }
-            }
-
-            // if we received an attention (but this thread didn't send it) then
-            // we throw an Operation Cancelled error
-            if (stateObj._attentionReceived)
-            {
-                // Dev11 #344723: SqlClient stress hang System_Data!Tcp::ReadSync via a call to SqlDataReader::Close
-                // Spin until SendAttention has cleared _attentionSending, this prevents a race condition between receiving the attention ACK and setting _attentionSent
-                TryRunSetupSpinWaitContinuation(stateObj);
-
-                Debug.Assert(stateObj._attentionSent, "Attention ACK has been received without attention sent");
-                if (stateObj._attentionSent)
-                {
-                    // Reset attention state.
-                    stateObj._attentionSent = false;
-                    stateObj._attentionReceived = false;
-
-                    if (RunBehavior.Clean != (RunBehavior.Clean & runBehavior) && !stateObj._internalTimeout)
-                    {
-                        // Add attention error to collection - if not RunBehavior.Clean!
-                        stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.OperationCancelled(), "", 0));
-                    }
-                }
-            }
-
-            if (stateObj.HasErrorOrWarning)
-            {
-                ThrowExceptionAndWarning(stateObj);
-            }
-            return true;
-        }
-
-        // This is in its own method to avoid always allocating the lambda in TryRun
-        private static void TryRunSetupSpinWaitContinuation(TdsParserStateObject stateObj) => SpinWait.SpinUntil(() => !stateObj._attentionSending);
-
-        private bool TryProcessEnvChange(int tokenLength, TdsParserStateObject stateObj, out SqlEnvChange sqlEnvChange)
-        {
-            // There could be multiple environment change messages following this token.
-            byte byteLength;
-            int processedLength = 0;
-            SqlEnvChange head = null;
-            SqlEnvChange tail = null;
-
-            sqlEnvChange = null;
-
-            while (tokenLength > processedLength)
-            {
-                var env = new SqlEnvChange();
-
-                if (!stateObj.TryReadByte(out env.type))
-                {
-                    return false;
-                }
-
-                if (head is null)
-                {
-                    head = env;
-                    tail = env;
-                }
-                else
-                {
-                    tail.Next = env;
-                    tail = env;
-                }
-
-                switch (env.type)
-                {
-                    case TdsEnums.ENV_DATABASE:
-                    case TdsEnums.ENV_LANG:
-                        if (!TryReadTwoStringFields(env, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-
-                    case TdsEnums.ENV_CHARSET:
-                        // we copied this behavior directly from luxor - see charset envchange
-                        // section from sqlctokn.c
-                        if (!TryReadTwoStringFields(env, stateObj))
-                        {
-                            return false;
-                        }
-                        if (env.newValue == TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_STRING)
-                        {
-                            _defaultCodePage = TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_VALUE;
-                            _defaultEncoding = System.Text.Encoding.GetEncoding(_defaultCodePage);
-                        }
-                        else
-                        {
-                            Debug.Assert(env.newValue.Length > TdsEnums.CHARSET_CODE_PAGE_OFFSET, "TdsParser.ProcessEnvChange(): charset value received with length <=10");
-
-                            string stringCodePage = env.newValue.Substring(TdsEnums.CHARSET_CODE_PAGE_OFFSET);
-
-                            _defaultCodePage = int.Parse(stringCodePage, NumberStyles.Integer, CultureInfo.InvariantCulture);
-                            _defaultEncoding = System.Text.Encoding.GetEncoding(_defaultCodePage);
-                        }
-
-                        break;
-
-                    case TdsEnums.ENV_PACKETSIZE:
-                        // take care of packet size right here
-                        Debug.Assert(stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-                        if (!TryReadTwoStringFields(env, stateObj))
-                        {
-                            // Changing packet size does not support retry, should not pend"
-                            throw SQL.SynchronousCallMayNotPend();
-                        }
-                        // Only set on physical state object - this should only occur on LoginAck prior
-                        // to MARS initialization!
-                        int packetSize = int.Parse(env.newValue, NumberStyles.Integer, CultureInfo.InvariantCulture);
-
-                        if (_physicalStateObj.SetPacketSize(packetSize))
-                        {
-                            // If packet size changed, we need to release our SNIPackets since
-                            // those are tied to packet size of connection.
-                            _physicalStateObj.ClearAllWritePackets();
-
-                            // Update SNI ConsumerInfo value to be resulting packet size
-                            uint unsignedPacketSize = (uint)packetSize;
-
-                            uint result = _physicalStateObj.SetConnectionBufferSize(ref unsignedPacketSize);
-                            Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SNISetInfo");
-                        }
-
-                        break;
-
-                    case TdsEnums.ENV_LOCALEID:
-                        if (!TryReadTwoStringFields(env, stateObj))
-                        {
-                            return false;
-                        }
-                        _defaultLCID = int.Parse(env.newValue, NumberStyles.Integer, CultureInfo.InvariantCulture);
-                        break;
-
-                    case TdsEnums.ENV_COMPFLAGS:
-                        if (!TryReadTwoStringFields(env, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-
-                    case TdsEnums.ENV_COLLATION:
-                        Debug.Assert(env.newLength == 5 || env.newLength == 0, "Improper length in new collation!");
-                        if (!stateObj.TryReadByte(out byteLength))
-                        {
-                            return false;
-                        }
-                        env.newLength = byteLength;
-                        if (env.newLength == 5)
-                        {
-                            if (!TryProcessCollation(stateObj, out env.newCollation))
-                            {
-                                return false;
-                            }
-
-                            // Give the parser the new collation values in case parameters don't specify one
-                            _defaultCollation = env.newCollation;
-
-                            // UTF8 collation
-                            if ((env.newCollation.info & TdsEnums.UTF8_IN_TDSCOLLATION) == TdsEnums.UTF8_IN_TDSCOLLATION)
-                            {
-                                _defaultEncoding = Encoding.UTF8;
-                            }
-                            else
-                            {
-                                int newCodePage = GetCodePage(env.newCollation, stateObj);
-                                if (newCodePage != _defaultCodePage)
-                                {
-                                    _defaultCodePage = newCodePage;
-                                    _defaultEncoding = System.Text.Encoding.GetEncoding(_defaultCodePage);
-                                }
-                            }
-                            _defaultLCID = env.newCollation.LCID;
-                        }
-
-                        if (!stateObj.TryReadByte(out byteLength))
-                        {
-                            return false;
-                        }
-                        env.oldLength = byteLength;
-                        Debug.Assert(env.oldLength == 5 || env.oldLength == 0, "Improper length in old collation!");
-                        if (env.oldLength == 5)
-                        {
-                            if (!TryProcessCollation(stateObj, out env.oldCollation))
-                            {
-                                return false;
-                            }
-                        }
-
-                        env.length = 3 + env.newLength + env.oldLength;
-                        break;
-
-                    case TdsEnums.ENV_BEGINTRAN:
-                    case TdsEnums.ENV_COMMITTRAN:
-                    case TdsEnums.ENV_ROLLBACKTRAN:
-                    case TdsEnums.ENV_ENLISTDTC:
-                    case TdsEnums.ENV_DEFECTDTC:
-                    case TdsEnums.ENV_TRANSACTIONENDED:
-                        if (!stateObj.TryReadByte(out byteLength))
-                        {
-                            return false;
-                        }
-                        env.newLength = byteLength;
-                        Debug.Assert(env.newLength == 0 || env.newLength == 8, "Improper length for new transaction id!");
-
-                        if (env.newLength > 0)
-                        {
-                            if (!stateObj.TryReadInt64(out env.newLongValue))
-                            {
-                                return false;
-                            }
-                            Debug.Assert(env.newLongValue != SqlInternalTransaction.NullTransactionId, "New transaction id is null?"); // the server guarantees that zero is an invalid transaction id.
-                        }
-                        else
-                        {
-                            env.newLongValue = SqlInternalTransaction.NullTransactionId; // the server guarantees that zero is an invalid transaction id.
-                        }
-
-                        if (!stateObj.TryReadByte(out byteLength))
-                        {
-                            return false;
-                        }
-                        env.oldLength = byteLength;
-                        Debug.Assert(env.oldLength == 0 || env.oldLength == 8, "Improper length for old transaction id!");
-
-                        if (env.oldLength > 0)
-                        {
-                            if (!stateObj.TryReadInt64(out env.oldLongValue))
-                            {
-                                return false;
-                            }
-                            Debug.Assert(env.oldLongValue != SqlInternalTransaction.NullTransactionId, "Old transaction id is null?"); // the server guarantees that zero is an invalid transaction id.
-                        }
-                        else
-                        {
-                            env.oldLongValue = SqlInternalTransaction.NullTransactionId; // the server guarantees that zero is an invalid transaction id.
-                        }
-
-                        // env.length includes 1 byte type token
-                        env.length = 3 + env.newLength + env.oldLength;
-                        break;
-
-                    case TdsEnums.ENV_LOGSHIPNODE:
-                        // env.newBinValue is secondary node, env.oldBinValue is witness node
-                        // comes before LoginAck so we can't assert this
-                        if (!TryReadTwoStringFields(env, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-
-                    case TdsEnums.ENV_PROMOTETRANSACTION:
-                        if (!stateObj.TryReadInt32(out env.newLength))
-                        { // new value has 4 byte length
-                            return false;
-                        }
-                        env.newBinValue = new byte[env.newLength];
-                        if (!stateObj.TryReadByteArray(env.newBinValue, env.newLength))
-                        { // read new value with 4 byte length
-                            return false;
-                        }
-
-                        if (!stateObj.TryReadByte(out byteLength))
-                        {
-                            return false;
-                        }
-                        env.oldLength = byteLength;
-                        Debug.Assert(0 == env.oldLength, "old length should be zero");
-
-                        // env.length includes 1 byte for type token
-                        env.length = 5 + env.newLength;
-                        break;
-
-                    case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
-                    case TdsEnums.ENV_SPRESETCONNECTIONACK:
-                        if (!TryReadTwoBinaryFields(env, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-
-                    case TdsEnums.ENV_USERINSTANCE:
-                        if (!TryReadTwoStringFields(env, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-
-                    case TdsEnums.ENV_ROUTING:
-                        ushort newLength;
-                        if (!stateObj.TryReadUInt16(out newLength))
-                        {
-                            return false;
-                        }
-                        env.newLength = newLength;
-                        byte protocol;
-                        if (!stateObj.TryReadByte(out protocol))
-                        {
-                            return false;
-                        }
-                        ushort port;
-                        if (!stateObj.TryReadUInt16(out port))
-                        {
-                            return false;
-                        }
-                        ushort serverLen;
-                        if (!stateObj.TryReadUInt16(out serverLen))
-                        {
-                            return false;
-                        }
-                        string serverName;
-                        if (!stateObj.TryReadString(serverLen, out serverName))
-                        {
-                            return false;
-                        }
-                        env.newRoutingInfo = new RoutingInfo(protocol, port, serverName);
-                        ushort oldLength;
-                        if (!stateObj.TryReadUInt16(out oldLength))
-                        {
-                            return false;
-                        }
-                        if (!stateObj.TrySkipBytes(oldLength))
-                        {
-                            return false;
-                        }
-                        env.length = env.newLength + oldLength + 5; // 5=2*sizeof(UInt16)+sizeof(byte) [token+newLength+oldLength]
-                        break;
-
-                    default:
-                        Debug.Fail("Unknown environment change token: " + env.type);
-                        break;
-                }
-                processedLength += env.length;
-            }
-
-            sqlEnvChange = head;
-            return true;
-        }
-
-        private bool TryReadTwoBinaryFields(SqlEnvChange env, TdsParserStateObject stateObj)
-        {
-            // Used by ProcessEnvChangeToken
-            byte byteLength;
-            if (!stateObj.TryReadByte(out byteLength))
-            {
-                return false;
-            }
-            env.newLength = byteLength;
-            env.newBinValue = ArrayPool<byte>.Shared.Rent(env.newLength);
-            env.newBinRented = true;
-            if (!stateObj.TryReadByteArray(env.newBinValue, env.newLength))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadByte(out byteLength))
-            {
-                return false;
-            }
-            env.oldLength = byteLength;
-            env.oldBinValue = ArrayPool<byte>.Shared.Rent(env.oldLength);
-            env.oldBinRented = true;
-            if (!stateObj.TryReadByteArray(env.oldBinValue, env.oldLength))
-            {
-                return false;
-            }
-
-            // env.length includes 1 byte type token
-            env.length = 3 + env.newLength + env.oldLength;
-            return true;
-        }
-
-        private bool TryReadTwoStringFields(SqlEnvChange env, TdsParserStateObject stateObj)
-        {
-            // Used by ProcessEnvChangeToken
-            byte newLength, oldLength;
-            string newValue, oldValue;
-            if (!stateObj.TryReadByte(out newLength))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadString(newLength, out newValue))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadByte(out oldLength))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadString(oldLength, out oldValue))
-            {
-                return false;
-            }
-
-            env.newLength = newLength;
-            env.newValue = newValue;
-            env.oldLength = oldLength;
-            env.oldValue = oldValue;
-
-            // env.length includes 1 byte type token
-            env.length = 3 + env.newLength * 2 + env.oldLength * 2;
-            return true;
-        }
-
-        private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavior run, TdsParserStateObject stateObj)
-        {
-            ushort curCmd;
-            ushort status;
-            int count;
-
-            // status
-            // command
-            // rowcount (valid only if DONE_COUNT bit is set)
-
-            if (!stateObj.TryReadUInt16(out status))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadUInt16(out curCmd))
-            {
-                return false;
-            }
-
-            long longCount;
-            if (!stateObj.TryReadInt64(out longCount))
-            {
-                return false;
-            }
-            count = (int)longCount;
-
-            // We get a done token with the attention bit set
-            if (TdsEnums.DONE_ATTN == (status & TdsEnums.DONE_ATTN))
-            {
-                Debug.Assert(TdsEnums.DONE_MORE != (status & TdsEnums.DONE_MORE), "Not expecting DONE_MORE when receiving DONE_ATTN");
-                Debug.Assert(stateObj._attentionSent, "Received attention done without sending one!");
-                stateObj._attentionReceived = true;
-                Debug.Assert(stateObj._inBytesUsed == stateObj._inBytesRead && stateObj._inBytesPacket == 0, "DONE_ATTN received with more data left on wire");
-            }
-            if ((null != cmd) && (TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT)))
-            {
-                if (curCmd != TdsEnums.SELECT)
-                {
-                    cmd.InternalRecordsAffected = count;
-                }
-                // Skip the bogus DONE counts sent by the server
-                if (stateObj._receivedColMetaData || (curCmd != TdsEnums.SELECT))
-                {
-                    cmd.OnStatementCompleted(count);
-                }
-            }
-
-            stateObj._receivedColMetaData = false;
-
-            // Surface exception for DONE_ERROR in the case we did not receive an error token
-            // in the stream, but an error occurred.  In these cases, we throw a general server error.  The
-            // situations where this can occur are: an invalid buffer received from client, login error
-            // and the server refused our connection, and the case where we are trying to log in but
-            // the server has reached its max connection limit.  Bottom line, we need to throw general
-            // error in the cases where we did not receive an error token along with the DONE_ERROR.
-            if ((TdsEnums.DONE_ERROR == (TdsEnums.DONE_ERROR & status)) && stateObj.ErrorCount == 0 &&
-                  stateObj._errorTokenReceived == false && (RunBehavior.Clean != (RunBehavior.Clean & run)))
-            {
-                stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0));
-
-                if (null != reader)
-                {
-                    if (!reader.IsInitialized)
-                    {
-                        run = RunBehavior.UntilDone;
-                    }
-                }
-            }
-
-            // Similar to above, only with a more severe error.  In this case, if we received
-            // the done_srverror, this exception will be added to the collection regardless.
-            // The server will always break the connection in this case.
-            if ((TdsEnums.DONE_SRVERROR == (TdsEnums.DONE_SRVERROR & status)) && (RunBehavior.Clean != (RunBehavior.Clean & run)))
-            {
-                stateObj.AddError(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0));
-
-                if (null != reader)
-                {
-                    if (!reader.IsInitialized)
-                    {
-                        run = RunBehavior.UntilDone;
-                    }
-                }
-            }
-
-            ProcessSqlStatistics(curCmd, status, count);
-
-            // stop if the DONE_MORE bit isn't set (see above for attention handling)
-            if (TdsEnums.DONE_MORE != (status & TdsEnums.DONE_MORE))
-            {
-                stateObj._errorTokenReceived = false;
-                if (stateObj._inBytesUsed >= stateObj._inBytesRead)
-                {
-                    stateObj._pendingData = false;
-                }
-            }
-
-            // _pendingData set by e.g. 'TdsExecuteSQLBatch'
-            // _hasOpenResult always set to true by 'WriteMarsHeader'
-            //
-            if (!stateObj._pendingData && stateObj._hasOpenResult)
-            {
-                /*
-                                Debug.Assert(!((sqlTransaction != null               && _distributedTransaction != null) ||
-                                               (_userStartedLocalTransaction != null && _distributedTransaction != null))
-                                              , "ProcessDone - have both distributed and local transactions not null!");
-                */
-                // WebData 112722
-
-                stateObj.DecrementOpenResultCount();
-            }
-
-            return true;
-        }
-
-        private void ProcessSqlStatistics(ushort curCmd, ushort status, int count)
-        {
-            // SqlStatistics bookkeeping stuff
-            //
-            if (null != _statistics)
-            {
-                // any done after row(s) counts as a resultset
-                if (_statistics.WaitForDoneAfterRow)
-                {
-                    _statistics.SafeIncrement(ref _statistics._sumResultSets);
-                    _statistics.WaitForDoneAfterRow = false;
-                }
-
-                // clear row count DONE_COUNT flag is not set
-                if (!(TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT)))
-                {
-                    count = 0;
-                }
-
-                switch (curCmd)
-                {
-                    case TdsEnums.INSERT:
-                    case TdsEnums.DELETE:
-                    case TdsEnums.UPDATE:
-                    case TdsEnums.MERGE:
-                        _statistics.SafeIncrement(ref _statistics._iduCount);
-                        _statistics.SafeAdd(ref _statistics._iduRows, count);
-                        if (!_statisticsIsInTransaction)
-                        {
-                            _statistics.SafeIncrement(ref _statistics._transactions);
-                        }
-
-                        break;
-
-                    case TdsEnums.SELECT:
-                        _statistics.SafeIncrement(ref _statistics._selectCount);
-                        _statistics.SafeAdd(ref _statistics._selectRows, count);
-                        break;
-
-                    case TdsEnums.BEGINXACT:
-                        if (!_statisticsIsInTransaction)
-                        {
-                            _statistics.SafeIncrement(ref _statistics._transactions);
-                        }
-                        _statisticsIsInTransaction = true;
-                        break;
-
-                    case TdsEnums.OPENCURSOR:
-                        _statistics.SafeIncrement(ref _statistics._cursorOpens);
-                        break;
-
-                    case TdsEnums.ABORT:
-                        _statisticsIsInTransaction = false;
-                        break;
-
-                    case TdsEnums.ENDXACT:
-                        _statisticsIsInTransaction = false;
-                        break;
-                } // switch
-            }
-            else
-            {
-                switch (curCmd)
-                {
-                    case TdsEnums.BEGINXACT:
-                        _statisticsIsInTransaction = true;
-                        break;
-
-                    case TdsEnums.ABORT:
-                    case TdsEnums.ENDXACT:
-                        _statisticsIsInTransaction = false;
-                        break;
-                }
-            }
-        }
-
-        private bool TryProcessFeatureExtAck(TdsParserStateObject stateObj)
-        {
-            // read feature ID
-            byte featureId;
-            do
-            {
-                if (!stateObj.TryReadByte(out featureId))
-                {
-                    return false;
-                }
-                if (featureId != TdsEnums.FEATUREEXT_TERMINATOR)
-                {
-                    uint dataLen;
-                    if (!stateObj.TryReadUInt32(out dataLen))
-                    {
-                        return false;
-                    }
-                    byte[] data = new byte[dataLen];
-                    if (dataLen > 0)
-                    {
-                        if (!stateObj.TryReadByteArray(data, checked((int)dataLen)))
-                        {
-                            return false;
-                        }
-                    }
-                    _connHandler.OnFeatureExtAck(featureId, data);
-                }
-            } while (featureId != TdsEnums.FEATUREEXT_TERMINATOR);
-            return true;
-        }
-
-        private bool TryProcessSessionState(TdsParserStateObject stateObj, int length, SessionData sdata)
-        {
-            if (length < 5)
-            {
-                throw SQL.ParsingError();
-            }
-            uint seqNum;
-            if (!stateObj.TryReadUInt32(out seqNum))
-            {
-                return false;
-            }
-            if (seqNum == uint.MaxValue)
-            {
-                _connHandler.DoNotPoolThisConnection();
-            }
-            byte status;
-            if (!stateObj.TryReadByte(out status))
-            {
-                return false;
-            }
-            if (status > 1)
-            {
-                throw SQL.ParsingError();
-            }
-            bool recoverable = status != 0;
-            length -= 5;
-            while (length > 0)
-            {
-                byte stateId;
-                if (!stateObj.TryReadByte(out stateId))
-                {
-                    return false;
-                }
-                int stateLen;
-                byte stateLenByte;
-                if (!stateObj.TryReadByte(out stateLenByte))
-                {
-                    return false;
-                }
-                if (stateLenByte < 0xFF)
-                {
-                    stateLen = stateLenByte;
-                }
-                else
-                {
-                    if (!stateObj.TryReadInt32(out stateLen))
-                    {
-                        return false;
-                    }
-                }
-                byte[] buffer = null;
-                lock (sdata._delta)
-                {
-                    if (sdata._delta[stateId] == null)
-                    {
-                        buffer = new byte[stateLen];
-                        sdata._delta[stateId] = new SessionStateRecord { _version = seqNum, _dataLength = stateLen, _data = buffer, _recoverable = recoverable };
-                        sdata._deltaDirty = true;
-                        if (!recoverable)
-                        {
-                            checked
-                            { sdata._unrecoverableStatesCount++; }
-                        }
-                    }
-                    else
-                    {
-                        if (sdata._delta[stateId]._version <= seqNum)
-                        {
-                            SessionStateRecord sv = sdata._delta[stateId];
-                            sv._version = seqNum;
-                            sv._dataLength = stateLen;
-                            if (sv._recoverable != recoverable)
-                            {
-                                if (recoverable)
-                                {
-                                    Debug.Assert(sdata._unrecoverableStatesCount > 0, "Unrecoverable states count >0");
-                                    sdata._unrecoverableStatesCount--;
-                                }
-                                else
-                                {
-                                    checked
-                                    { sdata._unrecoverableStatesCount++; }
-                                }
-                                sv._recoverable = recoverable;
-                            }
-                            buffer = sv._data;
-                            if (buffer.Length < stateLen)
-                            {
-                                buffer = new byte[stateLen];
-                                sv._data = buffer;
-                            }
-                        }
-                    }
-                }
-                if (buffer != null)
-                {
-                    if (!stateObj.TryReadByteArray(buffer, stateLen))
-                    {
-                        return false;
-                    }
-                }
-                else
-                {
-                    if (!stateObj.TrySkipBytes(stateLen))
-                        return false;
-                }
-
-                if (stateLenByte < 0xFF)
-                {
-                    length -= 2 + stateLen;
-                }
-                else
-                {
-                    length -= 6 + stateLen;
-                }
-            }
-            sdata.AssertUnrecoverableStateCountIsCorrect();
-
-            return true;
-        }
-
-        private bool TryProcessLoginAck(TdsParserStateObject stateObj, out SqlLoginAck sqlLoginAck)
-        {
-            SqlLoginAck a = new SqlLoginAck();
-
-            sqlLoginAck = null;
-
-            // read past interface type and version
-            if (!stateObj.TrySkipBytes(1))
-            {
-                return false;
-            }
-
-            Span<byte> b = stackalloc byte[TdsEnums.VERSION_SIZE];
-            if (!stateObj.TryReadByteArray(b, b.Length))
-            {
-                return false;
-            }
-            a.tdsVersion = (uint)((((((b[0] << 8) | b[1]) << 8) | b[2]) << 8) | b[3]); // bytes are in motorola order (high byte first)
-            uint majorMinor = a.tdsVersion & 0xff00ffff;
-            uint increment = (a.tdsVersion >> 16) & 0xff;
-
-            // Server responds:
-            // 0x07000000 -> Sphinx         // Notice server response format is different for bwd compat
-            // 0x07010000 -> Shiloh RTM     // Notice server response format is different for bwd compat
-            // 0x71000001 -> Shiloh SP1
-            // 0x72xx0002 -> Yukon RTM
-            // information provided by S. Ashwin
-
-            switch (majorMinor)
-            {
-                case TdsEnums.YUKON_MAJOR << 24 | TdsEnums.YUKON_RTM_MINOR:     // Yukon
-                    if (increment != TdsEnums.YUKON_INCREMENT)
-                    { throw SQL.InvalidTDSVersion(); }
-                    _isYukon = true;
-                    break;
-                case TdsEnums.KATMAI_MAJOR << 24 | TdsEnums.KATMAI_MINOR:
-                    if (increment != TdsEnums.KATMAI_INCREMENT)
-                    { throw SQL.InvalidTDSVersion(); }
-                    _isKatmai = true;
-                    break;
-                case TdsEnums.DENALI_MAJOR << 24 | TdsEnums.DENALI_MINOR:
-                    if (increment != TdsEnums.DENALI_INCREMENT)
-                    { throw SQL.InvalidTDSVersion(); }
-                    _isDenali = true;
-                    break;
-                default:
-                    throw SQL.InvalidTDSVersion();
-            }
-
-            _isKatmai |= _isDenali;
-            _isYukon |= _isKatmai;
-
-            stateObj._outBytesUsed = stateObj._outputHeaderLen;
-            byte len;
-            if (!stateObj.TryReadByte(out len))
-            {
-                return false;
-            }
-
-            if (!stateObj.TrySkipBytes(len * ADP.CharSize))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadByte(out a.majorVersion))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadByte(out a.minorVersion))
-            {
-                return false;
-            }
-            byte buildNumHi, buildNumLo;
-            if (!stateObj.TryReadByte(out buildNumHi))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadByte(out buildNumLo))
-            {
-                return false;
-            }
-
-            a.buildNum = (short)((buildNumHi << 8) + buildNumLo);
-
-            Debug.Assert(_state == TdsParserState.OpenNotLoggedIn, "ProcessLoginAck called with state not TdsParserState.OpenNotLoggedIn");
-            _state = TdsParserState.OpenLoggedIn;
-
-            {
-                if (_fMARS)
-                {
-                    _resetConnectionEvent = new AutoResetEvent(true);
-                }
-            }
-
-            // Fail if SSE UserInstance and we have not received this info.
-            if (_connHandler.ConnectionOptions.UserInstance &&
-                string.IsNullOrEmpty(_connHandler.InstanceName))
-            {
-                stateObj.AddError(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, Server, SQLMessage.UserInstanceFailure(), "", 0));
-                ThrowExceptionAndWarning(stateObj);
-            }
-
-            sqlLoginAck = a;
-            return true;
-        }
-
-        internal bool TryProcessError(byte token, TdsParserStateObject stateObj, out SqlError error)
-        {
-            ushort shortLen;
-            byte byteLen;
-            int number;
-            byte state;
-            byte errorClass;
-
-            error = null;
-
-            if (!stateObj.TryReadInt32(out number))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadByte(out state))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadByte(out errorClass))
-            {
-                return false;
-            }
-
-            Debug.Assert(((errorClass >= TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLERROR) ||
-                          ((errorClass < TdsEnums.MIN_ERROR_CLASS) && token == TdsEnums.SQLINFO), "class and token don't match!");
-
-            if (!stateObj.TryReadUInt16(out shortLen))
-            {
-                return false;
-            }
-            string message;
-            if (!stateObj.TryReadString(shortLen, out message))
-            {
-                return false;
-            }
-
-            if (!stateObj.TryReadByte(out byteLen))
-            {
-                return false;
-            }
-
-            string server;
-
-            // If the server field is not received use the locally cached value.
-            if (byteLen == 0)
-            {
-                server = _server;
-            }
-            else
-            {
-                if (!stateObj.TryReadString(byteLen, out server))
-                {
-                    return false;
-                }
-            }
-
-            if (!stateObj.TryReadByte(out byteLen))
-            {
-                return false;
-            }
-            string procedure;
-            if (!stateObj.TryReadString(byteLen, out procedure))
-            {
-                return false;
-            }
-
-            int line;
-            if (_isYukon)
-            {
-                if (!stateObj.TryReadInt32(out line))
-                {
-                    return false;
-                }
-            }
-            else
-            {
-                ushort shortLine;
-                if (!stateObj.TryReadUInt16(out shortLine))
-                {
-                    return false;
-                }
-                line = shortLine;
-                // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server
-                // In that case we still have to read another 2 bytes
-                if (_state == TdsParserState.OpenNotLoggedIn)
-                {
-                    // Login incomplete
-                    byte b;
-                    if (!stateObj.TryPeekByte(out b))
-                    {
-                        return false;
-                    }
-                    if (b == 0)
-                    {
-                        // This is an invalid token value
-                        ushort value;
-                        if (!stateObj.TryReadUInt16(out value))
-                        {
-                            return false;
-                        }
-                        line = (line << 16) + value;
-                    }
-                }
-            }
-
-            error = new SqlError(number, state, errorClass, _server, message, procedure, line);
-            return true;
-        }
-
-
-        internal bool TryProcessReturnValue(int length, TdsParserStateObject stateObj, out SqlReturnValue returnValue)
-        {
-            returnValue = null;
-            SqlReturnValue rec = new SqlReturnValue();
-            rec.length = length;        // In Yukon this length is -1
-            ushort parameterIndex;
-            if (!stateObj.TryReadUInt16(out parameterIndex))
-            {
-                return false;
-            }
-            byte len;
-            if (!stateObj.TryReadByte(out len))
-            { // Length of parameter name
-                return false;
-            }
-
-            if (len > 0)
-            {
-                if (!stateObj.TryReadString(len, out rec.parameter))
-                {
-                    return false;
-                }
-            }
-
-            // read status and ignore
-            byte ignored;
-            if (!stateObj.TryReadByte(out ignored))
-            {
-                return false;
-            }
-
-            uint userType;
-
-            // read user type - 4 bytes Yukon, 2 backwards
-            if (!stateObj.TryReadUInt32(out userType))
-            {
-                return false;
-            }
-
-            // read off the flags
-            ushort ignoredFlags;
-            if (!stateObj.TryReadUInt16(out ignoredFlags))
-            {
-                return false;
-            }
-
-            // read the type
-            byte tdsType;
-            if (!stateObj.TryReadByte(out tdsType))
-            {
-                return false;
-            }
-
-            // read the MaxLen
-            // For xml datatypes, there is no tokenLength
-            int tdsLen;
-
-            if (tdsType == TdsEnums.SQLXMLTYPE)
-            {
-                tdsLen = TdsEnums.SQL_USHORTVARMAXLEN;
-            }
-            else if (IsVarTimeTds(tdsType))
-                tdsLen = 0;  // placeholder until we read the scale, just make sure it's not SQL_USHORTVARMAXLEN
-            else if (tdsType == TdsEnums.SQLDATE)
-            {
-                tdsLen = 3;
-            }
-            else
-            {
-                if (!TryGetTokenLength(tdsType, stateObj, out tdsLen))
-                {
-                    return false;
-                }
-            }
-
-            rec.metaType = MetaType.GetSqlDataType(tdsType, userType, tdsLen);
-            rec.type = rec.metaType.SqlDbType;
-
-            // always use the nullable type for parameters if Shiloh or later
-            // Sphinx sometimes sends fixed length return values
-            rec.tdsType = rec.metaType.NullableType;
-            rec.IsNullable = true;
-            if (tdsLen == TdsEnums.SQL_USHORTVARMAXLEN)
-            {
-                rec.metaType = MetaType.GetMaxMetaTypeFromMetaType(rec.metaType);
-            }
-
-            if (rec.type == SqlDbType.Decimal)
-            {
-                if (!stateObj.TryReadByte(out rec.precision))
-                {
-                    return false;
-                }
-                if (!stateObj.TryReadByte(out rec.scale))
-                {
-                    return false;
-                }
-            }
-
-            if (rec.metaType.IsVarTime)
-            {
-                if (!stateObj.TryReadByte(out rec.scale))
-                {
-                    return false;
-                }
-            }
-
-            if (tdsType == TdsEnums.SQLUDT)
-            {
-                if (!TryProcessUDTMetaData((SqlMetaDataPriv)rec, stateObj))
-                {
-                    return false;
-                }
-            }
-
-            if (rec.type == SqlDbType.Xml)
-            {
-                // Read schema info
-                byte schemapresent;
-                if (!stateObj.TryReadByte(out schemapresent))
-                {
-                    return false;
-                }
-
-                if ((schemapresent & 1) != 0)
-                {
-                    if (!stateObj.TryReadByte(out len))
-                    {
-                        return false;
-                    }
-                    if (rec.xmlSchemaCollection is null)
-                    {
-                        rec.xmlSchemaCollection = new SqlMetaDataXmlSchemaCollection();
-                    }
-                    if (len != 0)
-                    {
-                        if (!stateObj.TryReadString(len, out rec.xmlSchemaCollection.Database))
-                        {
-                            return false;
-                        }
-                    }
-
-                    if (!stateObj.TryReadByte(out len))
-                    {
-                        return false;
-                    }
-                    if (len != 0)
-                    {
-                        if (!stateObj.TryReadString(len, out rec.xmlSchemaCollection.OwningSchema))
-                        {
-                            return false;
-                        }
-                    }
-
-                    short slen;
-                    if (!stateObj.TryReadInt16(out slen))
-                    {
-                        return false;
-                    }
-
-                    if (slen != 0)
-                    {
-                        if (!stateObj.TryReadString(slen, out rec.xmlSchemaCollection.Name))
-                        {
-                            return false;
-                        }
-                    }
-                }
-            }
-            else if (rec.metaType.IsCharType)
-            {
-                // read the collation for 8.x servers
-                if (!TryProcessCollation(stateObj, out rec.collation))
-                {
-                    return false;
-                }
-
-                // UTF8 collation
-                if ((rec.collation.info & TdsEnums.UTF8_IN_TDSCOLLATION) == TdsEnums.UTF8_IN_TDSCOLLATION)
-                {
-                    rec.encoding = Encoding.UTF8;
-                }
-                else
-                {
-                    int codePage = GetCodePage(rec.collation, stateObj);
-
-                    // If the column lcid is the same as the default, use the default encoder
-                    if (codePage == _defaultCodePage)
-                    {
-                        rec.codePage = _defaultCodePage;
-                        rec.encoding = _defaultEncoding;
-                    }
-                    else
-                    {
-                        rec.codePage = codePage;
-                        rec.encoding = System.Text.Encoding.GetEncoding(rec.codePage);
-                    }
-                }
-            }
-
-            // for now we coerce return values into a SQLVariant, not good...
-            bool isNull = false;
-            ulong valLen;
-            if (!TryProcessColumnHeaderNoNBC(rec, stateObj, out isNull, out valLen))
-            {
-                return false;
-            }
-
-            // always read as sql types
-            Debug.Assert(valLen < (ulong)(int.MaxValue), "ProcessReturnValue received data size > 2Gb");
-
-            int intlen = valLen > (ulong)(int.MaxValue) ? int.MaxValue : (int)valLen;
-
-            if (rec.metaType.IsPlp)
-            {
-                intlen = int.MaxValue;    // If plp data, read it all
-            }
-
-            if (isNull)
-            {
-                GetNullSqlValue(rec.value, rec);
-            }
-            else
-            {
-                if (!TryReadSqlValue(rec.value, rec, intlen, stateObj))
-                {
-                    return false;
-                }
-            }
-
-            returnValue = rec;
-            return true;
-        }
-
-        internal bool TryProcessCollation(TdsParserStateObject stateObj, out SqlCollation collation)
-        {
-            SqlCollation newCollation = new SqlCollation();
-
-            if (!stateObj.TryReadUInt32(out newCollation.info))
-            {
-                collation = null;
-                return false;
-            }
-            if (!stateObj.TryReadByte(out newCollation.sortId))
-            {
-                collation = null;
-                return false;
-            }
-
-            collation = newCollation;
-            return true;
-        }
-
-        private void WriteCollation(SqlCollation collation, TdsParserStateObject stateObj)
-        {
-            if (collation == null)
-            {
-                _physicalStateObj.WriteByte(0);
-            }
-            else
-            {
-                _physicalStateObj.WriteByte(sizeof(uint) + sizeof(byte));
-                WriteUnsignedInt(collation.info, _physicalStateObj);
-                _physicalStateObj.WriteByte(collation.sortId);
-            }
-        }
-
-        internal int GetCodePage(SqlCollation collation, TdsParserStateObject stateObj)
-        {
-            int codePage = 0;
-
-            if (0 != collation.sortId)
-            {
-                codePage = TdsEnums.CODE_PAGE_FROM_SORT_ID[collation.sortId];
-                Debug.Assert(0 != codePage, "GetCodePage accessed codepage array and produced 0!, sortID =" + ((byte)(collation.sortId)).ToString((IFormatProvider)null));
-            }
-            else
-            {
-                int cultureId = collation.LCID;
-                bool success = false;
-
-                try
-                {
-                    codePage = CultureInfo.GetCultureInfo(cultureId).TextInfo.ANSICodePage;
-
-                    // SqlHot 50001398: CodePage can be zero, but we should defer such errors until
-                    //  we actually MUST use the code page (i.e. don't error if no ANSI data is sent).
-                    success = true;
-                }
-                catch (ArgumentException)
-                {
-                }
-
-                // If we failed, it is quite possible this is because certain culture id's
-                // were removed in Win2k and beyond, however Sql Server still supports them.
-                // In this case we will mask off the sort id (the leading 1). If that fails,
-                // or we have a culture id other than the cases below, we throw an error and
-                // throw away the rest of the results.
-
-                //  Sometimes GetCultureInfo will return CodePage 0 instead of throwing.
-                //  This should be treated as an error and functionality switches into the following logic.
-                if (!success || codePage == 0)
-                {
-                    switch (cultureId)
-                    {
-                        case 0x10404: // zh-TW
-                        case 0x10804: // zh-CN
-                        case 0x10c04: // zh-HK
-                        case 0x11004: // zh-SG
-                        case 0x11404: // zh-MO
-                        case 0x10411: // ja-JP
-                        case 0x10412: // ko-KR
-                            // If one of the following special cases, mask out sortId and
-                            // retry.
-                            cultureId = cultureId & 0x03fff;
-
-                            try
-                            {
-                                codePage = new CultureInfo(cultureId).TextInfo.ANSICodePage;
-                                success = true;
-                            }
-                            catch (ArgumentException)
-                            {
-                            }
-                            break;
-                        case 0x827:     // Mapping Non-supported Lithuanian code page to supported Lithuanian.
-                            try
-                            {
-                                codePage = new CultureInfo(0x427).TextInfo.ANSICodePage;
-                                success = true;
-                            }
-                            catch (ArgumentException)
-                            {
-                            }
-                            break;
-                        default:
-                            break;
-                    }
-
-                    if (!success)
-                    {
-                        ThrowUnsupportedCollationEncountered(stateObj);
-                    }
-
-                    Debug.Assert(codePage >= 0, $"Invalid code page. codePage: {codePage}. cultureId: {cultureId}");
-                }
-            }
-
-            return codePage;
-        }
-
-
-        internal void DrainData(TdsParserStateObject stateObj)
-        {
-            try
-            {
-                SqlDataReader.SharedState sharedState = stateObj._readerState;
-                if (sharedState != null && sharedState._dataReady)
-                {
-                    var metadata = stateObj._cleanupMetaData;
-                    if (stateObj._partialHeaderBytesRead > 0)
-                    {
-                        if (!stateObj.TryProcessHeader())
-                        {
-                            throw SQL.SynchronousCallMayNotPend();
-                        }
-                    }
-                    if (0 == sharedState._nextColumnHeaderToRead)
-                    {
-                        // i. user called read but didn't fetch anything
-                        if (!stateObj.Parser.TrySkipRow(stateObj._cleanupMetaData, stateObj))
-                        {
-                            throw SQL.SynchronousCallMayNotPend();
-                        }
-                    }
-                    else
-                    {
-                        // iia.  if we still have bytes left from a partially read column, skip
-                        if (sharedState._nextColumnDataToRead < sharedState._nextColumnHeaderToRead)
-                        {
-                            if ((sharedState._nextColumnHeaderToRead > 0) && (metadata[sharedState._nextColumnHeaderToRead - 1].metaType.IsPlp))
-                            {
-                                if (stateObj._longlen != 0)
-                                {
-                                    ulong ignored;
-                                    if (!TrySkipPlpValue(ulong.MaxValue, stateObj, out ignored))
-                                    {
-                                        throw SQL.SynchronousCallMayNotPend();
-                                    }
-                                }
-                            }
-
-                            else if (0 < sharedState._columnDataBytesRemaining)
-                            {
-                                if (!stateObj.TrySkipLongBytes(sharedState._columnDataBytesRemaining))
-                                {
-                                    throw SQL.SynchronousCallMayNotPend();
-                                }
-                            }
-                        }
-
-
-                        // Read the remaining values off the wire for this row
-                        if (!stateObj.Parser.TrySkipRow(metadata, sharedState._nextColumnHeaderToRead, stateObj))
-                        {
-                            throw SQL.SynchronousCallMayNotPend();
-                        }
-                    }
-                }
-                Run(RunBehavior.Clean, null, null, null, stateObj);
-            }
-            catch
-            {
-                _connHandler.DoomThisConnection();
-                throw;
-            }
-        }
-
-
-        internal void ThrowUnsupportedCollationEncountered(TdsParserStateObject stateObj)
-        {
-            stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.CultureIdError(), "", 0));
-
-            if (null != stateObj)
-            {
-                DrainData(stateObj);
-
-                stateObj._pendingData = false;
-            }
-
-            ThrowExceptionAndWarning(stateObj);
-        }
-
-        internal bool TryProcessAltMetaData(int cColumns, TdsParserStateObject stateObj, out _SqlMetaDataSet metaData)
-        {
-            Debug.Assert(cColumns > 0, "should have at least 1 column in altMetaData!");
-
-            metaData = null;
-
-            _SqlMetaDataSet altMetaDataSet = new _SqlMetaDataSet(cColumns);
-            int[] indexMap = new int[cColumns];
-
-            if (!stateObj.TryReadUInt16(out altMetaDataSet.id))
-            {
-                return false;
-            }
-
-            byte byCols;
-            if (!stateObj.TryReadByte(out byCols))
-            {
-                return false;
-            }
-
-            while (byCols > 0)
-            {
-                if (!stateObj.TrySkipBytes(2))
-                { // ignore ColNum ...
-                    return false;
-                }
-                byCols--;
-            }
-
-            // pass 1, read the meta data off the wire
-            for (int i = 0; i < cColumns; i++)
-            {
-                // internal meta data class
-                _SqlMetaData col = altMetaDataSet[i];
-
-                byte op;
-                if (!stateObj.TryReadByte(out op))
-                {
-                    return false;
-                }
-                ushort operand;
-                if (!stateObj.TryReadUInt16(out operand))
-                {
-                    return false;
-                }
-
-                if (!TryCommonProcessMetaData(stateObj, col))
-                {
-                    return false;
-                }
-
-                indexMap[i] = i;
-            }
-
-            altMetaDataSet.indexMap = indexMap;
-            altMetaDataSet.visibleColumns = cColumns;
-
-            metaData = altMetaDataSet;
-            return true;
-        }
-
-        internal bool TryProcessMetaData(int cColumns, TdsParserStateObject stateObj, out _SqlMetaDataSet metaData)
-        {
-            Debug.Assert(cColumns > 0, "should have at least 1 column in metadata!");
-
-            _SqlMetaDataSet newMetaData = new _SqlMetaDataSet(cColumns);
-            for (int i = 0; i < cColumns; i++)
-            {
-                if (!TryCommonProcessMetaData(stateObj, newMetaData[i]))
-                {
-                    metaData = null;
-                    return false;
-                }
-            }
-
-            metaData = newMetaData;
-            return true;
-        }
-
-        private bool IsVarTimeTds(byte tdsType)
-        {
-            return tdsType == TdsEnums.SQLTIME || tdsType == TdsEnums.SQLDATETIME2 || tdsType == TdsEnums.SQLDATETIMEOFFSET;
-        }
-
-        private bool TryCommonProcessMetaData(TdsParserStateObject stateObj, _SqlMetaData col)
-        {
-            byte byteLen;
-            uint userType;
-
-            // read user type - 4 bytes Yukon, 2 backwards
-            if (!stateObj.TryReadUInt32(out userType))
-            {
-                return false;
-            }
-
-            // read flags and set appropriate flags in structure
-            byte flags;
-            if (!stateObj.TryReadByte(out flags))
-            {
-                return false;
-            }
-
-            col.Updatability = (byte)((flags & TdsEnums.Updatability) >> 2);
-            col.IsNullable = (TdsEnums.Nullable == (flags & TdsEnums.Nullable));
-            col.IsIdentity = (TdsEnums.Identity == (flags & TdsEnums.Identity));
-
-            // read second byte of column metadata flags
-            if (!stateObj.TryReadByte(out flags))
-            {
-                return false;
-            }
-
-            col.IsColumnSet = (TdsEnums.IsColumnSet == (flags & TdsEnums.IsColumnSet));
-
-            byte tdsType;
-            if (!stateObj.TryReadByte(out tdsType))
-            {
-                return false;
-            }
-
-            if (tdsType == TdsEnums.SQLXMLTYPE)
-                col.length = TdsEnums.SQL_USHORTVARMAXLEN;  //Use the same length as other plp datatypes
-            else if (IsVarTimeTds(tdsType))
-                col.length = 0;  // placeholder until we read the scale, just make sure it's not SQL_USHORTVARMAXLEN
-            else if (tdsType == TdsEnums.SQLDATE)
-            {
-                col.length = 3;
-            }
-            else
-            {
-                if (!TryGetTokenLength(tdsType, stateObj, out col.length))
-                {
-                    return false;
-                }
-            }
-
-            col.metaType = MetaType.GetSqlDataType(tdsType, userType, col.length);
-            col.type = col.metaType.SqlDbType;
-
-            col.tdsType = (col.IsNullable ? col.metaType.NullableType : col.metaType.TDSType);
-
-            {
-                if (TdsEnums.SQLUDT == tdsType)
-                {
-                    if (!TryProcessUDTMetaData((SqlMetaDataPriv)col, stateObj))
-                    {
-                        return false;
-                    }
-                }
-
-                if (col.length == TdsEnums.SQL_USHORTVARMAXLEN)
-                {
-                    Debug.Assert(tdsType == TdsEnums.SQLXMLTYPE ||
-                                 tdsType == TdsEnums.SQLBIGVARCHAR ||
-                                 tdsType == TdsEnums.SQLBIGVARBINARY ||
-                                 tdsType == TdsEnums.SQLNVARCHAR ||
-                                 tdsType == TdsEnums.SQLUDT,
-                                 "Invalid streaming datatype");
-                    col.metaType = MetaType.GetMaxMetaTypeFromMetaType(col.metaType);
-                    Debug.Assert(col.metaType.IsLong, "Max datatype not IsLong");
-                    col.length = int.MaxValue;
-                    if (tdsType == TdsEnums.SQLXMLTYPE)
-                    {
-                        byte schemapresent;
-                        if (!stateObj.TryReadByte(out schemapresent))
-                        {
-                            return false;
-                        }
-
-                        if ((schemapresent & 1) != 0)
-                        {
-                            if (!stateObj.TryReadByte(out byteLen))
-                            {
-                                return false;
-                            }
-                            if (col.xmlSchemaCollection is null)
-                            {
-                                col.xmlSchemaCollection = new SqlMetaDataXmlSchemaCollection();
-                            }
-                            if (byteLen != 0)
-                            {
-                                if (!stateObj.TryReadString(byteLen, out col.xmlSchemaCollection.Database))
-                                {
-                                    return false;
-                                }
-                            }
-
-                            if (!stateObj.TryReadByte(out byteLen))
-                            {
-                                return false;
-                            }
-                            if (byteLen != 0)
-                            {
-                                if (!stateObj.TryReadString(byteLen, out col.xmlSchemaCollection.OwningSchema))
-                                {
-                                    return false;
-                                }
-                            }
-
-                            short shortLen;
-                            if (!stateObj.TryReadInt16(out shortLen))
-                            {
-                                return false;
-                            }
-                            if (byteLen != 0)
-                            {
-                                if (!stateObj.TryReadString(shortLen, out col.xmlSchemaCollection.Name))
-                                {
-                                    return false;
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-
-            if (col.type == SqlDbType.Decimal)
-            {
-                if (!stateObj.TryReadByte(out col.precision))
-                {
-                    return false;
-                }
-                if (!stateObj.TryReadByte(out col.scale))
-                {
-                    return false;
-                }
-            }
-
-            if (col.metaType.IsVarTime)
-            {
-                if (!stateObj.TryReadByte(out col.scale))
-                {
-                    return false;
-                }
-
-                Debug.Assert(0 <= col.scale && col.scale <= 7);
-
-                // calculate actual column length here
-                switch (col.metaType.SqlDbType)
-                {
-                    case SqlDbType.Time:
-                        col.length = MetaType.GetTimeSizeFromScale(col.scale);
-                        break;
-                    case SqlDbType.DateTime2:
-                        // Date in number of days (3 bytes) + time
-                        col.length = 3 + MetaType.GetTimeSizeFromScale(col.scale);
-                        break;
-                    case SqlDbType.DateTimeOffset:
-                        // Date in days (3 bytes) + offset in minutes (2 bytes) + time
-                        col.length = 5 + MetaType.GetTimeSizeFromScale(col.scale);
-                        break;
-
-                    default:
-                        Debug.Fail("Unknown VariableTime type!");
-                        break;
-                }
-            }
-
-            // read the collation for 7.x servers
-            if (col.metaType.IsCharType && (tdsType != TdsEnums.SQLXMLTYPE))
-            {
-                if (!TryProcessCollation(stateObj, out col.collation))
-                {
-                    return false;
-                }
-
-                // UTF8 collation
-                if ((col.collation.info & TdsEnums.UTF8_IN_TDSCOLLATION) == TdsEnums.UTF8_IN_TDSCOLLATION)
-                {
-                    col.encoding = Encoding.UTF8;
-                }
-                else
-                {
-                    int codePage = GetCodePage(col.collation, stateObj);
-
-                    if (codePage == _defaultCodePage)
-                    {
-                        col.codePage = _defaultCodePage;
-                        col.encoding = _defaultEncoding;
-                    }
-                    else
-                    {
-                        col.codePage = codePage;
-                        col.encoding = System.Text.Encoding.GetEncoding(col.codePage);
-                    }
-                }
-            }
-
-            if (col.metaType.IsLong && !col.metaType.IsPlp)
-            {
-                int unusedLen = 0xFFFF;      //We ignore this value
-                if (!TryProcessOneTable(stateObj, ref unusedLen, out col.multiPartTableName))
-                {
-                    return false;
-                }
-            }
-
-            if (!stateObj.TryReadByte(out byteLen))
-            {
-                return false;
-            }
-            if (!stateObj.TryReadString(byteLen, out col.column))
-            {
-                return false;
-            }
-
-            // We get too many DONE COUNTs from the server, causing too many StatementCompleted event firings.
-            // We only need to fire this event when we actually have a meta data stream with 0 or more rows.
-            stateObj._receivedColMetaData = true;
-            return true;
-        }
-
-        private void WriteUDTMetaData(object value, string database, string schema, string type, TdsParserStateObject stateObj)
-        {
-            // database
-            if (string.IsNullOrEmpty(database))
-            {
-                stateObj.WriteByte(0);
-            }
-            else
-            {
-                stateObj.WriteByte((byte)database.Length);
-                WriteString(database, stateObj);
-            }
-
-            // schema
-            if (string.IsNullOrEmpty(schema))
-            {
-                stateObj.WriteByte(0);
-            }
-            else
-            {
-                stateObj.WriteByte((byte)schema.Length);
-                WriteString(schema, stateObj);
-            }
-
-            // type
-            if (string.IsNullOrEmpty(type))
-            {
-                stateObj.WriteByte(0);
-            }
-            else
-            {
-                stateObj.WriteByte((byte)type.Length);
-                WriteString(type, stateObj);
-            }
-        }
-
-        internal bool TryProcessTableName(int length, TdsParserStateObject stateObj, out MultiPartTableName[] multiPartTableNames)
-        {
-            int tablesAdded = 0;
-
-            MultiPartTableName[] tables = new MultiPartTableName[1];
-            MultiPartTableName mpt;
-            while (length > 0)
-            {
-                if (!TryProcessOneTable(stateObj, ref length, out mpt))
-                {
-                    multiPartTableNames = null;
-                    return false;
-                }
-                if (tablesAdded == 0)
-                {
-                    tables[tablesAdded] = mpt;
-                }
-                else
-                {
-                    MultiPartTableName[] newTables = new MultiPartTableName[tables.Length + 1];
-                    Array.Copy(tables, newTables, tables.Length);
-                    newTables[tables.Length] = mpt;
-                    tables = newTables;
-                }
-
-                tablesAdded++;
-            }
-
-            multiPartTableNames = tables;
-            return true;
-        }
-
-        private bool TryProcessOneTable(TdsParserStateObject stateObj, ref int length, out MultiPartTableName multiPartTableName)
-        {
-            ushort tableLen;
-            MultiPartTableName mpt;
-            string value;
-
-            multiPartTableName = default(MultiPartTableName);
-
-            mpt = default;
-            byte nParts;
-
-            // Find out how many parts in the TDS stream
-            if (!stateObj.TryReadByte(out nParts))
-            {
-                return false;
-            }
-            length--;
-            if (nParts == 4)
-            {
-                if (!stateObj.TryReadUInt16(out tableLen))
-                {
-                    return false;
-                }
-                length -= 2;
-                if (!stateObj.TryReadString(tableLen, out value))
-                {
-                    return false;
-                }
-                mpt.ServerName = value;
-                nParts--;
-                length -= (tableLen * 2); // wide bytes
-            }
-            if (nParts == 3)
-            {
-                if (!stateObj.TryReadUInt16(out tableLen))
-                {
-                    return false;
-                }
-                length -= 2;
-                if (!stateObj.TryReadString(tableLen, out value))
-                {
-                    return false;
-                }
-                mpt.CatalogName = value;
-                length -= (tableLen * 2); // wide bytes
-                nParts--;
-            }
-            if (nParts == 2)
-            {
-                if (!stateObj.TryReadUInt16(out tableLen))
-                {
-                    return false;
-                }
-                length -= 2;
-                if (!stateObj.TryReadString(tableLen, out value))
-                {
-                    return false;
-                }
-                mpt.SchemaName = value;
-                length -= (tableLen * 2); // wide bytes
-                nParts--;
-            }
-            if (nParts == 1)
-            {
-                if (!stateObj.TryReadUInt16(out tableLen))
-                {
-                    return false;
-                }
-                length -= 2;
-                if (!stateObj.TryReadString(tableLen, out value))
-                {
-                    return false;
-                }
-                mpt.TableName = value;
-                length -= (tableLen * 2); // wide bytes
-                nParts--;
-            }
-            Debug.Assert(nParts == 0, "ProcessTableName:Unidentified parts in the table name token stream!");
-
-            multiPartTableName = mpt;
-            return true;
-        }
-
-        // augments current metadata with table and key information
-        private bool TryProcessColInfo(_SqlMetaDataSet columns, SqlDataReader reader, TdsParserStateObject stateObj, out _SqlMetaDataSet metaData)
-        {
-            Debug.Assert(columns != null && columns.Length > 0, "no metadata available!");
-
-            metaData = null;
-
-            for (int i = 0; i < columns.Length; i++)
-            {
-                _SqlMetaData col = columns[i];
-
-                byte ignored;
-                if (!stateObj.TryReadByte(out ignored))
-                { // colnum, ignore
-                    return false;
-                }
-                if (!stateObj.TryReadByte(out col.tableNum))
-                {
-                    return false;
-                }
-
-                // interpret status
-                byte status;
-                if (!stateObj.TryReadByte(out status))
-                {
-                    return false;
-                }
-
-                col.IsDifferentName = (TdsEnums.SQLDifferentName == (status & TdsEnums.SQLDifferentName));
-                col.IsExpression = (TdsEnums.SQLExpression == (status & TdsEnums.SQLExpression));
-                col.IsKey = (TdsEnums.SQLKey == (status & TdsEnums.SQLKey));
-                col.IsHidden = (TdsEnums.SQLHidden == (status & TdsEnums.SQLHidden));
-
-                // read off the base table name if it is different than the select list column name
-                if (col.IsDifferentName)
-                {
-                    byte len;
-                    if (!stateObj.TryReadByte(out len))
-                    {
-                        return false;
-                    }
-                    if (!stateObj.TryReadString(len, out col.baseColumn))
-                    {
-                        return false;
-                    }
-                }
-
-                // Fixup column name - only if result of a table - that is if it was not the result of
-                // an expression.
-                if ((reader.TableNames != null) && (col.tableNum > 0))
-                {
-                    Debug.Assert(reader.TableNames.Length >= col.tableNum, "invalid tableNames array!");
-                    col.multiPartTableName = reader.TableNames[col.tableNum - 1];
-                }
-
-                // Expressions are readonly
-                if (col.IsExpression)
-                {
-                    col.Updatability = 0;
-                }
-            }
-
-            // set the metadata so that the stream knows some metadata info has changed
-            metaData = columns;
-            return true;
-        }
-
-        // takes care of any per data header information:
-        // for long columns, reads off textptrs, reads length, check nullability
-        // for other columns, reads length, checks nullability
-        // returns length and nullability
-        internal bool TryProcessColumnHeader(SqlMetaDataPriv col, TdsParserStateObject stateObj, int columnOrdinal, out bool isNull, out ulong length)
-        {
-            // query NBC row information first
-            if (stateObj.IsNullCompressionBitSet(columnOrdinal))
-            {
-                isNull = true;
-                // column information is not present in TDS if null compression bit is set, return now
-                length = 0;
-                return true;
-            }
-
-            return TryProcessColumnHeaderNoNBC(col, stateObj, out isNull, out length);
-        }
-
-        private bool TryProcessColumnHeaderNoNBC(SqlMetaDataPriv col, TdsParserStateObject stateObj, out bool isNull, out ulong length)
-        {
-            if (col.metaType.IsLong && !col.metaType.IsPlp)
-            {
-                //
-                // we don't care about TextPtrs, simply go after the data after it
-                //
-                byte textPtrLen;
-                if (!stateObj.TryReadByte(out textPtrLen))
-                {
-                    isNull = false;
-                    length = 0;
-                    return false;
-                }
-
-                if (0 != textPtrLen)
-                {
-                    // read past text pointer
-                    if (!stateObj.TrySkipBytes(textPtrLen))
-                    {
-                        isNull = false;
-                        length = 0;
-                        return false;
-                    }
-
-                    // read past timestamp
-                    if (!stateObj.TrySkipBytes(TdsEnums.TEXT_TIME_STAMP_LEN))
-                    {
-                        isNull = false;
-                        length = 0;
-                        return false;
-                    }
-
-                    isNull = false;
-                    return TryGetDataLength(col, stateObj, out length);
-                }
-                else
-                {
-                    isNull = true;
-                    length = 0;
-                    return true;
-                }
-            }
-            else
-            {
-                // non-blob columns
-                ulong longlen;
-                if (!TryGetDataLength(col, stateObj, out longlen))
-                {
-                    isNull = false;
-                    length = 0;
-                    return false;
-                }
-                isNull = IsNull(col.metaType, longlen);
-                length = (isNull ? 0 : longlen);
-                return true;
-            }
-        }
-
-        // assumes that the current position is at the start of an altrow!
-        internal bool TryGetAltRowId(TdsParserStateObject stateObj, out int id)
-        {
-            byte token;
-            if (!stateObj.TryReadByte(out token))
-            { // skip over ALTROW token
-                id = 0;
-                return false;
-            }
-            Debug.Assert((token == TdsEnums.SQLALTROW), "");
-
-            // Start a fresh row - disable NBC since Alt Rows are never compressed
-            if (!stateObj.TryStartNewRow(isNullCompressed: false))
-            {
-                id = 0;
-                return false;
-            }
-
-            ushort shortId;
-            if (!stateObj.TryReadUInt16(out shortId))
-            {
-                id = 0;
-                return false;
-            }
-
-            id = shortId;
-            return true;
-        }
-
-        // Used internally by BulkCopy only
-        private bool TryProcessRow(_SqlMetaDataSet columns, object[] buffer, int[] map, TdsParserStateObject stateObj)
-        {
-            SqlBuffer data = new SqlBuffer();
-
-            for (int i = 0; i < columns.Length; i++)
-            {
-                _SqlMetaData md = columns[i];
-                Debug.Assert(md != null, "_SqlMetaData should not be null for column " + i.ToString(CultureInfo.InvariantCulture));
-
-                bool isNull;
-                ulong len;
-                if (!TryProcessColumnHeader(md, stateObj, i, out isNull, out len))
-                {
-                    return false;
-                }
-
-                if (isNull)
-                {
-                    GetNullSqlValue(data, md);
-                    buffer[map[i]] = data.SqlValue;
-                }
-                else
-                {
-                    // We only read up to 2Gb. Throw if data is larger. Very large data
-                    // should be read in chunks in sequential read mode
-                    // For Plp columns, we may have gotten only the length of the first chunk
-                    if (!TryReadSqlValue(data, md, md.metaType.IsPlp ? (int.MaxValue) : (int)len, stateObj))
-                    {
-                        return false;
-                    }
-                    buffer[map[i]] = data.SqlValue;
-                    if (stateObj._longlen != 0)
-                    {
-                        throw new SqlTruncateException(SR.GetString(SR.SqlMisc_TruncationMaxDataMessage));
-                    }
-                }
-                data.Clear();
-            }
-
-            return true;
-        }
-
-        internal object GetNullSqlValue(SqlBuffer nullVal, SqlMetaDataPriv md)
-        {
-            switch (md.type)
-            {
-                case SqlDbType.Real:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Single);
-                    break;
-
-                case SqlDbType.Float:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Double);
-                    break;
-
-                case SqlDbType.Udt:
-                case SqlDbType.Binary:
-                case SqlDbType.VarBinary:
-                case SqlDbType.Image:
-                    nullVal.SqlBinary = SqlBinary.Null;
-                    break;
-
-                case SqlDbType.UniqueIdentifier:
-                    nullVal.SqlGuid = SqlGuid.Null;
-                    break;
-
-                case SqlDbType.Bit:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Boolean);
-                    break;
-
-                case SqlDbType.TinyInt:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Byte);
-                    break;
-
-                case SqlDbType.SmallInt:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Int16);
-                    break;
-
-                case SqlDbType.Int:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Int32);
-                    break;
-
-                case SqlDbType.BigInt:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Int64);
-                    break;
-
-                case SqlDbType.Char:
-                case SqlDbType.VarChar:
-                case SqlDbType.NChar:
-                case SqlDbType.NVarChar:
-                case SqlDbType.Text:
-                case SqlDbType.NText:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.String);
-                    break;
-
-                case SqlDbType.Decimal:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Decimal);
-                    break;
-
-                case SqlDbType.DateTime:
-                case SqlDbType.SmallDateTime:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.DateTime);
-                    break;
-
-                case SqlDbType.Money:
-                case SqlDbType.SmallMoney:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Money);
-                    break;
-
-                case SqlDbType.Variant:
-                    // DBNull.Value will have to work here
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Empty);
-                    break;
-
-                case SqlDbType.Xml:
-                    nullVal.SqlCachedBuffer = SqlCachedBuffer.Null;
-                    break;
-
-                case SqlDbType.Date:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Date);
-                    break;
-
-                case SqlDbType.Time:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.Time);
-                    break;
-
-                case SqlDbType.DateTime2:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.DateTime2);
-                    break;
-
-                case SqlDbType.DateTimeOffset:
-                    nullVal.SetToNullOfType(SqlBuffer.StorageType.DateTimeOffset);
-                    break;
-
-                case SqlDbType.Timestamp:
-                    break;
-
-                default:
-                    Debug.Fail("unknown null sqlType!" + md.type.ToString());
-                    break;
-            }
-
-            return nullVal;
-        }
-
-        internal bool TrySkipRow(_SqlMetaDataSet columns, TdsParserStateObject stateObj)
-        {
-            return TrySkipRow(columns, 0, stateObj);
-        }
-
-        internal bool TrySkipRow(_SqlMetaDataSet columns, int startCol, TdsParserStateObject stateObj)
-        {
-            for (int i = startCol; i < columns.Length; i++)
-            {
-                _SqlMetaData md = columns[i];
-
-                if (!TrySkipValue(md, i, stateObj))
-                {
-                    return false;
-                }
-            }
-            return true;
-        }
-
-        /// <summary>
-        /// This method skips bytes of a single column value from the media. It supports NBCROW and handles all types of values, including PLP and long
-        /// </summary>
-        internal bool TrySkipValue(SqlMetaDataPriv md, int columnOrdinal, TdsParserStateObject stateObj)
-        {
-            if (stateObj.IsNullCompressionBitSet(columnOrdinal))
-            {
-                return true;
-            }
-
-            if (md.metaType.IsPlp)
-            {
-                ulong ignored;
-                if (!TrySkipPlpValue(ulong.MaxValue, stateObj, out ignored))
-                {
-                    return false;
-                }
-            }
-            else if (md.metaType.IsLong)
-            {
-                Debug.Assert(!md.metaType.IsPlp, "Plp types must be handled using SkipPlpValue");
-
-                byte textPtrLen;
-                if (!stateObj.TryReadByte(out textPtrLen))
-                {
-                    return false;
-                }
-
-                if (0 != textPtrLen)
-                {
-                    if (!stateObj.TrySkipBytes(textPtrLen + TdsEnums.TEXT_TIME_STAMP_LEN))
-                    {
-                        return false;
-                    }
-
-                    int length;
-                    if (!TryGetTokenLength(md.tdsType, stateObj, out length))
-                    {
-                        return false;
-                    }
-                    if (!stateObj.TrySkipBytes(length))
-                    {
-                        return false;
-                    }
-                }
-            }
-            else
-            {
-                int length;
-                if (!TryGetTokenLength(md.tdsType, stateObj, out length))
-                {
-                    return false;
-                }
-
-                // if false, no value to skip - it's null
-                if (!IsNull(md.metaType, (ulong)length))
-                {
-                    if (!stateObj.TrySkipBytes(length))
-                    {
-                        return false;
-                    }
-                }
-            }
-
-            return true;
-        }
-
-        private bool IsNull(MetaType mt, ulong length)
-        {
-            // null bin and char types have a length of -1 to represent null
-            if (mt.IsPlp)
-            {
-                return (TdsEnums.SQL_PLP_NULL == length);
-            }
-
-            // HOTFIX #50000415: for image/text, 0xFFFF is the length, not representing null
-            if ((TdsEnums.VARNULL == length) && !mt.IsLong)
-            {
-                return true;
-            }
-
-            // other types have a length of 0 to represent null
-            // long and non-PLP types will always return false because these types are either char or binary
-            // this is expected since for long and non-plp types isnull is checked based on textptr field and not the length
-            return ((TdsEnums.FIXEDNULL == length) && !mt.IsCharType && !mt.IsBinType);
-        }
-
-        private bool TryReadSqlStringValue(SqlBuffer value, byte type, int length, Encoding encoding, bool isPlp, TdsParserStateObject stateObj)
-        {
-            switch (type)
-            {
-                case TdsEnums.SQLCHAR:
-                case TdsEnums.SQLBIGCHAR:
-                case TdsEnums.SQLVARCHAR:
-                case TdsEnums.SQLBIGVARCHAR:
-                case TdsEnums.SQLTEXT:
-                    // If bigvarchar(max), we only read the first chunk here,
-                    // expecting the caller to read the rest
-                    if (encoding == null)
-                    {
-                        // if hitting 7.0 server, encoding will be null in metadata for columns or return values since
-                        // 7.0 has no support for multiple code pages in data - single code page support only
-                        encoding = _defaultEncoding;
-                    }
-                    string stringValue;
-                    if (!stateObj.TryReadStringWithEncoding(length, encoding, isPlp, out stringValue))
-                    {
-                        return false;
-                    }
-                    value.SetToString(stringValue);
-                    break;
-
-                case TdsEnums.SQLNCHAR:
-                case TdsEnums.SQLNVARCHAR:
-                case TdsEnums.SQLNTEXT:
-                    {
-                        string s = null;
-
-                        if (isPlp)
-                        {
-                            char[] cc = null;
-
-                            if (!TryReadPlpUnicodeChars(ref cc, 0, length >> 1, stateObj, out length))
-                            {
-                                return false;
-                            }
-                            if (length > 0)
-                            {
-                                s = new string(cc, 0, length);
-                            }
-                            else
-                            {
-                                s = string.Empty;
-                            }
-                        }
-                        else
-                        {
-                            if (!stateObj.TryReadString(length >> 1, out s))
-                            {
-                                return false;
-                            }
-                        }
-
-                        value.SetToString(s);
-                        break;
-                    }
-
-                default:
-                    Debug.Fail("Unknown tds type for SqlString!" + type.ToString(CultureInfo.InvariantCulture));
-                    break;
-            }
-
-            return true;
-        }
-
-        internal bool TryReadSqlValue(SqlBuffer value, SqlMetaDataPriv md, int length, TdsParserStateObject stateObj)
-        {
-            bool isPlp = md.metaType.IsPlp;
-            byte tdsType = md.tdsType;
-
-            Debug.Assert(isPlp || !IsNull(md.metaType, (ulong)length), "null value should not get here!");
-            if (isPlp)
-            {
-                // We must read the column value completely, no matter what length is passed in
-                length = int.MaxValue;
-            }
-            switch (tdsType)
-            {
-                case TdsEnums.SQLDECIMALN:
-                case TdsEnums.SQLNUMERICN:
-                    if (!TryReadSqlDecimal(value, length, md.precision, md.scale, stateObj))
-                    {
-                        return false;
-                    }
-                    break;
-
-                case TdsEnums.SQLUDT:
-                case TdsEnums.SQLBINARY:
-                case TdsEnums.SQLBIGBINARY:
-                case TdsEnums.SQLBIGVARBINARY:
-                case TdsEnums.SQLVARBINARY:
-                case TdsEnums.SQLIMAGE:
-                    byte[] b = null;
-
-                    // If varbinary(max), we only read the first chunk here, expecting the caller to read the rest
-                    if (isPlp)
-                    {
-                        // If we are given -1 for length, then we read the entire value,
-                        // otherwise only the requested amount, usually first chunk.
-                        int ignored;
-                        if (!stateObj.TryReadPlpBytes(ref b, 0, length, out ignored))
-                        {
-                            return false;
-                        }
-                    }
-                    else
-                    {
-                        //Debug.Assert(length > 0 && length < (long)(Int32.MaxValue), "Bad length for column");
-                        b = new byte[length];
-                        if (!stateObj.TryReadByteArray(b, length))
-                        {
-                            return false;
-                        }
-                    }
-
-                    value.SqlBinary = SqlTypeWorkarounds.SqlBinaryCtor(b, true);
-
-                    break;
-
-                case TdsEnums.SQLCHAR:
-                case TdsEnums.SQLBIGCHAR:
-                case TdsEnums.SQLVARCHAR:
-                case TdsEnums.SQLBIGVARCHAR:
-                case TdsEnums.SQLTEXT:
-                case TdsEnums.SQLNCHAR:
-                case TdsEnums.SQLNVARCHAR:
-                case TdsEnums.SQLNTEXT:
-                    if (!TryReadSqlStringValue(value, tdsType, length, md.encoding, isPlp, stateObj))
-                    {
-                        return false;
-                    }
-                    break;
-
-                case TdsEnums.SQLXMLTYPE:
-                    // We store SqlCachedBuffer here, so that we can return either SqlBinary, SqlString or SqlXmlReader.
-                    SqlCachedBuffer sqlBuf;
-                    if (!SqlCachedBuffer.TryCreate(md, this, stateObj, out sqlBuf))
-                    {
-                        return false;
-                    }
-
-                    value.SqlCachedBuffer = sqlBuf;
-                    break;
-
-                case TdsEnums.SQLDATE:
-                case TdsEnums.SQLTIME:
-                case TdsEnums.SQLDATETIME2:
-                case TdsEnums.SQLDATETIMEOFFSET:
-                    if (!TryReadSqlDateTime(value, tdsType, length, md.scale, stateObj))
-                    {
-                        return false;
-                    }
-                    break;
-
-                default:
-                    Debug.Assert(!isPlp, "ReadSqlValue calling ReadSqlValueInternal with plp data");
-                    if (!TryReadSqlValueInternal(value, tdsType, length, stateObj))
-                    {
-                        return false;
-                    }
-                    break;
-            }
-
-            Debug.Assert((stateObj._longlen == 0) && (stateObj._longlenleft == 0), "ReadSqlValue did not read plp field completely, longlen =" + stateObj._longlen.ToString((IFormatProvider)null) + ",longlenleft=" + stateObj._longlenleft.ToString((IFormatProvider)null));
-            return true;
-        }
-
-        private bool TryReadSqlDateTime(SqlBuffer value, byte tdsType, int length, byte scale, TdsParserStateObject stateObj)
-        {
-            Span<byte> datetimeBuffer = ((uint)length <= 16) ? stackalloc byte[16] : new byte[length];
-
-            if (!stateObj.TryReadByteArray(datetimeBuffer, length))
-            {
-                return false;
-            }
-            ReadOnlySpan<byte> dateTimeData = datetimeBuffer.Slice(0, length);
-            switch (tdsType)
-            {
-                case TdsEnums.SQLDATE:
-                    Debug.Assert(length == 3, "invalid length for date type!");
-                    value.SetToDate(dateTimeData);
-                    break;
-
-                case TdsEnums.SQLTIME:
-                    Debug.Assert(3 <= length && length <= 5, "invalid length for time type!");
-                    value.SetToTime(dateTimeData, scale);
-                    break;
-
-                case TdsEnums.SQLDATETIME2:
-                    Debug.Assert(6 <= length && length <= 8, "invalid length for datetime2 type!");
-                    value.SetToDateTime2(dateTimeData, scale);
-                    break;
-
-                case TdsEnums.SQLDATETIMEOFFSET:
-                    Debug.Assert(8 <= length && length <= 10, "invalid length for datetimeoffset type!");
-                    value.SetToDateTimeOffset(dateTimeData, scale);
-                    break;
-
-                default:
-                    Debug.Fail("ReadSqlDateTime is called with the wrong tdsType");
-                    break;
-            }
-
-            return true;
-        }
-
-        internal bool TryReadSqlValueInternal(SqlBuffer value, byte tdsType, int length, TdsParserStateObject stateObj)
-        {
-            switch (tdsType)
-            {
-                case TdsEnums.SQLBIT:
-                case TdsEnums.SQLBITN:
-                    Debug.Assert(length == 1, "invalid length for SqlBoolean type!");
-                    byte byteValue;
-                    if (!stateObj.TryReadByte(out byteValue))
-                    {
-                        return false;
-                    }
-                    value.Boolean = (byteValue != 0);
-                    break;
-
-                case TdsEnums.SQLINTN:
-                    if (length == 1)
-                    {
-                        goto case TdsEnums.SQLINT1;
-                    }
-                    else if (length == 2)
-                    {
-                        goto case TdsEnums.SQLINT2;
-                    }
-                    else if (length == 4)
-                    {
-                        goto case TdsEnums.SQLINT4;
-                    }
-                    else
-                    {
-                        goto case TdsEnums.SQLINT8;
-                    }
-
-                case TdsEnums.SQLINT1:
-                    Debug.Assert(length == 1, "invalid length for SqlByte type!");
-                    if (!stateObj.TryReadByte(out byteValue))
-                    {
-                        return false;
-                    }
-                    value.Byte = byteValue;
-                    break;
-
-                case TdsEnums.SQLINT2:
-                    Debug.Assert(length == 2, "invalid length for SqlInt16 type!");
-                    short shortValue;
-                    if (!stateObj.TryReadInt16(out shortValue))
-                    {
-                        return false;
-                    }
-                    value.Int16 = shortValue;
-                    break;
-
-                case TdsEnums.SQLINT4:
-                    Debug.Assert(length == 4, "invalid length for SqlInt32 type!");
-                    int intValue;
-                    if (!stateObj.TryReadInt32(out intValue))
-                    {
-                        return false;
-                    }
-                    value.Int32 = intValue;
-                    break;
-
-                case TdsEnums.SQLINT8:
-                    Debug.Assert(length == 8, "invalid length for SqlInt64 type!");
-                    long longValue;
-                    if (!stateObj.TryReadInt64(out longValue))
-                    {
-                        return false;
-                    }
-                    value.Int64 = longValue;
-                    break;
-
-                case TdsEnums.SQLFLTN:
-                    if (length == 4)
-                    {
-                        goto case TdsEnums.SQLFLT4;
-                    }
-                    else
-                    {
-                        goto case TdsEnums.SQLFLT8;
-                    }
-
-                case TdsEnums.SQLFLT4:
-                    Debug.Assert(length == 4, "invalid length for SqlSingle type!");
-                    float singleValue;
-                    if (!stateObj.TryReadSingle(out singleValue))
-                    {
-                        return false;
-                    }
-                    value.Single = singleValue;
-                    break;
-
-                case TdsEnums.SQLFLT8:
-                    Debug.Assert(length == 8, "invalid length for SqlDouble type!");
-                    double doubleValue;
-                    if (!stateObj.TryReadDouble(out doubleValue))
-                    {
-                        return false;
-                    }
-                    value.Double = doubleValue;
-                    break;
-
-                case TdsEnums.SQLMONEYN:
-                    if (length == 4)
-                    {
-                        goto case TdsEnums.SQLMONEY4;
-                    }
-                    else
-                    {
-                        goto case TdsEnums.SQLMONEY;
-                    }
-
-                case TdsEnums.SQLMONEY:
-                    {
-                        int mid;
-                        uint lo;
-
-                        if (!stateObj.TryReadInt32(out mid))
-                        {
-                            return false;
-                        }
-                        if (!stateObj.TryReadUInt32(out lo))
-                        {
-                            return false;
-                        }
-
-                        long l = (((long)mid) << 0x20) + ((long)lo);
-
-                        value.SetToMoney(l);
-                        break;
-                    }
-
-                case TdsEnums.SQLMONEY4:
-                    if (!stateObj.TryReadInt32(out intValue))
-                    {
-                        return false;
-                    }
-                    value.SetToMoney(intValue);
-                    break;
-
-                case TdsEnums.SQLDATETIMN:
-                    if (length == 4)
-                    {
-                        goto case TdsEnums.SQLDATETIM4;
-                    }
-                    else
-                    {
-                        goto case TdsEnums.SQLDATETIME;
-                    }
-
-                case TdsEnums.SQLDATETIM4:
-                    ushort daypartShort, timepartShort;
-                    if (!stateObj.TryReadUInt16(out daypartShort))
-                    {
-                        return false;
-                    }
-                    if (!stateObj.TryReadUInt16(out timepartShort))
-                    {
-                        return false;
-                    }
-                    value.SetToDateTime(daypartShort, timepartShort * SqlDateTime.SQLTicksPerMinute);
-                    break;
-
-                case TdsEnums.SQLDATETIME:
-                    int daypart;
-                    uint timepart;
-                    if (!stateObj.TryReadInt32(out daypart))
-                    {
-                        return false;
-                    }
-                    if (!stateObj.TryReadUInt32(out timepart))
-                    {
-                        return false;
-                    }
-                    value.SetToDateTime(daypart, (int)timepart);
-                    break;
-
-                case TdsEnums.SQLUNIQUEID:
-                    {
-                        Debug.Assert(length == 16, "invalid length for SqlGuid type!");
-                        Span<byte> b = stackalloc byte[16];
-                        if (!stateObj.TryReadByteArray(b, length))
-                        {
-                            return false;
-                        }
-                        value.Guid = ConstructGuid(b);
-                        break;
-                    }
-
-                case TdsEnums.SQLBINARY:
-                case TdsEnums.SQLBIGBINARY:
-                case TdsEnums.SQLBIGVARBINARY:
-                case TdsEnums.SQLVARBINARY:
-                case TdsEnums.SQLIMAGE:
-                    {
-                        // Note: Better not come here with plp data!!
-                        Debug.Assert(length <= TdsEnums.MAXSIZE);
-                        byte[] b = new byte[length];
-                        if (!stateObj.TryReadByteArray(b, length))
-                        {
-                            return false;
-                        }
-                        value.SqlBinary = SqlTypeWorkarounds.SqlBinaryCtor(b, true);
-
-                        break;
-                    }
-
-                case TdsEnums.SQLVARIANT:
-                    if (!TryReadSqlVariant(value, length, stateObj))
-                    {
-                        return false;
-                    }
-                    break;
-
-                default:
-                    Debug.Fail("Unknown SqlType!" + tdsType.ToString(CultureInfo.InvariantCulture));
-                    break;
-            } // switch
-
-            return true;
-        }
-
-        //
-        // Read in a SQLVariant
-        //
-        // SQLVariant looks like:
-        // struct
-        // {
-        //      BYTE TypeTag
-        //      BYTE cbPropBytes
-        //      BYTE[] Properties
-        //      BYTE[] DataVal
-        // }
-        internal bool TryReadSqlVariant(SqlBuffer value, int lenTotal, TdsParserStateObject stateObj)
-        {
-            // get the SQLVariant type
-            byte type;
-            if (!stateObj.TryReadByte(out type))
-            {
-                return false;
-            }
-            ushort lenMax = 0; // maximum lenData of value inside variant
-
-            // read cbPropBytes
-            byte cbPropsActual;
-            if (!stateObj.TryReadByte(out cbPropsActual))
-            {
-                return false;
-            }
-            MetaType mt = MetaType.GetSqlDataType(type, 0 /*no user datatype*/, 0 /* no lenData, non-nullable type */);
-            byte cbPropsExpected = mt.PropBytes;
-
-            int lenConsumed = TdsEnums.SQLVARIANT_SIZE + cbPropsActual; // type, count of propBytes, and actual propBytes
-            int lenData = lenTotal - lenConsumed; // length of actual data
-
-            // read known properties and skip unknown properties
-            Debug.Assert(cbPropsActual >= cbPropsExpected, "cbPropsActual is less that cbPropsExpected!");
-
-            //
-            // now read the value
-            //
-            switch (type)
-            {
-                case TdsEnums.SQLBIT:
-                case TdsEnums.SQLINT1:
-                case TdsEnums.SQLINT2:
-                case TdsEnums.SQLINT4:
-                case TdsEnums.SQLINT8:
-                case TdsEnums.SQLFLT4:
-                case TdsEnums.SQLFLT8:
-                case TdsEnums.SQLMONEY:
-                case TdsEnums.SQLMONEY4:
-                case TdsEnums.SQLDATETIME:
-                case TdsEnums.SQLDATETIM4:
-                case TdsEnums.SQLUNIQUEID:
-                    if (!TryReadSqlValueInternal(value, type, lenData, stateObj))
-                    {
-                        return false;
-                    }
-                    break;
-
-                case TdsEnums.SQLDECIMALN:
-                case TdsEnums.SQLNUMERICN:
-                    {
-                        Debug.Assert(cbPropsExpected == 2, "SqlVariant: invalid PropBytes for decimal/numeric type!");
-
-                        byte precision;
-                        if (!stateObj.TryReadByte(out precision))
-                        {
-                            return false;
-                        }
-                        byte scale;
-                        if (!stateObj.TryReadByte(out scale))
-                        {
-                            return false;
-                        }
-
-                        // skip over unknown properties
-                        if (cbPropsActual > cbPropsExpected)
-                        {
-                            if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected))
-                            {
-                                return false;
-                            }
-                        }
-
-                        if (!TryReadSqlDecimal(value, TdsEnums.MAX_NUMERIC_LEN, precision, scale, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-                    }
-
-                case TdsEnums.SQLBIGBINARY:
-                case TdsEnums.SQLBIGVARBINARY:
-                    //Debug.Assert(TdsEnums.VARNULL == lenData, "SqlVariant: data length for Binary indicates null?");
-                    Debug.Assert(cbPropsExpected == 2, "SqlVariant: invalid PropBytes for binary type!");
-
-                    if (!stateObj.TryReadUInt16(out lenMax))
-                    {
-                        return false;
-                    }
-                    Debug.Assert(lenMax != TdsEnums.SQL_USHORTVARMAXLEN, "bigvarbinary(max) in a sqlvariant");
-
-                    // skip over unknown properties
-                    if (cbPropsActual > cbPropsExpected)
-                    {
-                        if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected))
-                        {
-                            return false;
-                        }
-                    }
-
-                    goto case TdsEnums.SQLBIT;
-
-                case TdsEnums.SQLBIGCHAR:
-                case TdsEnums.SQLBIGVARCHAR:
-                case TdsEnums.SQLNCHAR:
-                case TdsEnums.SQLNVARCHAR:
-                    {
-                        Debug.Assert(cbPropsExpected == 7, "SqlVariant: invalid PropBytes for character type!");
-
-                        SqlCollation collation;
-                        if (!TryProcessCollation(stateObj, out collation))
-                        {
-                            return false;
-                        }
-
-                        if (!stateObj.TryReadUInt16(out lenMax))
-                        {
-                            return false;
-                        }
-                        Debug.Assert(lenMax != TdsEnums.SQL_USHORTVARMAXLEN, "bigvarchar(max) or nvarchar(max) in a sqlvariant");
-
-                        // skip over unknown properties
-                        if (cbPropsActual > cbPropsExpected)
-                        {
-                            if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected))
-                            {
-                                return false;
-                            }
-                        }
-
-                        Encoding encoding = Encoding.GetEncoding(GetCodePage(collation, stateObj));
-                        if (!TryReadSqlStringValue(value, type, lenData, encoding, false, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-                    }
-                case TdsEnums.SQLDATE:
-                    if (!TryReadSqlDateTime(value, type, lenData, 0, stateObj))
-                    {
-                        return false;
-                    }
-                    break;
-
-                case TdsEnums.SQLTIME:
-                case TdsEnums.SQLDATETIME2:
-                case TdsEnums.SQLDATETIMEOFFSET:
-                    {
-                        Debug.Assert(cbPropsExpected == 1, "SqlVariant: invalid PropBytes for time/datetime2/datetimeoffset type!");
-
-                        byte scale;
-                        if (!stateObj.TryReadByte(out scale))
-                        {
-                            return false;
-                        }
-
-                        // skip over unknown properties
-                        if (cbPropsActual > cbPropsExpected)
-                        {
-                            if (!stateObj.TrySkipBytes(cbPropsActual - cbPropsExpected))
-                            {
-                                return false;
-                            }
-                        }
-
-                        if (!TryReadSqlDateTime(value, type, lenData, scale, stateObj))
-                        {
-                            return false;
-                        }
-                        break;
-                    }
-
-                default:
-                    Debug.Fail("Unknown tds type in SqlVariant!" + type.ToString(CultureInfo.InvariantCulture));
-                    break;
-            } // switch
-
-            return true;
-        }
-
-        //
-        // Translates a com+ object -> SqlVariant
-        // when the type is ambiguous, we always convert to the bigger type
-        // note that we also write out the maxlen and actuallen members (4 bytes each)
-        // in addition to the SQLVariant structure
-        //
-        internal Task WriteSqlVariantValue(object value, int length, int offset, TdsParserStateObject stateObj, bool canAccumulate = true)
-        {
-            // handle null values
-            if (ADP.IsNull(value))
-            {
-                WriteInt(TdsEnums.FIXEDNULL, stateObj); //maxlen
-                WriteInt(TdsEnums.FIXEDNULL, stateObj); //actuallen
-                return null;
-            }
-
-            MetaType mt = MetaType.GetMetaTypeFromValue(value);
-
-            // Special case data type correction for SqlMoney inside a SqlVariant.
-            if ((TdsEnums.SQLNUMERICN == mt.TDSType) && (8 == length))
-            {
-                // The caller will coerce all SqlTypes to native CLR types, which means SqlMoney will
-                // coerce to decimal/SQLNUMERICN (via SqlMoney.Value call).  In the case where the original
-                // value was SqlMoney the caller will also pass in the metadata length for the SqlMoney type
-                // which is 8 bytes.  To honor the intent of the caller here we coerce this special case
-                // input back to SqlMoney from decimal/SQLNUMERICN.
-                mt = MetaType.GetMetaTypeFromValue(new SqlMoney((decimal)value));
-            }
-
-            if (mt.IsAnsiType)
-            {
-                length = GetEncodingCharLength((string)value, length, 0, _defaultEncoding);
-            }
-
-            // max and actual len are equal to
-            // SQLVARIANTSIZE {type (1 byte) + cbPropBytes (1 byte)} + cbPropBytes + length (actual length of data in bytes)
-            WriteInt(TdsEnums.SQLVARIANT_SIZE + mt.PropBytes + length, stateObj); // maxLen
-            WriteInt(TdsEnums.SQLVARIANT_SIZE + mt.PropBytes + length, stateObj); // actualLen
-
-            // write the SQLVariant header (type and cbPropBytes)
-            stateObj.WriteByte(mt.TDSType);
-            stateObj.WriteByte(mt.PropBytes);
-
-            // now write the actual PropBytes and data
-            switch (mt.TDSType)
-            {
-                case TdsEnums.SQLFLT4:
-                    WriteFloat((float)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLFLT8:
-                    WriteDouble((double)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT8:
-                    WriteLong((long)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT4:
-                    WriteInt((int)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT2:
-                    WriteShort((short)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT1:
-                    stateObj.WriteByte((byte)value);
-                    break;
-
-                case TdsEnums.SQLBIT:
-                    if ((bool)value == true)
-                        stateObj.WriteByte(1);
-                    else
-                        stateObj.WriteByte(0);
-
-                    break;
-
-                case TdsEnums.SQLBIGVARBINARY:
-                    {
-                        byte[] b = (byte[])value;
-
-                        WriteShort(length, stateObj); // propbytes: varlen
-                        return stateObj.WriteByteArray(b, length, offset, canAccumulate);
-                    }
-
-                case TdsEnums.SQLBIGVARCHAR:
-                    {
-                        string s = (string)value;
-
-                        WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
-                        stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
-                        WriteShort(length, stateObj); // propbyte: varlen
-                        return WriteEncodingChar(s, _defaultEncoding, stateObj, canAccumulate);
-                    }
-
-                case TdsEnums.SQLUNIQUEID:
-                    {
-                        System.Guid guid = (System.Guid)value;
-                        Span<byte> b = stackalloc byte[16];
-                        TdsParser.FillGuidBytes(guid, b);
-                        Debug.Assert((length == b.Length) && (length == 16), "Invalid length for guid type in com+ object");
-                        stateObj.WriteByteSpan(b);
-                        break;
-                    }
-
-                case TdsEnums.SQLNVARCHAR:
-                    {
-                        string s = (string)value;
-
-                        WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
-                        stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
-                        WriteShort(length, stateObj); // propbyte: varlen
-
-                        // string takes cchar, not cbyte so convert
-                        length >>= 1;
-                        return WriteString(s, length, offset, stateObj, canAccumulate);
-                    }
-
-                case TdsEnums.SQLDATETIME:
-                    {
-                        TdsDateTime dt = MetaType.FromDateTime((DateTime)value, 8);
-
-                        WriteInt(dt.days, stateObj);
-                        WriteInt(dt.time, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLMONEY:
-                    {
-                        WriteCurrency((decimal)value, 8, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLNUMERICN:
-                    {
-                        stateObj.WriteByte(mt.Precision); //propbytes: precision
-                        stateObj.WriteByte((byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10)); // propbytes: scale
-                        WriteDecimal((decimal)value, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLTIME:
-                    stateObj.WriteByte(mt.Scale); //propbytes: scale
-                    WriteTime((TimeSpan)value, mt.Scale, length, stateObj);
-                    break;
-
-                case TdsEnums.SQLDATETIMEOFFSET:
-                    stateObj.WriteByte(mt.Scale); //propbytes: scale
-                    WriteDateTimeOffset((DateTimeOffset)value, mt.Scale, length, stateObj);
-                    break;
-
-                default:
-                    Debug.Fail("unknown tds type for sqlvariant!");
-                    break;
-            } // switch
-            // return point for accumulated writes, note: non-accumulated writes returned from their case statements
-            return null;
-        }
-
-        // todo: since we now know the difference between SqlWriteVariantValue and SqlWriteRowDataVariant we should consider
-        // combining these tow methods.
-
-        //
-        // Translates a com+ object -> SqlVariant
-        // when the type is ambiguous, we always convert to the bigger type
-        // note that we also write out the maxlen and actuallen members (4 bytes each)
-        // in addition to the SQLVariant structure
-        //
-        // Devnote: DataRows are preceded by Metadata. The Metadata includes the MaxLen value.
-        // Therefore the sql_variant value must not include the MaxLength. This is the major difference
-        // between this method and WriteSqlVariantValue above.
-        //
-        internal Task WriteSqlVariantDataRowValue(object value, TdsParserStateObject stateObj, bool canAccumulate = true)
-        {
-            // handle null values
-            if ((null == value) || (DBNull.Value == value))
-            {
-                WriteInt(TdsEnums.FIXEDNULL, stateObj);
-                return null;
-            }
-
-            MetaType metatype = MetaType.GetMetaTypeFromValue(value);
-            int length = 0;
-
-            if (metatype.IsAnsiType)
-            {
-                length = GetEncodingCharLength((string)value, length, 0, _defaultEncoding);
-            }
-
-            switch (metatype.TDSType)
-            {
-                case TdsEnums.SQLFLT4:
-                    WriteSqlVariantHeader(6, metatype.TDSType, metatype.PropBytes, stateObj);
-                    WriteFloat((float)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLFLT8:
-                    WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
-                    WriteDouble((double)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT8:
-                    WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
-                    WriteLong((long)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT4:
-                    WriteSqlVariantHeader(6, metatype.TDSType, metatype.PropBytes, stateObj);
-                    WriteInt((int)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT2:
-                    WriteSqlVariantHeader(4, metatype.TDSType, metatype.PropBytes, stateObj);
-                    WriteShort((short)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLINT1:
-                    WriteSqlVariantHeader(3, metatype.TDSType, metatype.PropBytes, stateObj);
-                    stateObj.WriteByte((byte)value);
-                    break;
-
-                case TdsEnums.SQLBIT:
-                    WriteSqlVariantHeader(3, metatype.TDSType, metatype.PropBytes, stateObj);
-                    if ((bool)value == true)
-                        stateObj.WriteByte(1);
-                    else
-                        stateObj.WriteByte(0);
-
-                    break;
-
-                case TdsEnums.SQLBIGVARBINARY:
-                    {
-                        byte[] b = (byte[])value;
-
-                        length = b.Length;
-                        WriteSqlVariantHeader(4 + length, metatype.TDSType, metatype.PropBytes, stateObj);
-                        WriteShort(length, stateObj); // propbytes: varlen
-                        return stateObj.WriteByteArray(b, length, 0, canAccumulate);
-                    }
-
-                case TdsEnums.SQLBIGVARCHAR:
-                    {
-                        string s = (string)value;
-
-                        length = s.Length;
-                        WriteSqlVariantHeader(9 + length, metatype.TDSType, metatype.PropBytes, stateObj);
-                        WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
-                        stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
-                        WriteShort(length, stateObj);
-                        return WriteEncodingChar(s, _defaultEncoding, stateObj, canAccumulate);
-                    }
-
-                case TdsEnums.SQLUNIQUEID:
-                    {
-                        System.Guid guid = (System.Guid)value;
-
-                        Span<byte> b = stackalloc byte[16];
-                        FillGuidBytes(guid, b);
-                        length = b.Length;
-                        Debug.Assert(length == 16, "Invalid length for guid type in com+ object");
-                        WriteSqlVariantHeader(18, metatype.TDSType, metatype.PropBytes, stateObj);
-                        stateObj.WriteByteSpan(b);
-
-                        break;
-                    }
-
-                case TdsEnums.SQLNVARCHAR:
-                    {
-                        string s = (string)value;
-
-                        length = s.Length * 2;
-                        WriteSqlVariantHeader(9 + length, metatype.TDSType, metatype.PropBytes, stateObj);
-                        WriteUnsignedInt(_defaultCollation.info, stateObj); // propbytes: collation.Info
-                        stateObj.WriteByte(_defaultCollation.sortId); // propbytes: collation.SortId
-                        WriteShort(length, stateObj); // propbyte: varlen
-
-                        // string takes cchar, not cbyte so convert
-                        length >>= 1;
-                        return WriteString(s, length, 0, stateObj, canAccumulate);
-                    }
-
-                case TdsEnums.SQLDATETIME:
-                    {
-                        TdsDateTime dt = MetaType.FromDateTime((DateTime)value, 8);
-
-                        WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
-                        WriteInt(dt.days, stateObj);
-                        WriteInt(dt.time, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLMONEY:
-                    {
-                        WriteSqlVariantHeader(10, metatype.TDSType, metatype.PropBytes, stateObj);
-                        WriteCurrency((decimal)value, 8, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLNUMERICN:
-                    {
-                        WriteSqlVariantHeader(21, metatype.TDSType, metatype.PropBytes, stateObj);
-                        stateObj.WriteByte(metatype.Precision); //propbytes: precision
-                        stateObj.WriteByte((byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10)); // propbytes: scale
-                        WriteDecimal((decimal)value, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLTIME:
-                    WriteSqlVariantHeader(8, metatype.TDSType, metatype.PropBytes, stateObj);
-                    stateObj.WriteByte(metatype.Scale); //propbytes: scale
-                    WriteTime((TimeSpan)value, metatype.Scale, 5, stateObj);
-                    break;
-
-                case TdsEnums.SQLDATETIMEOFFSET:
-                    WriteSqlVariantHeader(13, metatype.TDSType, metatype.PropBytes, stateObj);
-                    stateObj.WriteByte(metatype.Scale); //propbytes: scale
-                    WriteDateTimeOffset((DateTimeOffset)value, metatype.Scale, 10, stateObj);
-                    break;
-
-                default:
-                    Debug.Fail("unknown tds type for sqlvariant!");
-                    break;
-            } // switch
-            // return point for accumulated writes, note: non-accumulated writes returned from their case statements
-            return null;
-        }
-
-        internal void WriteSqlVariantHeader(int length, byte tdstype, byte propbytes, TdsParserStateObject stateObj)
-        {
-            WriteInt(length, stateObj);
-            stateObj.WriteByte(tdstype);
-            stateObj.WriteByte(propbytes);
-        }
-
-        internal void WriteSqlVariantDateTime2(DateTime value, TdsParserStateObject stateObj)
-        {
-            MSS.SmiMetaData dateTime2MetaData = MSS.SmiMetaData.DefaultDateTime2;
-            // NOTE: 3 bytes added here to support additional header information for variant - internal type, scale prop, scale
-            WriteSqlVariantHeader((int)(dateTime2MetaData.MaxLength + 3), TdsEnums.SQLDATETIME2, 1 /* one scale prop */, stateObj);
-            stateObj.WriteByte(dateTime2MetaData.Scale); //scale property
-            WriteDateTime2(value, dateTime2MetaData.Scale, (int)(dateTime2MetaData.MaxLength), stateObj);
-        }
-
-        internal void WriteSqlVariantDate(DateTime value, TdsParserStateObject stateObj)
-        {
-            MSS.SmiMetaData dateMetaData = MSS.SmiMetaData.DefaultDate;
-            // NOTE: 2 bytes added here to support additional header information for variant - internal type, scale prop (ignoring scale here)
-            WriteSqlVariantHeader((int)(dateMetaData.MaxLength + 2), TdsEnums.SQLDATE, 0 /* one scale prop */, stateObj);
-            WriteDate(value, stateObj);
-        }
-
-        private void WriteSqlMoney(SqlMoney value, int length, TdsParserStateObject stateObj)
-        {
-            int[] bits = decimal.GetBits(value.Value);
-
-            // this decimal should be scaled by 10000 (regardless of what the incoming decimal was scaled by)
-            bool isNeg = (0 != (bits[3] & unchecked((int)0x80000000)));
-            long l = ((long)(uint)bits[1]) << 0x20 | (uint)bits[0];
-
-            if (isNeg)
-                l = -l;
-
-            if (length == 4)
-            {
-                decimal decimalValue = value.Value;
-
-                // validate the value can be represented as a small money
-                if (decimalValue < TdsEnums.SQL_SMALL_MONEY_MIN || decimalValue > TdsEnums.SQL_SMALL_MONEY_MAX)
-                {
-                    throw SQL.MoneyOverflow(decimalValue.ToString(CultureInfo.InvariantCulture));
-                }
-
-                WriteInt((int)l, stateObj);
-            }
-            else
-            {
-                WriteInt((int)(l >> 0x20), stateObj);
-                WriteInt((int)l, stateObj);
-            }
-        }
-
-        private void WriteCurrency(decimal value, int length, TdsParserStateObject stateObj)
-        {
-            SqlMoney m = new SqlMoney(value);
-            int[] bits = decimal.GetBits(m.Value);
-
-            // this decimal should be scaled by 10000 (regardless of what the incoming decimal was scaled by)
-            bool isNeg = (0 != (bits[3] & unchecked((int)0x80000000)));
-            long l = ((long)(uint)bits[1]) << 0x20 | (uint)bits[0];
-
-            if (isNeg)
-                l = -l;
-
-            if (length == 4)
-            {
-                // validate the value can be represented as a small money
-                if (value < TdsEnums.SQL_SMALL_MONEY_MIN || value > TdsEnums.SQL_SMALL_MONEY_MAX)
-                {
-                    throw SQL.MoneyOverflow(value.ToString(CultureInfo.InvariantCulture));
-                }
-
-                WriteInt((int)l, stateObj);
-            }
-            else
-            {
-                WriteInt((int)(l >> 0x20), stateObj);
-                WriteInt((int)l, stateObj);
-            }
-        }
-
-        private void WriteDate(DateTime value, TdsParserStateObject stateObj)
-        {
-            long days = value.Subtract(DateTime.MinValue).Days;
-            WritePartialLong(days, 3, stateObj);
-        }
-
-        private void WriteTime(TimeSpan value, byte scale, int length, TdsParserStateObject stateObj)
-        {
-            if (0 > value.Ticks || value.Ticks >= TimeSpan.TicksPerDay)
-            {
-                throw SQL.TimeOverflow(value.ToString());
-            }
-            long time = value.Ticks / TdsEnums.TICKS_FROM_SCALE[scale];
-            WritePartialLong(time, length, stateObj);
-        }
-
-        private void WriteDateTime2(DateTime value, byte scale, int length, TdsParserStateObject stateObj)
-        {
-            long time = value.TimeOfDay.Ticks / TdsEnums.TICKS_FROM_SCALE[scale]; // DateTime.TimeOfDay always returns a valid TimeSpan for Time
-            WritePartialLong(time, length - 3, stateObj);
-            WriteDate(value, stateObj);
-        }
-
-        private void WriteDateTimeOffset(DateTimeOffset value, byte scale, int length, TdsParserStateObject stateObj)
-        {
-            WriteDateTime2(value.UtcDateTime, scale, length - 2, stateObj);
-            short offset = (short)value.Offset.TotalMinutes;
-            stateObj.WriteByte((byte)(offset & 0xff));
-            stateObj.WriteByte((byte)((offset >> 8) & 0xff));
-        }
-
-        private bool TryReadSqlDecimal(SqlBuffer value, int length, byte precision, byte scale, TdsParserStateObject stateObj)
-        {
-            byte byteValue;
-            if (!stateObj.TryReadByte(out byteValue))
-            {
-                return false;
-            }
-            bool fPositive = (1 == byteValue);
-
-            length = checked((int)length - 1);
-
-            int[] bits;
-            if (!TryReadDecimalBits(length, stateObj, out bits))
-            {
-                return false;
-            }
-
-            value.SetToDecimal(precision, scale, fPositive, bits);
-            return true;
-        }
-
-        // @devnote: length should be size of decimal without the sign
-        // @devnote: sign should have already been read off the wire
-        private bool TryReadDecimalBits(int length, TdsParserStateObject stateObj, out int[] bits)
-        {
-            bits = stateObj._decimalBits; // used alloc'd array if we have one already
-            int i;
-
-            if (null == bits)
-            {
-                bits = new int[4];
-                stateObj._decimalBits = bits;
-            }
-            else
-            {
-                for (i = 0; i < bits.Length; i++)
-                    bits[i] = 0;
-            }
-
-            Debug.Assert((length > 0) &&
-                         (length <= TdsEnums.MAX_NUMERIC_LEN - 1) &&
-                         (length % 4 == 0), "decimal should have 4, 8, 12, or 16 bytes of data");
-
-            int decLength = length >> 2;
-
-            for (i = 0; i < decLength; i++)
-            {
-                // up to 16 bytes of data following the sign byte
-                if (!stateObj.TryReadInt32(out bits[i]))
-                {
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        internal static SqlDecimal AdjustSqlDecimalScale(SqlDecimal d, int newScale)
-        {
-            if (d.Scale != newScale)
-            {
-                return SqlDecimal.AdjustScale(d, newScale - d.Scale, false /* Don't round, truncate. */);
-            }
-
-            return d;
-        }
-
-        internal static decimal AdjustDecimalScale(decimal value, int newScale)
-        {
-            int oldScale = (decimal.GetBits(value)[3] & 0x00ff0000) >> 0x10;
-
-            if (newScale != oldScale)
-            {
-                SqlDecimal num = new SqlDecimal(value);
-
-                num = SqlDecimal.AdjustScale(num, newScale - oldScale, false /* Don't round, truncate.  */);
-                return num.Value;
-            }
-
-            return value;
-        }
-
-        internal void WriteSqlDecimal(SqlDecimal d, TdsParserStateObject stateObj)
-        {
-            // sign
-            if (d.IsPositive)
-                stateObj.WriteByte(1);
-            else
-                stateObj.WriteByte(0);
-
-            uint data1, data2, data3, data4;
-            SqlTypeWorkarounds.SqlDecimalExtractData(d, out data1, out data2, out data3, out data4);
-            WriteUnsignedInt(data1, stateObj);
-            WriteUnsignedInt(data2, stateObj);
-            WriteUnsignedInt(data3, stateObj);
-            WriteUnsignedInt(data4, stateObj);
-        }
-
-        private void WriteDecimal(decimal value, TdsParserStateObject stateObj)
-        {
-            stateObj._decimalBits = decimal.GetBits(value);
-            Debug.Assert(null != stateObj._decimalBits, "decimalBits should be filled in at TdsExecuteRPC time");
-
-            /*
-             Returns a binary representation of a Decimal. The return value is an integer
-             array with four elements. Elements 0, 1, and 2 contain the low, middle, and
-             high 32 bits of the 96-bit integer part of the Decimal. Element 3 contains
-             the scale factor and sign of the Decimal: bits 0-15 (the lower word) are
-             unused; bits 16-23 contain a value between 0 and 28, indicating the power of
-             10 to divide the 96-bit integer part by to produce the Decimal value; bits 24-
-             30 are unused; and finally bit 31 indicates the sign of the Decimal value, 0
-             meaning positive and 1 meaning negative.
-
-             SQLDECIMAL/SQLNUMERIC has a byte stream of:
-             struct {
-                 BYTE sign; // 1 if positive, 0 if negative
-                 BYTE data[];
-             }
-
-             For TDS 7.0 and above, there are always 17 bytes of data
-            */
-
-            // write the sign (note that COM and SQL are opposite)
-            if (0x80000000 == (stateObj._decimalBits[3] & 0x80000000))
-                stateObj.WriteByte(0);
-            else
-                stateObj.WriteByte(1);
-
-            WriteInt(stateObj._decimalBits[0], stateObj);
-            WriteInt(stateObj._decimalBits[1], stateObj);
-            WriteInt(stateObj._decimalBits[2], stateObj);
-            WriteInt(0, stateObj);
-        }
-
-        private void WriteIdentifier(string s, TdsParserStateObject stateObj)
-        {
-            if (null != s)
-            {
-                stateObj.WriteByte(checked((byte)s.Length));
-                WriteString(s, stateObj);
-            }
-            else
-            {
-                stateObj.WriteByte((byte)0);
-            }
-        }
-
-        private void WriteIdentifierWithShortLength(string s, TdsParserStateObject stateObj)
-        {
-            if (null != s)
-            {
-                WriteShort(checked((short)s.Length), stateObj);
-                WriteString(s, stateObj);
-            }
-            else
-            {
-                WriteShort(0, stateObj);
-            }
-        }
-
-        private Task WriteString(string s, TdsParserStateObject stateObj, bool canAccumulate = true)
-        {
-            return WriteString(s, s.Length, 0, stateObj, canAccumulate);
-        }
-
-        internal Task WriteCharArray(char[] carr, int length, int offset, TdsParserStateObject stateObj, bool canAccumulate = true)
-        {
-            int cBytes = ADP.CharSize * length;
-
-            // Perf shortcut: If it fits, write directly to the outBuff
-            if (cBytes < (stateObj._outBuff.Length - stateObj._outBytesUsed))
-            {
-                CopyCharsToBytes(carr, offset, stateObj._outBuff, stateObj._outBytesUsed, length);
-                stateObj._outBytesUsed += cBytes;
-                return null;
-            }
-            else
-            {
-                if (stateObj._bTmp == null || stateObj._bTmp.Length < cBytes)
-                {
-                    stateObj._bTmp = new byte[cBytes];
-                }
-
-                CopyCharsToBytes(carr, offset, stateObj._bTmp, 0, length);
-                return stateObj.WriteByteArray(stateObj._bTmp, cBytes, 0, canAccumulate);
-            }
-        }
-
-        internal Task WriteString(string s, int length, int offset, TdsParserStateObject stateObj, bool canAccumulate = true)
-        {
-            int cBytes = ADP.CharSize * length;
-
-            // Perf shortcut: If it fits, write directly to the outBuff
-            if (cBytes < (stateObj._outBuff.Length - stateObj._outBytesUsed))
-            {
-                CopyStringToBytes(s, offset, stateObj._outBuff, stateObj._outBytesUsed, length);
-                stateObj._outBytesUsed += cBytes;
-                return null;
-            }
-            else
-            {
-                if (stateObj._bTmp == null || stateObj._bTmp.Length < cBytes)
-                {
-                    stateObj._bTmp = new byte[cBytes];
-                }
-
-                CopyStringToBytes(s, offset, stateObj._bTmp, 0, length);
-                return stateObj.WriteByteArray(stateObj._bTmp, cBytes, 0, canAccumulate);
-            }
-        }
-
-
-        private static void CopyCharsToBytes(char[] source, int sourceOffset, byte[] dest, int destOffset, int charLength)
-        {
-            Buffer.BlockCopy(source, sourceOffset, dest, destOffset, charLength * ADP.CharSize);
-        }
-
-        private static void CopyStringToBytes(string source, int sourceOffset, byte[] dest, int destOffset, int charLength)
-        {
-            Encoding.Unicode.GetBytes(source, sourceOffset, charLength, dest, destOffset);
-        }
-
-        private Task WriteEncodingChar(string s, Encoding encoding, TdsParserStateObject stateObj, bool canAccumulate = true)
-        {
-            return WriteEncodingChar(s, s.Length, 0, encoding, stateObj, canAccumulate);
-        }
-
-        private Task WriteEncodingChar(string s, int numChars, int offset, Encoding encoding, TdsParserStateObject stateObj, bool canAccumulate = true)
-        {
-            char[] charData;
-            byte[] byteData;
-
-            // if hitting 7.0 server, encoding will be null in metadata for columns or return values since
-            // 7.0 has no support for multiple code pages in data - single code page support only
-            if (encoding == null)
-                encoding = _defaultEncoding;
-
-            charData = s.ToCharArray(offset, numChars);
-
-            // Optimization: if the entire string fits in the current buffer, then copy it directly
-            int bytesLeft = stateObj._outBuff.Length - stateObj._outBytesUsed;
-            if ((numChars <= bytesLeft) && (encoding.GetMaxByteCount(charData.Length) <= bytesLeft))
-            {
-                int bytesWritten = encoding.GetBytes(charData, 0, charData.Length, stateObj._outBuff, stateObj._outBytesUsed);
-                stateObj._outBytesUsed += bytesWritten;
-                return null;
-            }
-            else
-            {
-                byteData = encoding.GetBytes(charData, 0, numChars);
-                Debug.Assert(byteData != null, "no data from encoding");
-                return stateObj.WriteByteArray(byteData, byteData.Length, 0, canAccumulate);
-            }
-        }
-
-        internal int GetEncodingCharLength(string value, int numChars, int charOffset, Encoding encoding)
-        {
-            if (value == null || value == string.Empty)
-            {
-                return 0;
-            }
-
-            // if hitting 7.0 server, encoding will be null in metadata for columns or return values since
-            // 7.0 has no support for multiple code pages in data - single code page support only
-            if (encoding == null)
-            {
-                if (null == _defaultEncoding)
-                {
-                    ThrowUnsupportedCollationEncountered(null);
-                }
-
-                encoding = _defaultEncoding;
-            }
-
-            char[] charData = value.ToCharArray(charOffset, numChars);
-
-            return encoding.GetByteCount(charData, 0, numChars);
-        }
-
-        //
-        // Returns the data stream length of the data identified by tds type or SqlMetaData returns
-        // Returns either the total size or the size of the first chunk for partially length prefixed types.
-        //
-        internal bool TryGetDataLength(SqlMetaDataPriv colmeta, TdsParserStateObject stateObj, out ulong length)
-        {
-            // Handle Yukon specific tokens
-            if (colmeta.metaType.IsPlp)
-            {
-                Debug.Assert(colmeta.tdsType == TdsEnums.SQLXMLTYPE ||
-                             colmeta.tdsType == TdsEnums.SQLBIGVARCHAR ||
-                             colmeta.tdsType == TdsEnums.SQLBIGVARBINARY ||
-                             colmeta.tdsType == TdsEnums.SQLNVARCHAR ||
-                             // Large UDTs is WinFS-only
-                             colmeta.tdsType == TdsEnums.SQLUDT,
-                             "GetDataLength:Invalid streaming datatype");
-                return stateObj.TryReadPlpLength(true, out length);
-            }
-            else
-            {
-                int intLength;
-                if (!TryGetTokenLength(colmeta.tdsType, stateObj, out intLength))
-                {
-                    length = 0;
-                    return false;
-                }
-                length = (ulong)intLength;
-                return true;
-            }
-        }
-
-        //
-        // returns the token length of the token or tds type
-        // Returns -1 for partially length prefixed (plp) types for metadata info.
-        // DOES NOT handle plp data streams correctly!!!
-        // Plp data streams length information should be obtained from GetDataLength
-        //
-        internal bool TryGetTokenLength(byte token, TdsParserStateObject stateObj, out int tokenLength)
-        {
-            Debug.Assert(token != 0, "0 length token!");
-
-            switch (token)
-            { // rules about SQLLenMask no longer apply to new tokens (as of 7.4)
-                case TdsEnums.SQLFEATUREEXTACK:
-                    tokenLength = -1;
-                    return true;
-                case TdsEnums.SQLSESSIONSTATE:
-                    return stateObj.TryReadInt32(out tokenLength);
-            }
-
-            {
-                if (token == TdsEnums.SQLUDT)
-                { // special case for UDTs
-                    tokenLength = -1; // Should we return -1 or not call GetTokenLength for UDTs?
-                    return true;
-                }
-                else if (token == TdsEnums.SQLRETURNVALUE)
-                {
-                    tokenLength = -1; // In Yukon, the RETURNVALUE token stream no longer has length
-                    return true;
-                }
-                else if (token == TdsEnums.SQLXMLTYPE)
-                {
-                    ushort value;
-                    if (!stateObj.TryReadUInt16(out value))
-                    {
-                        tokenLength = 0;
-                        return false;
-                    }
-                    tokenLength = (int)value;
-                    Debug.Assert(tokenLength == TdsEnums.SQL_USHORTVARMAXLEN, "Invalid token stream for xml datatype");
-                    return true;
-                }
-            }
-
-            switch (token & TdsEnums.SQLLenMask)
-            {
-                case TdsEnums.SQLFixedLen:
-                    tokenLength = ((0x01 << ((token & 0x0c) >> 2))) & 0xff;
-                    return true;
-                case TdsEnums.SQLZeroLen:
-                    tokenLength = 0;
-                    return true;
-                case TdsEnums.SQLVarLen:
-                case TdsEnums.SQLVarCnt:
-                    if (0 != (token & 0x80))
-                    {
-                        ushort value;
-                        if (!stateObj.TryReadUInt16(out value))
-                        {
-                            tokenLength = 0;
-                            return false;
-                        }
-                        tokenLength = value;
-                        return true;
-                    }
-                    else if (0 == (token & 0x0c))
-                    {
-                        if (!stateObj.TryReadInt32(out tokenLength))
-                        {
-                            return false;
-                        }
-                        return true;
-                    }
-                    else
-                    {
-                        byte value;
-                        if (!stateObj.TryReadByte(out value))
-                        {
-                            tokenLength = 0;
-                            return false;
-                        }
-                        tokenLength = value;
-                        return true;
-                    }
-                default:
-                    Debug.Fail("Unknown token length!");
-                    tokenLength = 0;
-                    return true;
-            }
-        }
-
-        private void ProcessAttention(TdsParserStateObject stateObj)
-        {
-            if (_state == TdsParserState.Closed || _state == TdsParserState.Broken)
-            {
-                return;
-            }
-            Debug.Assert(stateObj._attentionSent, "invalid attempt to ProcessAttention, attentionSent == false!");
-
-            // Attention processing scenarios:
-            // 1) EOM packet with header ST_AACK bit plus DONE with status DONE_ATTN
-            // 2) Packet without ST_AACK header bit but has DONE with status DONE_ATTN
-            // 3) Secondary timeout occurs while reading, break connection
-
-            // Since errors can occur and we need to cancel prior to throwing those errors, we
-            // cache away error state and then process TDS for the attention.  We restore those
-            // errors after processing.
-            stateObj.StoreErrorAndWarningForAttention();
-
-            try
-            {
-                // Call run loop to process looking for attention ack.
-                Run(RunBehavior.Attention, null, null, null, stateObj);
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-
-                // If an exception occurs - break the connection.
-                // Attention error will not be thrown in this case by Run(), but other failures may.
-                _state = TdsParserState.Broken;
-                _connHandler.BreakConnection();
-
-                throw;
-            }
-
-            stateObj.RestoreErrorAndWarningAfterAttention();
-
-            Debug.Assert(!stateObj._attentionSent, "Invalid attentionSent state at end of ProcessAttention");
-        }
-
-        private static int StateValueLength(int dataLen)
-        {
-            return dataLen < 0xFF ? (dataLen + 1) : (dataLen + 5);
-        }
-
-        internal int WriteSessionRecoveryFeatureRequest(SessionData reconnectData, bool write /* if false just calculates the length */)
-        {
-            int len = 1;
-            if (write)
-            {
-                _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_SRECOVERY);
-            }
-            if (reconnectData == null)
-            {
-                if (write)
-                {
-                    WriteInt(0, _physicalStateObj);
-                }
-                len += 4;
-            }
-            else
-            {
-                Debug.Assert(reconnectData._unrecoverableStatesCount == 0, "Unrecoverable state count should be 0");
-                int initialLength = 0; // sizeof(DWORD) - length itself
-                initialLength += 1 + 2 * TdsParserStaticMethods.NullAwareStringLength(reconnectData._initialDatabase);
-                initialLength += 1 + 2 * TdsParserStaticMethods.NullAwareStringLength(reconnectData._initialLanguage);
-                initialLength += (reconnectData._initialCollation == null) ? 1 : 6;
-                for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++)
-                {
-                    if (reconnectData._initialState[i] != null)
-                    {
-                        initialLength += 1 /* StateId*/ + StateValueLength(reconnectData._initialState[i].Length);
-                    }
-                }
-                int currentLength = 0; // sizeof(DWORD) - length itself
-                currentLength += 1 + 2 * (reconnectData._initialDatabase == reconnectData._database ? 0 : TdsParserStaticMethods.NullAwareStringLength(reconnectData._database));
-                currentLength += 1 + 2 * (reconnectData._initialLanguage == reconnectData._language ? 0 : TdsParserStaticMethods.NullAwareStringLength(reconnectData._language));
-                currentLength += (reconnectData._collation != null && !SqlCollation.AreSame(reconnectData._collation, reconnectData._initialCollation)) ? 6 : 1;
-                bool[] writeState = new bool[SessionData._maxNumberOfSessionStates];
-                for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++)
-                {
-                    if (reconnectData._delta[i] != null)
-                    {
-                        Debug.Assert(reconnectData._delta[i]._recoverable, "State should be recoverable");
-                        writeState[i] = true;
-                        if (reconnectData._initialState[i] != null && reconnectData._initialState[i].Length == reconnectData._delta[i]._dataLength)
-                        {
-                            writeState[i] = false;
-                            for (int j = 0; j < reconnectData._delta[i]._dataLength; j++)
-                            {
-                                if (reconnectData._initialState[i][j] != reconnectData._delta[i]._data[j])
-                                {
-                                    writeState[i] = true;
-                                    break;
-                                }
-                            }
-                        }
-                        if (writeState[i])
-                        {
-                            currentLength += 1 /* StateId*/ + StateValueLength(reconnectData._delta[i]._dataLength);
-                        }
-                    }
-                }
-                if (write)
-                {
-                    WriteInt(8 + initialLength + currentLength, _physicalStateObj); // length of data w/o total length (initial + current + 2 * sizeof(DWORD))
-                    WriteInt(initialLength, _physicalStateObj);
-                    WriteIdentifier(reconnectData._initialDatabase, _physicalStateObj);
-                    WriteCollation(reconnectData._initialCollation, _physicalStateObj);
-                    WriteIdentifier(reconnectData._initialLanguage, _physicalStateObj);
-                    for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++)
-                    {
-                        if (reconnectData._initialState[i] != null)
-                        {
-                            _physicalStateObj.WriteByte((byte)i);
-                            if (reconnectData._initialState[i].Length < 0xFF)
-                            {
-                                _physicalStateObj.WriteByte((byte)reconnectData._initialState[i].Length);
-                            }
-                            else
-                            {
-                                _physicalStateObj.WriteByte(0xFF);
-                                WriteInt(reconnectData._initialState[i].Length, _physicalStateObj);
-                            }
-                            _physicalStateObj.WriteByteArray(reconnectData._initialState[i], reconnectData._initialState[i].Length, 0);
-                        }
-                    }
-                    WriteInt(currentLength, _physicalStateObj);
-                    WriteIdentifier(reconnectData._database != reconnectData._initialDatabase ? reconnectData._database : null, _physicalStateObj);
-                    WriteCollation(SqlCollation.AreSame(reconnectData._initialCollation, reconnectData._collation) ? null : reconnectData._collation, _physicalStateObj);
-                    WriteIdentifier(reconnectData._language != reconnectData._initialLanguage ? reconnectData._language : null, _physicalStateObj);
-                    for (int i = 0; i < SessionData._maxNumberOfSessionStates; i++)
-                    {
-                        if (writeState[i])
-                        {
-                            _physicalStateObj.WriteByte((byte)i);
-                            if (reconnectData._delta[i]._dataLength < 0xFF)
-                            {
-                                _physicalStateObj.WriteByte((byte)reconnectData._delta[i]._dataLength);
-                            }
-                            else
-                            {
-                                _physicalStateObj.WriteByte(0xFF);
-                                WriteInt(reconnectData._delta[i]._dataLength, _physicalStateObj);
-                            }
-                            _physicalStateObj.WriteByteArray(reconnectData._delta[i]._data, reconnectData._delta[i]._dataLength, 0);
-                        }
-                    }
-                }
-                len += initialLength + currentLength + 12 /* length fields (initial, current, total) */;
-            }
-            return len;
-        }
-
-        internal int WriteFedAuthFeatureRequest(FederatedAuthenticationFeatureExtensionData fedAuthFeatureData,
-                                                bool write /* if false just calculates the length */)
-        {
-            Debug.Assert(fedAuthFeatureData.libraryType == TdsEnums.FedAuthLibrary.SecurityToken,
-                "only Security Token are supported in writing feature request");
-
-            int dataLen = 0;
-            int totalLen = 0;
-
-            // set dataLen and totalLen
-            switch (fedAuthFeatureData.libraryType)
-            {
-                case TdsEnums.FedAuthLibrary.SecurityToken:
-                    Debug.Assert(fedAuthFeatureData.accessToken != null, "AccessToken should not be null.");
-                    dataLen = 1 + sizeof(int) + fedAuthFeatureData.accessToken.Length; // length of feature data = 1 byte for library and echo, security token length and sizeof(int) for token lengh itself
-                    break;
-                default:
-                    Debug.Fail("Unrecognized library type for fedauth feature extension request");
-                    break;
-            }
-
-            totalLen = dataLen + 5; // length of feature id (1 byte), data length field (4 bytes), and feature data (dataLen)
-
-            // write feature id
-            if (write)
-            {
-                _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_FEDAUTH);
-
-                // set options
-                byte options = 0x00;
-
-                // set upper 7 bits of options to indicate fed auth library type
-                switch (fedAuthFeatureData.libraryType)
-                {
-                    case TdsEnums.FedAuthLibrary.SecurityToken:
-                        Debug.Assert(_connHandler._federatedAuthenticationRequested == true, "_federatedAuthenticationRequested field should be true");
-                        options |= TdsEnums.FEDAUTHLIB_SECURITYTOKEN << 1;
-                        break;
-                    default:
-                        Debug.Fail("Unrecognized FedAuthLibrary type for feature extension request");
-                        break;
-                }
-
-                options |= (byte)(fedAuthFeatureData.fedAuthRequiredPreLoginResponse == true ? 0x01 : 0x00);
-
-                // write dataLen and options
-                WriteInt(dataLen, _physicalStateObj);
-                _physicalStateObj.WriteByte(options);
-
-                // write accessToken for FedAuthLibrary.SecurityToken
-                switch (fedAuthFeatureData.libraryType)
-                {
-                    case TdsEnums.FedAuthLibrary.SecurityToken:
-                        WriteInt(fedAuthFeatureData.accessToken.Length, _physicalStateObj);
-                        _physicalStateObj.WriteByteArray(fedAuthFeatureData.accessToken, fedAuthFeatureData.accessToken.Length, 0);
-                        break;
-                    default:
-                        Debug.Fail("Unrecognized FedAuthLibrary type for feature extension request");
-                        break;
-                }
-            }
-            return totalLen;
-        }
-
-        internal int WriteGlobalTransactionsFeatureRequest(bool write /* if false just calculates the length */)
-        {
-            int len = 5; // 1byte = featureID, 4bytes = featureData length
-
-            if (write)
-            {
-                // Write Feature ID
-                _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS);
-                WriteInt(0, _physicalStateObj); // we don't send any data
-            }
-
-            return len;
-        }
-        internal int WriteUTF8SupportFeatureRequest(bool write /* if false just calculates the length */)
-        {
-            int len = 5; // 1byte = featureID, 4bytes = featureData length, sizeof(DWORD)
-
-            if (write)
-            {
-                // Write Feature ID
-                _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_UTF8SUPPORT);
-                WriteInt(0, _physicalStateObj); // we don't send any data
-            }
-
-            return len;
-        }
-
-        internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData? fedAuthFeatureExtensionData)
-        {
-            _physicalStateObj.SetTimeoutSeconds(rec.timeout);
-
-            Debug.Assert(recoverySessionData == null || (requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0, "Recovery session data without session recovery feature request");
-            Debug.Assert(TdsEnums.MAXLEN_HOSTNAME >= rec.hostName.Length, "_workstationId.Length exceeds the max length for this value");
-
-            Debug.Assert(!rec.useSSPI || (requestedFeatures & TdsEnums.FeatureExtension.FedAuth) == 0, "Cannot use both SSPI and FedAuth");
-            Debug.Assert(fedAuthFeatureExtensionData == null || (requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0, "fedAuthFeatureExtensionData provided without fed auth feature request");
-            Debug.Assert(fedAuthFeatureExtensionData != null || (requestedFeatures & TdsEnums.FeatureExtension.FedAuth) == 0, "Fed Auth feature requested without specifying fedAuthFeatureExtensionData.");
-
-            Debug.Assert(rec.userName == null || (rec.userName != null && TdsEnums.MAXLEN_USERNAME >= rec.userName.Length), "_userID.Length exceeds the max length for this value");
-            Debug.Assert(rec.credential == null || (rec.credential != null && TdsEnums.MAXLEN_USERNAME >= rec.credential.UserId.Length), "_credential.UserId.Length exceeds the max length for this value");
-
-            Debug.Assert(rec.password == null || (rec.password != null && TdsEnums.MAXLEN_PASSWORD >= rec.password.Length), "_password.Length exceeds the max length for this value");
-            Debug.Assert(rec.credential == null || (rec.credential != null && TdsEnums.MAXLEN_PASSWORD >= rec.credential.Password.Length), "_credential.Password.Length exceeds the max length for this value");
-
-            Debug.Assert(rec.credential != null || rec.userName != null || rec.password != null, "cannot mix the new secure password system and the connection string based password");
-            Debug.Assert(rec.newSecurePassword != null || rec.newPassword != null, "cannot have both new secure change password and string based change password");
-            Debug.Assert(TdsEnums.MAXLEN_APPNAME >= rec.applicationName.Length, "_applicationName.Length exceeds the max length for this value");
-            Debug.Assert(TdsEnums.MAXLEN_SERVERNAME >= rec.serverName.Length, "_dataSource.Length exceeds the max length for this value");
-            Debug.Assert(TdsEnums.MAXLEN_LANGUAGE >= rec.language.Length, "_currentLanguage .Length exceeds the max length for this value");
-            Debug.Assert(TdsEnums.MAXLEN_DATABASE >= rec.database.Length, "_initialCatalog.Length exceeds the max length for this value");
-            Debug.Assert(TdsEnums.MAXLEN_ATTACHDBFILE >= rec.attachDBFilename.Length, "_attachDBFileName.Length exceeds the max length for this value");
-
-            Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point.");
-            _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.LoginBegin);
-            _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth);
-
-            // get the password up front to use in sspi logic below
-            byte[] encryptedPassword = null;
-            byte[] encryptedChangePassword = null;
-            int encryptedPasswordLengthInBytes;
-            int encryptedChangePasswordLengthInBytes;
-            bool useFeatureExt = (requestedFeatures != TdsEnums.FeatureExtension.None);
-
-            string userName;
-
-            if (rec.credential != null)
-            {
-                userName = rec.credential.UserId;
-                encryptedPasswordLengthInBytes = rec.credential.Password.Length * 2;
-            }
-            else
-            {
-                userName = rec.userName;
-                encryptedPassword = TdsParserStaticMethods.ObfuscatePassword(rec.password);
-                encryptedPasswordLengthInBytes = encryptedPassword.Length;  // password in clear text is already encrypted and its length is in byte
-            }
-
-            if (rec.newSecurePassword != null)
-            {
-                encryptedChangePasswordLengthInBytes = rec.newSecurePassword.Length * 2;
-            }
-            else
-            {
-                encryptedChangePassword = TdsParserStaticMethods.ObfuscatePassword(rec.newPassword);
-                encryptedChangePasswordLengthInBytes = encryptedChangePassword.Length;
-            }
-
-            // set the message type
-            _physicalStateObj._outputMessageType = TdsEnums.MT_LOGIN7;
-
-            // length in bytes
-            int length = TdsEnums.YUKON_LOG_REC_FIXED_LEN;
-
-            string clientInterfaceName = TdsEnums.SQL_PROVIDER_NAME;
-            Debug.Assert(TdsEnums.MAXLEN_CLIENTINTERFACE >= clientInterfaceName.Length, "cchCltIntName can specify at most 128 unicode characters. See Tds spec");
-
-            // add up variable-len portions (multiply by 2 for byte len of char strings)
-            //
-            checked
-            {
-                length += (rec.hostName.Length + rec.applicationName.Length +
-                            rec.serverName.Length + clientInterfaceName.Length +
-                            rec.language.Length + rec.database.Length +
-                            rec.attachDBFilename.Length) * 2;
-                if (useFeatureExt)
-                {
-                    length += 4;
-                }
-            }
-
-            // allocate memory for SSPI variables
-            byte[] rentedSSPIBuff = null;
-            byte[] outSSPIBuff = null;
-            uint outSSPILength = 0;
-
-            // only add lengths of password and username if not using SSPI or requesting federated authentication info
-            if (!rec.useSSPI && !_connHandler._federatedAuthenticationRequested)
-            {
-                checked
-                {
-                    length += (userName.Length * 2) + encryptedPasswordLengthInBytes
-                    + encryptedChangePasswordLengthInBytes;
-                }
-            }
-            else
-            {
-                if (rec.useSSPI)
-                {
-                    // now allocate proper length of buffer, and set length
-                    rentedSSPIBuff = ArrayPool<byte>.Shared.Rent((int)s_maxSSPILength);
-                    outSSPIBuff = rentedSSPIBuff;
-                    outSSPILength = s_maxSSPILength;
-
-                    // Call helper function for SSPI data and actual length.
-                    // Since we don't have SSPI data from the server, send null for the
-                    // byte[] buffer and 0 for the int length.
-                    Debug.Assert(SniContext.Snix_Login == _physicalStateObj.SniContext, $"Unexpected SniContext. Expecting Snix_Login, actual value is '{_physicalStateObj.SniContext}'");
-                    _physicalStateObj.SniContext = SniContext.Snix_LoginSspi;
-
-                    SSPIData(null, 0, ref outSSPIBuff, ref outSSPILength);
-
-                    if (outSSPILength > int.MaxValue)
-                    {
-                        throw SQL.InvalidSSPIPacketSize();  // SqlBu 332503
-                    }
-                    _physicalStateObj.SniContext = SniContext.Snix_Login;
-
-                    checked
-                    {
-                        length += (int)outSSPILength;
-                    }
-                }
-            }
-
-            int feOffset = length;
-
-            if (useFeatureExt)
-            {
-                if ((requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0)
-                {
-                    length += WriteSessionRecoveryFeatureRequest(recoverySessionData, false);
-                }
-                if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0)
-                {
-                    Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null.");
-                    length += WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: false);
-                }
-                if ((requestedFeatures & TdsEnums.FeatureExtension.GlobalTransactions) != 0)
-                {
-                    length += WriteGlobalTransactionsFeatureRequest(false);
-                }
-                if ((requestedFeatures & TdsEnums.FeatureExtension.UTF8Support) != 0)
-                {
-                    length += WriteUTF8SupportFeatureRequest(false);
-                }
-
-                length++; // for terminator
-            }
-
-            try
-            {
-                WriteInt(length, _physicalStateObj);
-                if (recoverySessionData == null)
-                {
-                    WriteInt((TdsEnums.DENALI_MAJOR << 24) | (TdsEnums.DENALI_INCREMENT << 16) | TdsEnums.DENALI_MINOR, _physicalStateObj);
-                }
-                else
-                {
-                    WriteUnsignedInt(recoverySessionData._tdsVersion, _physicalStateObj);
-                }
-                WriteInt(rec.packetSize, _physicalStateObj);
-                WriteInt(TdsEnums.CLIENT_PROG_VER, _physicalStateObj);
-                WriteInt(TdsParserStaticMethods.GetCurrentProcessIdForTdsLoginOnly(), _physicalStateObj);
-                WriteInt(0, _physicalStateObj); // connectionID is unused
-
-                // Log7Flags (DWORD)
-                int log7Flags = 0;
-
-                /*
-                 Current snapshot from TDS spec with the offsets added:
-                    0) fByteOrder:1,                // byte order of numeric data types on client
-                    1) fCharSet:1,                  // character set on client
-                    2) fFloat:2,                    // Type of floating point on client
-                    4) fDumpLoad:1,                 // Dump/Load and BCP enable
-                    5) fUseDb:1,                    // USE notification
-                    6) fDatabase:1,                 // Initial database fatal flag
-                    7) fSetLang:1,                  // SET LANGUAGE notification
-                    8) fLanguage:1,                 // Initial language fatal flag
-                    9) fODBC:1,                     // Set if client is ODBC driver
-                   10) fTranBoundary:1,             // Transaction boundary notification
-                   11) fDelegatedSec:1,             // Security with delegation is available
-                   12) fUserType:3,                 // Type of user
-                   15) fIntegratedSecurity:1,       // Set if client is using integrated security
-                   16) fSQLType:4,                  // Type of SQL sent from client
-                   20) fOLEDB:1,                    // Set if client is OLEDB driver
-                   21) fSpare1:3,                   // first bit used for read-only intent, rest unused
-                   24) fResetPassword:1,            // set if client wants to reset password
-                   25) fNoNBCAndSparse:1,           // set if client does not support NBC and Sparse column
-                   26) fUserInstance:1,             // This connection wants to connect to a SQL "user instance"
-                   27) fUnknownCollationHandling:1, // This connection can handle unknown collation correctly.
-                   28) fExtension:1                 // Extensions are used
-                   32 - total
-                */
-
-                // first byte
-                log7Flags |= TdsEnums.USE_DB_ON << 5;
-                log7Flags |= TdsEnums.INIT_DB_FATAL << 6;
-                log7Flags |= TdsEnums.SET_LANG_ON << 7;
-
-                // second byte
-                log7Flags |= TdsEnums.INIT_LANG_FATAL << 8;
-                log7Flags |= TdsEnums.ODBC_ON << 9;
-                if (rec.useReplication)
-                {
-                    log7Flags |= TdsEnums.REPL_ON << 12;
-                }
-                if (rec.useSSPI)
-                {
-                    log7Flags |= TdsEnums.SSPI_ON << 15;
-                }
-
-                // third byte
-                if (rec.readOnlyIntent)
-                {
-                    log7Flags |= TdsEnums.READONLY_INTENT_ON << 21; // read-only intent flag is a first bit of fSpare1
-                }
-
-                // 4th one
-                if (!string.IsNullOrEmpty(rec.newPassword) || (rec.newSecurePassword != null && rec.newSecurePassword.Length != 0))
-                {
-                    log7Flags |= 1 << 24;
-                }
-                if (rec.userInstance)
-                {
-                    log7Flags |= 1 << 26;
-                }
-                if (useFeatureExt)
-                {
-                    log7Flags |= 1 << 28;
-                }
-
-                WriteInt(log7Flags, _physicalStateObj);
-
-                WriteInt(0, _physicalStateObj);  // ClientTimeZone is not used
-                WriteInt(0, _physicalStateObj);  // LCID is unused by server
-
-                // Start writing offset and length of variable length portions
-                int offset = TdsEnums.YUKON_LOG_REC_FIXED_LEN;
-
-                // write offset/length pairs
-
-                // note that you must always set ibHostName since it indicates the beginning of the variable length section of the login record
-                WriteShort(offset, _physicalStateObj); // host name offset
-                WriteShort(rec.hostName.Length, _physicalStateObj);
-                offset += rec.hostName.Length * 2;
-
-                // Only send user/password over if not fSSPI...  If both user/password and SSPI are in login
-                // rec, only SSPI is used.  Confirmed same behavior as in luxor.
-                if (rec.useSSPI == false)
-                {
-                    WriteShort(offset, _physicalStateObj);  // userName offset
-                    WriteShort(userName.Length, _physicalStateObj);
-                    offset += userName.Length * 2;
-
-                    // the encrypted password is a byte array - so length computations different than strings
-                    WriteShort(offset, _physicalStateObj); // password offset
-                    WriteShort(encryptedPasswordLengthInBytes / 2, _physicalStateObj);
-                    offset += encryptedPasswordLengthInBytes;
-                }
-                else
-                {
-                    // case where user/password data is not used, send over zeros
-                    WriteShort(0, _physicalStateObj);  // userName offset
-                    WriteShort(0, _physicalStateObj);
-                    WriteShort(0, _physicalStateObj);  // password offset
-                    WriteShort(0, _physicalStateObj);
-                }
-
-                WriteShort(offset, _physicalStateObj); // app name offset
-                WriteShort(rec.applicationName.Length, _physicalStateObj);
-                offset += rec.applicationName.Length * 2;
-
-                WriteShort(offset, _physicalStateObj); // server name offset
-                WriteShort(rec.serverName.Length, _physicalStateObj);
-                offset += rec.serverName.Length * 2;
-
-                WriteShort(offset, _physicalStateObj);
-                if (useFeatureExt)
-                {
-                    WriteShort(4, _physicalStateObj); // length of ibFeatgureExtLong (which is a DWORD)
-                    offset += 4;
-                }
-                else
-                {
-                    WriteShort(0, _physicalStateObj); // unused (was remote password ?)
-                }
-
-                WriteShort(offset, _physicalStateObj); // client interface name offset
-                WriteShort(clientInterfaceName.Length, _physicalStateObj);
-                offset += clientInterfaceName.Length * 2;
-
-                WriteShort(offset, _physicalStateObj); // language name offset
-                WriteShort(rec.language.Length, _physicalStateObj);
-                offset += rec.language.Length * 2;
-
-                WriteShort(offset, _physicalStateObj); // database name offset
-                WriteShort(rec.database.Length, _physicalStateObj);
-                offset += rec.database.Length * 2;
-
-                if (null == s_nicAddress)
-                    s_nicAddress = TdsParserStaticMethods.GetNetworkPhysicalAddressForTdsLoginOnly();
-
-                _physicalStateObj.WriteByteArray(s_nicAddress, s_nicAddress.Length, 0);
-
-                WriteShort(offset, _physicalStateObj); // ibSSPI offset
-                if (rec.useSSPI)
-                {
-                    WriteShort((int)outSSPILength, _physicalStateObj);
-                    offset += (int)outSSPILength;
-                }
-                else
-                {
-                    WriteShort(0, _physicalStateObj);
-                }
-
-                WriteShort(offset, _physicalStateObj); // DB filename offset
-                WriteShort(rec.attachDBFilename.Length, _physicalStateObj);
-                offset += rec.attachDBFilename.Length * 2;
-
-                WriteShort(offset, _physicalStateObj); // reset password offset
-                WriteShort(encryptedChangePasswordLengthInBytes / 2, _physicalStateObj);
-
-                WriteInt(0, _physicalStateObj);        // reserved for chSSPI
-
-                // write variable length portion
-                WriteString(rec.hostName, _physicalStateObj);
-
-                // if we are using SSPI, do not send over username/password, since we will use SSPI instead
-                // same behavior as Luxor
-                if (!rec.useSSPI)
-                {
-                    WriteString(userName, _physicalStateObj);
-
-                    if (rec.credential != null)
-                    {
-                        _physicalStateObj.WriteSecureString(rec.credential.Password);
-                    }
-                    else
-                    {
-                        _physicalStateObj.WriteByteArray(encryptedPassword, encryptedPasswordLengthInBytes, 0);
-                    }
-                }
-
-                WriteString(rec.applicationName, _physicalStateObj);
-                WriteString(rec.serverName, _physicalStateObj);
-
-                // write ibFeatureExtLong
-                if (useFeatureExt)
-                {
-                    WriteInt(feOffset, _physicalStateObj);
-                }
-
-                WriteString(clientInterfaceName, _physicalStateObj);
-                WriteString(rec.language, _physicalStateObj);
-                WriteString(rec.database, _physicalStateObj);
-
-                // send over SSPI data if we are using SSPI
-                if (rec.useSSPI)
-                    _physicalStateObj.WriteByteArray(outSSPIBuff, (int)outSSPILength, 0);
-
-                WriteString(rec.attachDBFilename, _physicalStateObj);
-                if (!rec.useSSPI)
-                {
-                    if (rec.newSecurePassword != null)
-                    {
-                        _physicalStateObj.WriteSecureString(rec.newSecurePassword);
-                    }
-                    else
-                    {
-                        _physicalStateObj.WriteByteArray(encryptedChangePassword, encryptedChangePasswordLengthInBytes, 0);
-                    }
-                }
-
-                if (useFeatureExt)
-                {
-                    if ((requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0)
-                    {
-                        length += WriteSessionRecoveryFeatureRequest(recoverySessionData, true);
-                    }
-                    if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0)
-                    {
-                        Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null.");
-                        WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true);
-                    }
-                    if ((requestedFeatures & TdsEnums.FeatureExtension.GlobalTransactions) != 0)
-                    {
-                        WriteGlobalTransactionsFeatureRequest(true);
-                    }
-                    if ((requestedFeatures & TdsEnums.FeatureExtension.UTF8Support) != 0)
-                    {
-                        WriteUTF8SupportFeatureRequest(true);
-                    }
-
-                    _physicalStateObj.WriteByte(0xFF); // terminator
-                }
-            }
-            catch (Exception e)
-            {
-                if (ADP.IsCatchableExceptionType(e))
-                {
-                    // be sure to wipe out our buffer if we started sending stuff
-                    _physicalStateObj.ResetPacketCounters();
-                    _physicalStateObj.ResetBuffer();
-                }
-
-                throw;
-            }
-
-            if (rentedSSPIBuff != null)
-            {
-                ArrayPool<byte>.Shared.Return(rentedSSPIBuff, clearArray: true);
-            }
-
-            _physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
-            _physicalStateObj.ResetSecurePasswordsInformation();
-            _physicalStateObj._pendingData = true;
-            _physicalStateObj._messageStatus = 0;
-        }// tdsLogin
-
-        private void SSPIData(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength)
-        {
-            SNISSPIData(receivedBuff, receivedLength, ref sendBuff, ref sendLength);
-        }
-
-
-        private void SNISSPIData(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength)
-        {
-            if (TdsParserStateObjectFactory.UseManagedSNI)
-            {
-                try
-                {
-                    _physicalStateObj.GenerateSspiClientContext(receivedBuff, receivedLength, ref sendBuff, ref sendLength, _sniSpnBuffer);
-                }
-                catch (Exception e)
-                {
-                    SSPIError(e.Message + Environment.NewLine + e.StackTrace, TdsEnums.GEN_CLIENT_CONTEXT);
-                }
-            }
-            else
-            {
-                if (receivedBuff == null)
-                {
-                    // if we do not have SSPI data coming from server, send over 0's for pointer and length
-                    receivedLength = 0;
-                }
-
-                // we need to respond to the server's message with SSPI data
-                if (0 != _physicalStateObj.GenerateSspiClientContext(receivedBuff, receivedLength, ref sendBuff, ref sendLength, _sniSpnBuffer))
-                {
-                    SSPIError(SQLMessage.SSPIGenerateError(), TdsEnums.GEN_CLIENT_CONTEXT);
-                }
-            }
-        }
-
-        private void ProcessSSPI(int receivedLength)
-        {
-            SniContext outerContext = _physicalStateObj.SniContext;
-            _physicalStateObj.SniContext = SniContext.Snix_ProcessSspi;
-            // allocate received buffer based on length from SSPI message
-            byte[] receivedBuff = ArrayPool<byte>.Shared.Rent(receivedLength);
-
-            // read SSPI data received from server
-            Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = _physicalStateObj.TryReadByteArray(receivedBuff, receivedLength);
-            if (!result)
-            { throw SQL.SynchronousCallMayNotPend(); }
-
-            // allocate send buffer and initialize length
-            byte[] rentedSendBuff = ArrayPool<byte>.Shared.Rent((int)s_maxSSPILength);
-            byte[] sendBuff = rentedSendBuff;
-            uint sendLength = s_maxSSPILength;
-
-            // make call for SSPI data
-            SSPIData(receivedBuff, (uint)receivedLength, ref sendBuff, ref sendLength);
-
-            // DO NOT SEND LENGTH - TDS DOC INCORRECT!  JUST SEND SSPI DATA!
-            _physicalStateObj.WriteByteArray(sendBuff, (int)sendLength, 0);
-
-            ArrayPool<byte>.Shared.Return(rentedSendBuff, clearArray: true);
-            ArrayPool<byte>.Shared.Return(receivedBuff, clearArray: true);
-
-            // set message type so server knows its a SSPI response
-            _physicalStateObj._outputMessageType = TdsEnums.MT_SSPI;
-
-            // send to server
-            _physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
-            _physicalStateObj.SniContext = outerContext;
-        }
-
-        private void SSPIError(string error, string procedure)
-        {
-            Debug.Assert(!string.IsNullOrEmpty(procedure), "TdsParser.SSPIError called with an empty or null procedure string");
-            Debug.Assert(!string.IsNullOrEmpty(error), "TdsParser.SSPIError called with an empty or null error string");
-
-            _physicalStateObj.AddError(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, _server, error, procedure, 0));
-            ThrowExceptionAndWarning(_physicalStateObj);
-        }
-
-        internal byte[] GetDTCAddress(int timeout, TdsParserStateObject stateObj)
-        {
-            // If this fails, the server will return a server error - Sameet Agarwal confirmed.
-            // Success: DTCAddress returned.  Failure: SqlError returned.
-
-            byte[] dtcAddr = null;
-
-            using (SqlDataReader dtcReader = TdsExecuteTransactionManagerRequest(
-                                                        null,
-                                                        TdsEnums.TransactionManagerRequestType.GetDTCAddress,
-                                                        null,
-                                                        TdsEnums.TransactionManagerIsolationLevel.Unspecified,
-                                                        timeout, null, stateObj, true))
-            {
-
-                Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, $"The SniContext should be Snix_Read but it actually is {stateObj.SniContext}");
-                if (null != dtcReader && dtcReader.Read())
-                {
-                    Debug.Assert(dtcReader.GetName(0) == "TM Address", "TdsParser: GetDTCAddress did not return 'TM Address'");
-
-                    // DTCAddress is of variable size, and does not have a maximum.  So we call GetBytes
-                    // to get the length of the dtcAddress, then allocate a byte array of that length,
-                    // then call GetBytes again on that byte[] with the length
-                    long dtcLength = dtcReader.GetBytes(0, 0, null, 0, 0);
-
-                    //
-                    if (dtcLength <= int.MaxValue)
-                    {
-                        int cb = (int)dtcLength;
-
-                        dtcAddr = new byte[cb];
-                        dtcReader.GetBytes(0, 0, dtcAddr, 0, cb);
-                    }
-#if DEBUG
-                    else
-                    {
-                        Debug.Fail("unexpected length (> Int32.MaxValue) returned from dtcReader.GetBytes");
-                        // if we hit this case we'll just return a null address so that the user
-                        // will get a transcaction enlistment error in the upper layers
-                    }
-#endif
-                }
-            }
-            return dtcAddr;
-        }
-
-        // Propagate the dtc cookie to the server, enlisting the connection.
-        internal void PropagateDistributedTransaction(byte[] buffer, int timeout, TdsParserStateObject stateObj)
-        {
-            // if this fails, the server will return a server error - Sameet Agarwal confirmed
-            // Success: server will return done token.  Failure: SqlError returned.
-
-            TdsExecuteTransactionManagerRequest(buffer,
-                TdsEnums.TransactionManagerRequestType.Propagate, null,
-                TdsEnums.TransactionManagerIsolationLevel.Unspecified, timeout, null, stateObj, true);
-        }
-
-        internal SqlDataReader TdsExecuteTransactionManagerRequest(
-                    byte[] buffer,
-                    TdsEnums.TransactionManagerRequestType request,
-                    string transactionName,
-                    TdsEnums.TransactionManagerIsolationLevel isoLevel,
-                    int timeout,
-                    SqlInternalTransaction transaction,
-                    TdsParserStateObject stateObj,
-                    bool isDelegateControlRequest
-        )
-        {
-            Debug.Assert(this == stateObj.Parser, "different parsers");
-
-            if (TdsParserState.Broken == State || TdsParserState.Closed == State)
-            {
-                return null;
-            }
-
-            // Promote, Commit and Rollback requests for
-            // delegated transactions often happen while there is an open result
-            // set, so we need to handle them by using a different MARS session,
-            // otherwise we'll write on the physical state objects while someone
-            // else is using it.  When we don't have MARS enabled, we need to
-            // lock the physical state object to synchronize its use at least
-            // until we increment the open results count.  Once it's been
-            // incremented the delegated transaction requests will fail, so they
-            // won't stomp on anything.
-
-
-            Debug.Assert(!_connHandler.ThreadHasParserLockForClose || _connHandler._parserLock.ThreadMayHaveLock(), "Thread claims to have parser lock, but lock is not taken");
-            bool callerHasConnectionLock = _connHandler.ThreadHasParserLockForClose;   // If the thread already claims to have the parser lock, then we will let the caller handle releasing it
-            if (!callerHasConnectionLock)
-            {
-                _connHandler._parserLock.Wait(canReleaseFromAnyThread: false);
-                _connHandler.ThreadHasParserLockForClose = true;
-            }
-            // Capture _asyncWrite (after taking lock) to restore it afterwards
-            bool hadAsyncWrites = _asyncWrite;
-            try
-            {
-                // Temporarily disable async writes
-                _asyncWrite = false;
-
-                // This validation step MUST be done after locking the connection to guarantee we don't
-                //  accidentally execute after the transaction has completed on a different thread.
-                if (!isDelegateControlRequest)
-                {
-                    _connHandler.CheckEnlistedTransactionBinding();
-                }
-
-                stateObj._outputMessageType = TdsEnums.MT_TRANS;       // set message type
-                stateObj.SetTimeoutSeconds(timeout);
-
-                stateObj.SniContext = SniContext.Snix_Execute;
-
-                const int marsHeaderSize = 18; // 4 + 2 + 8 + 4
-                const int totalHeaderLength = 22; // 4 + 4 + 2 + 8 + 4
-                Debug.Assert(stateObj._outBytesUsed == stateObj._outputHeaderLen, "Output bytes written before total header length");
-                // Write total header length
-                WriteInt(totalHeaderLength, stateObj);
-                // Write mars header length
-                WriteInt(marsHeaderSize, stateObj);
-                WriteMarsHeaderData(stateObj, _currentTransaction);
-
-                WriteShort((short)request, stateObj); // write TransactionManager Request type
-
-                bool returnReader = false;
-
-                switch (request)
-                {
-                    case TdsEnums.TransactionManagerRequestType.GetDTCAddress:
-                        WriteShort(0, stateObj);
-
-                        returnReader = true;
-                        break;
-                    case TdsEnums.TransactionManagerRequestType.Propagate:
-                        if (null != buffer)
-                        {
-                            WriteShort(buffer.Length, stateObj);
-                            stateObj.WriteByteArray(buffer, buffer.Length, 0);
-                        }
-                        else
-                        {
-                            WriteShort(0, stateObj);
-                        }
-                        break;
-                    case TdsEnums.TransactionManagerRequestType.Begin:
-                        Debug.Assert(null != transaction, "Should have specified an internalTransaction when doing a BeginTransaction request!");
-
-                        // Only assign the passed in transaction if it is not equal to the current transaction.
-                        // And, if it is not equal, the current actually should be null.  Anything else
-                        // is a unexpected state.  The concern here is mainly for the mixed use of
-                        // T-SQL and API transactions.
-
-                        // Expected states:
-                        // 1) _pendingTransaction = null, _currentTransaction = null, non null transaction
-                        // passed in on BeginTransaction API call.
-                        // 2) _currentTransaction != null, _pendingTransaction = null, non null transaction
-                        // passed in but equivalent to _currentTransaction.
-
-                        // #1 will occur on standard BeginTransactionAPI call.  #2 should only occur if
-                        // t-sql transaction started followed by a call to SqlConnection.BeginTransaction.
-                        // Any other state is unknown.
-                        if (_currentTransaction != transaction)
-                        {
-                            Debug.Assert(_currentTransaction == null || true == _fResetConnection, "We should not have a current Tx at this point");
-                            PendingTransaction = transaction;
-                        }
-
-                        stateObj.WriteByte((byte)isoLevel);
-
-                        stateObj.WriteByte((byte)(transactionName.Length * 2)); // Write number of bytes (unicode string).
-                        WriteString(transactionName, stateObj);
-                        break;
-                    case TdsEnums.TransactionManagerRequestType.Promote:
-                        // No payload - except current transaction in header
-                        // Promote returns a DTC cookie.  However, the transaction cookie we use for the
-                        // connection does not change after a promote.
-                        break;
-                    case TdsEnums.TransactionManagerRequestType.Commit:
-
-                        Debug.Assert(transactionName.Length == 0, "Should not have a transaction name on Commit");
-                        stateObj.WriteByte((byte)0); // No xact name
-
-                        stateObj.WriteByte(0);  // No flags
-
-                        Debug.Assert(isoLevel == TdsEnums.TransactionManagerIsolationLevel.Unspecified, "Should not have isolation level other than unspecified on Commit!");
-                        // WriteByte((byte) 0, stateObj); // IsolationLevel
-                        // WriteByte((byte) 0, stateObj); // No begin xact name
-                        break;
-                    case TdsEnums.TransactionManagerRequestType.Rollback:
-
-                        stateObj.WriteByte((byte)(transactionName.Length * 2)); // Write number of bytes (unicode string).
-                        WriteString(transactionName, stateObj);
-
-                        stateObj.WriteByte(0);  // No flags
-
-                        Debug.Assert(isoLevel == TdsEnums.TransactionManagerIsolationLevel.Unspecified, "Should not have isolation level other than unspecified on Commit!");
-                        // WriteByte((byte) 0, stateObj); // IsolationLevel
-                        // WriteByte((byte) 0, stateObj); // No begin xact name
-                        break;
-                    case TdsEnums.TransactionManagerRequestType.Save:
-
-                        stateObj.WriteByte((byte)(transactionName.Length * 2)); // Write number of bytes (unicode string).
-                        WriteString(transactionName, stateObj);
-                        break;
-                    default:
-                        Debug.Fail("Unexpected TransactionManagerRequest");
-                        break;
-                }
-
-                Task writeTask = stateObj.WritePacket(TdsEnums.HARDFLUSH);
-                Debug.Assert(writeTask == null, "Writes should not pend when writing sync");
-                stateObj._pendingData = true;
-                stateObj._messageStatus = 0;
-
-                SqlDataReader dtcReader = null;
-                stateObj.SniContext = SniContext.Snix_Read;
-                if (returnReader)
-                {
-                    dtcReader = new SqlDataReader(null, CommandBehavior.Default);
-                    Debug.Assert(this == stateObj.Parser, "different parser");
-#if DEBUG
-                    // Remove the current owner of stateObj - otherwise we will hit asserts
-                    stateObj.Owner = null;
-#endif
-                    dtcReader.Bind(stateObj);
-
-                    // force consumption of metadata
-                    _SqlMetaDataSet metaData = dtcReader.MetaData;
-                }
-                else
-                {
-                    Run(RunBehavior.UntilDone, null, null, null, stateObj);
-                }
-
-                // If the retained ID is no longer valid (because we are enlisting in null or a new transaction) then it should be cleared
-                if (((request == TdsEnums.TransactionManagerRequestType.Begin) || (request == TdsEnums.TransactionManagerRequestType.Propagate)) && ((transaction == null) || (transaction.TransactionId != _retainedTransactionId)))
-                {
-                    _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
-                }
-
-                return dtcReader;
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-
-                FailureCleanup(stateObj, e);
-
-                throw;
-            }
-            finally
-            {
-                // SQLHotfix 50000518
-                // make sure we don't leave temporary fields set when leaving this function
-                _pendingTransaction = null;
-
-                _asyncWrite = hadAsyncWrites;
-
-                if (!callerHasConnectionLock)
-                {
-                    _connHandler.ThreadHasParserLockForClose = false;
-                    _connHandler._parserLock.Release();
-                }
-            }
-        }
-
-        internal void FailureCleanup(TdsParserStateObject stateObj, Exception e)
-        {
-            int old_outputPacketNumber = stateObj._outputPacketNumber;
-
-
-            if (stateObj.HasOpenResult)
-            { // Need to decrement openResultCount if operation failed.
-                stateObj.DecrementOpenResultCount();
-            }
-
-            // be sure to wipe out our buffer if we started sending stuff
-            stateObj.ResetBuffer();
-            stateObj.ResetPacketCounters();
-
-            if (old_outputPacketNumber != 1 && _state == TdsParserState.OpenLoggedIn)
-            {
-                Debug.Assert(_connHandler._parserLock.ThreadMayHaveLock(), "Should not be calling into FailureCleanup without first taking the parser lock");
-
-                bool originalThreadHasParserLock = _connHandler.ThreadHasParserLockForClose;
-                try
-                {
-                    // Need to set this to true such that if we have an error sending\processing the attention, we won't deadlock ourselves
-                    _connHandler.ThreadHasParserLockForClose = true;
-
-                    // If _outputPacketNumber prior to ResetBuffer was not equal to 1, a packet was already
-                    // sent to the server and so we need to send an attention and process the attention ack.
-                    stateObj.SendAttention();
-                    ProcessAttention(stateObj);
-                }
-                finally
-                {
-                    // Reset the ThreadHasParserLock value in case our caller expects it to be set\not set
-                    _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock;
-                }
-            }
-        }
-
-        internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool sync, bool callerHasConnectionLock = false)
-        {
-            if (TdsParserState.Broken == State || TdsParserState.Closed == State)
-            {
-                return null;
-            }
-
-            if (stateObj.BcpLock)
-            {
-                throw SQL.ConnectionLockedForBcpEvent();
-            }
-
-            // Promote, Commit and Rollback requests for
-            // delegated transactions often happen while there is an open result
-            // set, so we need to handle them by using a different MARS session,
-            // otherwise we'll write on the physical state objects while someone
-            // else is using it.  When we don't have MARS enabled, we need to
-            // lock the physical state object to synchronize it's use at least
-            // until we increment the open results count.  Once it's been
-            // incremented the delegated transaction requests will fail, so they
-            // won't stomp on anything.
-
-            // Only need to take the lock if neither the thread nor the caller claims to already have it
-            bool needToTakeParserLock = (!callerHasConnectionLock) && (!_connHandler.ThreadHasParserLockForClose);
-            Debug.Assert(!_connHandler.ThreadHasParserLockForClose || sync, "Thread shouldn't claim to have the parser lock if we are doing async writes");     // Since we have the possibility of pending with async writes, make sure the thread doesn't claim to already have the lock
-            Debug.Assert(needToTakeParserLock || _connHandler._parserLock.ThreadMayHaveLock(), "Thread or caller claims to have connection lock, but lock is not taken");
-
-            bool releaseConnectionLock = false;
-            if (needToTakeParserLock)
-            {
-                _connHandler._parserLock.Wait(canReleaseFromAnyThread: !sync);
-                releaseConnectionLock = true;
-            }
-
-            // Switch the writing mode
-            // NOTE: We are not turning off async writes when we complete since SqlBulkCopy uses this method and expects _asyncWrite to not change
-            _asyncWrite = !sync;
-
-            try
-            {
-                // Check that the connection is still alive
-                if ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))
-                {
-                    throw ADP.ClosedConnectionError();
-                }
-
-                // This validation step MUST be done after locking the connection to guarantee we don't
-                //  accidentally execute after the transaction has completed on a different thread.
-                _connHandler.CheckEnlistedTransactionBinding();
-
-                stateObj.SetTimeoutSeconds(timeout);
-                stateObj.SniContext = SniContext.Snix_Execute;
-
-                WriteRPCBatchHeaders(stateObj, notificationRequest);
-
-                stateObj._outputMessageType = TdsEnums.MT_SQL;
-
-                WriteString(text, text.Length, 0, stateObj);
-
-                Task executeTask = stateObj.ExecuteFlush();
-                if (executeTask == null)
-                {
-                    stateObj.SniContext = SniContext.Snix_Read;
-                }
-                else
-                {
-                    Debug.Assert(!sync, "Should not have gotten a Task when writing in sync mode");
-
-                    // Need to wait for flush - continuation will unlock the connection
-                    bool taskReleaseConnectionLock = releaseConnectionLock;
-                    releaseConnectionLock = false;
-                    return executeTask.ContinueWith(
-                        (task, state) =>
-                        {
-                            Debug.Assert(!task.IsCanceled, "Task should not be canceled");
-                            var parameters = (Tuple<TdsParser, TdsParserStateObject, SqlInternalConnectionTds>)state;
-                            TdsParser parser = parameters.Item1;
-                            TdsParserStateObject tdsParserStateObject = parameters.Item2;
-                            SqlInternalConnectionTds internalConnectionTds = parameters.Item3;
-                            try
-                            {
-                                if (task.IsFaulted)
-                                {
-                                    parser.FailureCleanup(tdsParserStateObject, task.Exception.InnerException);
-                                    throw task.Exception.InnerException;
-                                }
-                                else
-                                {
-                                    tdsParserStateObject.SniContext = SniContext.Snix_Read;
-                                }
-                            }
-                            finally
-                            {
-                                internalConnectionTds?._parserLock.Release();
-                            }
-                        },
-                        Tuple.Create(this, stateObj, taskReleaseConnectionLock ? _connHandler : null),
-                        TaskScheduler.Default
-                    );
-                }
-
-                // Finished sync
-                return null;
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-
-                FailureCleanup(stateObj, e);
-
-                throw;
-            }
-            finally
-            {
-                if (releaseConnectionLock)
-                {
-                    _connHandler._parserLock.Release();
-                }
-            }
-        }
-
-        internal Task TdsExecuteRPC(_SqlRPC[] rpcArray, int timeout, bool inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool isCommandProc, bool sync = true,
-                  TaskCompletionSource<object> completion = null, int startRpc = 0, int startParam = 0)
-        {
-            bool firstCall = (completion == null);
-            bool releaseConnectionLock = false;
-
-            Debug.Assert(!firstCall || startRpc == 0, "startRpc is not 0 on first call");
-            Debug.Assert(!firstCall || startParam == 0, "startParam is not 0 on first call");
-            Debug.Assert(!firstCall || !_connHandler.ThreadHasParserLockForClose, "Thread should not already have connection lock");
-            Debug.Assert(firstCall || _connHandler._parserLock.ThreadMayHaveLock(), "Connection lock not taken after the first call");
-            try
-            {
-                _SqlRPC rpcext = null;
-                int tempLen;
-
-                // Promote, Commit and Rollback requests for
-                // delegated transactions often happen while there is an open result
-                // set, so we need to handle them by using a different MARS session,
-                // otherwise we'll write on the physical state objects while someone
-                // else is using it.  When we don't have MARS enabled, we need to
-                // lock the physical state object to synchronize its use at least
-                // until we increment the open results count.  Once it's been
-                // incremented the delegated transaction requests will fail, so they
-                // won't stomp on anything.
-
-
-                if (firstCall)
-                {
-                    _connHandler._parserLock.Wait(canReleaseFromAnyThread: !sync);
-                    releaseConnectionLock = true;
-                }
-                try
-                {
-                    // Ensure that connection is alive
-                    if ((TdsParserState.Broken == State) || (TdsParserState.Closed == State))
-                    {
-                        throw ADP.ClosedConnectionError();
-                    }
-
-                    // This validation step MUST be done after locking the connection to guarantee we don't
-                    //  accidentally execute after the transaction has completed on a different thread.
-                    if (firstCall)
-                    {
-                        _asyncWrite = !sync;
-
-                        _connHandler.CheckEnlistedTransactionBinding();
-
-                        stateObj.SetTimeoutSeconds(timeout);
-
-                        stateObj.SniContext = SniContext.Snix_Execute;
-
-                        if (_isYukon)
-                        {
-                            WriteRPCBatchHeaders(stateObj, notificationRequest);
-                        }
-
-                        stateObj._outputMessageType = TdsEnums.MT_RPC;
-                    }
-
-                    for (int ii = startRpc; ii < rpcArray.Length; ii++)
-                    {
-                        rpcext = rpcArray[ii];
-
-                        if (startParam == 0 || ii > startRpc)
-                        {
-                            if (rpcext.ProcID != 0)
-                            {
-                                // Perf optimization for Shiloh and later,
-                                Debug.Assert(rpcext.ProcID < 255, "rpcExec:ProcID can't be larger than 255");
-                                WriteShort(0xffff, stateObj);
-                                WriteShort((short)(rpcext.ProcID), stateObj);
-                            }
-                            else
-                            {
-                                Debug.Assert(!string.IsNullOrEmpty(rpcext.rpcName), "must have an RPC name");
-                                tempLen = rpcext.rpcName.Length;
-                                WriteShort(tempLen, stateObj);
-                                WriteString(rpcext.rpcName, tempLen, 0, stateObj);
-                            }
-
-                            // Options
-                            WriteShort((short)rpcext.options, stateObj);
-                        }
-
-                        // Stream out parameters
-                        //SqlParameter[] parameters = rpcext.parameters;
-                        int parametersLength = rpcext.userParamCount + rpcext.systemParamCount;
-
-                        for (int i = (ii == startRpc) ? startParam : 0; i < parametersLength; i++)
-                        {
-                            byte options = 0;
-                            SqlParameter param = rpcext.GetParameterByIndex(i, out options);
-
-                            // Since we are reusing the parameters array, we cannot rely on length to indicate no of parameters.
-                            if (param == null)
-                            {
-                                break;      // End of parameters for this execute
-                            }
-
-                            // Validate parameters are not variable length without size and with null value.
-                            param.Validate(i, isCommandProc);
-
-                            // type (parameter record stores the MetaType class which is a helper that encapsulates all the type information we need here)
-                            MetaType mt = param.InternalMetaType;
-
-                            if (mt.IsNewKatmaiType)
-                            {
-                                WriteSmiParameter(param, i, 0 != (options & TdsEnums.RPC_PARAM_DEFAULT), stateObj);
-                                continue;
-                            }
-
-                            if ((!_isYukon && !mt.Is80Supported) ||
-                                (!_isKatmai && !mt.Is90Supported))
-                            {
-                                throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
-                            }
-
-                            Task writeParamTask = TDSExecuteRPCAddParameter(stateObj, param, mt, options);
-
-                            if (!sync)
-                            {
-                                if (writeParamTask == null)
-                                {
-                                    writeParamTask = stateObj.WaitForAccumulatedWrites();
-                                }
-
-                                if (writeParamTask != null)
-                                {
-                                    Task task = null;
-                                    if (completion == null)
-                                    {
-                                        completion = new TaskCompletionSource<object>();
-                                        task = completion.Task;
-                                    }
-
-                                    TDSExecuteRPCParameterSetupWriteCompletion(
-                                        rpcArray,
-                                        timeout,
-                                        inSchema,
-                                        notificationRequest,
-                                        stateObj,
-                                        isCommandProc,
-                                        sync,
-                                        completion,
-                                        ii,
-                                        i + 1,
-                                        writeParamTask
-                                   );
-
-                                    // Take care of releasing the locks
-                                    if (releaseConnectionLock)
-                                    {
-                                        task.ContinueWith(_ =>
-                                        {
-                                            _connHandler._parserLock.Release();
-                                        }, TaskScheduler.Default);
-                                        releaseConnectionLock = false;
-                                    }
-
-                                    return task;
-                                }
-                            }
-#if DEBUG
-                            else
-                            {
-                                Debug.Assert(writeParamTask == null, "Should not have a task when executing sync");
-                            }
-#endif
-                        } // parameter for loop
-
-                        // If this is not the last RPC we are sending, add the batch flag
-                        if (ii < (rpcArray.Length - 1))
-                        {
-                            if (_isYukon)
-                            {
-                                stateObj.WriteByte(TdsEnums.YUKON_RPCBATCHFLAG);
-                            }
-                            else
-                            {
-                                stateObj.WriteByte(TdsEnums.SHILOH_RPCBATCHFLAG);
-                            }
-                        }
-                    } // rpc for loop
-
-                    Task execFlushTask = stateObj.ExecuteFlush();
-                    Debug.Assert(!sync || execFlushTask == null, "Should not get a task when executing sync");
-                    if (execFlushTask != null)
-                    {
-                        Task task = null;
-
-                        if (completion == null)
-                        {
-                            completion = new TaskCompletionSource<object>();
-                            task = completion.Task;
-                        }
-
-                        TDSExecuteRPCParameterSetupFlushCompletion(stateObj, completion, execFlushTask, releaseConnectionLock);
-
-                        // TDSExecuteRPCParameterSetupFlushCompletion calling ExecuteFlushTaskCallback will take care of the locks for us
-                        releaseConnectionLock = false;
-
-                        return task;
-                    }
-                }
-                catch (Exception e)
-                {
-                    if (!ADP.IsCatchableExceptionType(e))
-                    {
-                        throw;
-                    }
-
-                    FailureCleanup(stateObj, e);
-
-                    throw;
-                }
-                FinalizeExecuteRPC(stateObj);
-                if (completion != null)
-                {
-                    completion.SetResult(null);
-                }
-                return null;
-            }
-            catch (Exception e)
-            {
-                FinalizeExecuteRPC(stateObj);
-                if (completion != null)
-                {
-                    completion.SetException(e);
-                    return null;
-                }
-                else
-                {
-                    throw;
-                }
-            }
-            finally
-            {
-                Debug.Assert(firstCall || !releaseConnectionLock, "Shouldn't be releasing locks synchronously after the first call");
-                if (releaseConnectionLock)
-                {
-                    _connHandler._parserLock.Release();
-                }
-            }
-        }
-
-        private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParameter param, MetaType mt, byte options)
-        {
-            int tempLen;
-            object value = null;
-            bool isNull = true;
-            bool isSqlVal = false;
-            bool isDataFeed = false;
-            // if we have an output param, set the value to null so we do not send it across to the server
-            if (param.Direction == ParameterDirection.Output)
-            {
-                isSqlVal = param.ParameterIsSqlType;  // We have to forward the TYPE info, we need to know what type we are returning.  Once we null the parameter we will no longer be able to distinguish what type were seeing.
-                param.Value = null;
-                param.ParameterIsSqlType = isSqlVal;
-            }
-            else
-            {
-                value = param.GetCoercedValue();
-                isNull = param.IsNull;
-                if (!isNull)
-                {
-                    isSqlVal = param.CoercedValueIsSqlType;
-                    isDataFeed = param.CoercedValueIsDataFeed;
-                }
-            }
-
-            WriteParameterName(param.ParameterNameFixed, stateObj);
-
-            // Write parameter status
-            stateObj.WriteByte(options);
-
-            // MaxLen field is only written out for non-fixed length data types
-            // use the greater of the two sizes for maxLen
-            int actualSize;
-            int size = mt.IsSizeInCharacters ? param.GetParameterSize() * 2 : param.GetParameterSize();
-
-            // for UDTs, we calculate the length later when we get the bytes. This is a really expensive operation
-            if (mt.TDSType != TdsEnums.SQLUDT)
-                // getting the actualSize is expensive, cache here and use below
-                actualSize = param.GetActualSize();
-            else
-                actualSize = 0; //get this later
-
-            byte precision = 0;
-            byte scale = 0;
-
-            // scale and precision are only relevant for numeric and decimal types
-            // adjust the actual value scale and precision to match the user specified
-            if (mt.SqlDbType == SqlDbType.Decimal)
-            {
-                precision = param.GetActualPrecision();
-                scale = param.GetActualScale();
-
-                if (precision > TdsEnums.MAX_NUMERIC_PRECISION)
-                {
-                    throw SQL.PrecisionValueOutOfRange(precision);
-                }
-
-                // Make sure the value matches the scale the user enters
-                if (!isNull)
-                {
-                    if (isSqlVal)
-                    {
-                        value = AdjustSqlDecimalScale((SqlDecimal)value, scale);
-
-                        // If Precision is specified, verify value precision vs param precision
-                        if (precision != 0)
-                        {
-                            if (precision < ((SqlDecimal)value).Precision)
-                            {
-                                throw ADP.ParameterValueOutOfRange((SqlDecimal)value);
-                            }
-                        }
-                    }
-                    else
-                    {
-                        value = AdjustDecimalScale((decimal)value, scale);
-
-                        SqlDecimal sqlValue = new SqlDecimal((decimal)value);
-
-                        // If Precision is specified, verify value precision vs param precision
-                        if (precision != 0)
-                        {
-                            if (precision < sqlValue.Precision)
-                            {
-                                throw ADP.ParameterValueOutOfRange((decimal)value);
-                            }
-                        }
-                    }
-                }
-            }
-
-            // fixup the types by using the NullableType property of the MetaType class
-            //
-            // following rules should be followed based on feedback from the M-SQL team
-            // 1) always use the BIG* types (ex: instead of SQLCHAR use SQLBIGCHAR)
-            // 2) always use nullable types (ex: instead of SQLINT use SQLINTN)
-            // 3) DECIMALN should always be sent as NUMERICN
-            //
-            stateObj.WriteByte(mt.NullableType);
-
-            // handle variants here: the SQLVariant writing routine will write the maxlen and actual len columns
-            if (mt.TDSType == TdsEnums.SQLVARIANT)
-            {
-                // devnote: Do we ever hit this codepath? Yes, when a null value is being written out via a sql variant
-                // param.GetActualSize is not used
-                WriteSqlVariantValue(isSqlVal ? MetaType.GetComValueFromSqlVariant(value) : value, param.GetActualSize(), param.Offset, stateObj);
-                return null;
-            }
-
-            int codePageByteSize = 0;
-            int maxsize = 0;
-
-            if (mt.IsAnsiType)
-            {
-                // Avoid the following code block if ANSI but unfilled LazyMat blob
-                if ((!isNull) && (!isDataFeed))
-                {
-                    string s;
-
-                    if (isSqlVal)
-                    {
-                        if (value is SqlString)
-                        {
-                            s = ((SqlString)value).Value;
-                        }
-                        else
-                        {
-                            Debug.Assert(value is SqlChars, "Unknown value for Ansi datatype");
-                            s = new string(((SqlChars)value).Value);
-                        }
-                    }
-                    else
-                    {
-                        s = (string)value;
-                    }
-
-                    codePageByteSize = GetEncodingCharLength(s, actualSize, param.Offset, _defaultEncoding);
-                }
-
-                if (mt.IsPlp)
-                {
-                    WriteShort(TdsEnums.SQL_USHORTVARMAXLEN, stateObj);
-                }
-                else
-                {
-                    maxsize = (size > codePageByteSize) ? size : codePageByteSize;
-                    if (maxsize == 0)
-                    {
-                        // Yukon doesn't like 0 as MaxSize. Change it to 2 for unicode types
-                        if (mt.IsNCharType)
-                            maxsize = 2;
-                        else
-                            maxsize = 1;
-                    }
-
-                    WriteParameterVarLen(mt, maxsize, false /*IsNull*/, stateObj);
-                }
-            }
-            else
-            {
-                // If type timestamp - treat as fixed type and always send over timestamp length, which is 8.
-                // For fixed types, we either send null or fixed length for type length.  We want to match that
-                // behavior for timestamps.  However, in the case of null, we still must send 8 because if we
-                // send null we will not receive a output val.  You can send null for fixed types and still
-                // receive a output value, but not for variable types.  So, always send 8 for timestamp because
-                // while the user sees it as a fixed type, we are actually representing it as a bigbinary which
-                // is variable.
-                if (mt.SqlDbType == SqlDbType.Timestamp)
-                {
-                    WriteParameterVarLen(mt, TdsEnums.TEXT_TIME_STAMP_LEN, false, stateObj);
-                }
-                else if (mt.SqlDbType == SqlDbType.Udt)
-                {
-                    byte[] udtVal = null;
-                    Format format = Format.Native;
-
-                    Debug.Assert(_isYukon, "Invalid DataType UDT for non-Yukon or later server!");
-
-                    if (!isNull)
-                    {
-                        if (value is byte[] rawBytes)
-                        {
-                            udtVal = rawBytes;
-                        }
-                        else if (value is SqlBytes sqlBytes)
-                        {
-                            switch (sqlBytes.Storage)
-                            {
-                                case StorageState.Buffer:
-                                    // use the buffer directly, the only way to create it is with the correctly sized byte array
-                                    udtVal = sqlBytes.Buffer;
-                                    break;
-                                case StorageState.Stream:
-                                case StorageState.UnmanagedBuffer:
-                                    // allocate a new byte array to store the data
-                                    udtVal = sqlBytes.Value;
-                                    break;
-                            }
-                        }
-                        else
-                        {
-                            udtVal = _connHandler.Connection.GetBytes(value, out format, out maxsize);
-                        }
-
-                        Debug.Assert(null != udtVal, "GetBytes returned null instance. Make sure that it always returns non-null value");
-                        size = udtVal.Length;
-
-                        //it may be legitimate, but we dont support it yet
-                        if (size < 0 || (size >= ushort.MaxValue && maxsize != -1))
-                            throw new IndexOutOfRangeException();
-                    }
-
-                    if (string.IsNullOrEmpty(param.UdtTypeName))
-                        throw SQL.MustSetUdtTypeNameForUdtParams();
-
-                    // Split the input name. TypeName is returned as single 3 part name during DeriveParameters.
-                    // NOTE: ParseUdtTypeName throws if format is incorrect
-                    string[] names = SqlParameter.ParseTypeName(param.UdtTypeName, true /* is UdtTypeName */);
-                    if (!string.IsNullOrEmpty(names[0]) && TdsEnums.MAX_SERVERNAME < names[0].Length)
-                    {
-                        throw ADP.ArgumentOutOfRange(nameof(names));
-                    }
-                    if (!string.IsNullOrEmpty(names[1]) && TdsEnums.MAX_SERVERNAME < names[names.Length - 2].Length)
-                    {
-                        throw ADP.ArgumentOutOfRange(nameof(names));
-                    }
-                    if (TdsEnums.MAX_SERVERNAME < names[2].Length)
-                    {
-                        throw ADP.ArgumentOutOfRange(nameof(names));
-                    }
-
-                    WriteUDTMetaData(value, names[0], names[1], names[2], stateObj);
-
-                    if (!isNull)
-                    {
-                        WriteUnsignedLong((ulong)udtVal.Length, stateObj); // PLP length
-                        if (udtVal.Length > 0)
-                        { // Only write chunk length if its value is greater than 0
-                            WriteInt(udtVal.Length, stateObj); // Chunk length
-                            stateObj.WriteByteArray(udtVal, udtVal.Length, 0); // Value
-                        }
-                        WriteInt(0, stateObj); // Terminator
-                    }
-                    else
-                    {
-                        WriteUnsignedLong(TdsEnums.SQL_PLP_NULL, stateObj); // PLP Null.
-                    }
-                    return null; //continue; // End of UDT - continue to next parameter.
-                }
-                else if (mt.IsPlp)
-                {
-                    if (mt.SqlDbType != SqlDbType.Xml)
-                        WriteShort(TdsEnums.SQL_USHORTVARMAXLEN, stateObj);
-                }
-                else if ((!mt.IsVarTime) && (mt.SqlDbType != SqlDbType.Date))
-                {   // Time, Date, DateTime2, DateTimeoffset do not have the size written out
-                    maxsize = (size > actualSize) ? size : actualSize;
-                    if (maxsize == 0 && _isYukon)
-                    {
-                        // Yukon doesn't like 0 as MaxSize. Change it to 2 for unicode types (SQL9 - 682322)
-                        if (mt.IsNCharType)
-                            maxsize = 2;
-                        else
-                            maxsize = 1;
-                    }
-
-                    WriteParameterVarLen(mt, maxsize, false /*IsNull*/, stateObj);
-                }
-            }
-
-            // scale and precision are only relevant for numeric and decimal types
-            if (mt.SqlDbType == SqlDbType.Decimal)
-            {
-                if (0 == precision)
-                {
-                    stateObj.WriteByte(TdsEnums.DEFAULT_NUMERIC_PRECISION);
-                }
-                else
-                {
-                    stateObj.WriteByte(precision);
-                }
-
-                stateObj.WriteByte(scale);
-            }
-            else if (mt.IsVarTime)
-            {
-                stateObj.WriteByte(param.GetActualScale());
-            }
-
-            // write out collation or xml metadata
-
-            if (_isYukon && (mt.SqlDbType == SqlDbType.Xml))
-            {
-                if (((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != string.Empty)) ||
-                    ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != string.Empty)) ||
-                    ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != string.Empty)))
-                {
-                    stateObj.WriteByte(1);  //Schema present flag
-
-                    if ((param.XmlSchemaCollectionDatabase != null) && (param.XmlSchemaCollectionDatabase != string.Empty))
-                    {
-                        tempLen = (param.XmlSchemaCollectionDatabase).Length;
-                        stateObj.WriteByte((byte)(tempLen));
-                        WriteString(param.XmlSchemaCollectionDatabase, tempLen, 0, stateObj);
-                    }
-                    else
-                    {
-                        stateObj.WriteByte(0);       // No dbname
-                    }
-
-                    if ((param.XmlSchemaCollectionOwningSchema != null) && (param.XmlSchemaCollectionOwningSchema != string.Empty))
-                    {
-                        tempLen = (param.XmlSchemaCollectionOwningSchema).Length;
-                        stateObj.WriteByte((byte)(tempLen));
-                        WriteString(param.XmlSchemaCollectionOwningSchema, tempLen, 0, stateObj);
-                    }
-                    else
-                    {
-                        stateObj.WriteByte(0);      // no xml schema name
-                    }
-
-                    if ((param.XmlSchemaCollectionName != null) && (param.XmlSchemaCollectionName != string.Empty))
-                    {
-                        tempLen = (param.XmlSchemaCollectionName).Length;
-                        WriteShort((short)(tempLen), stateObj);
-                        WriteString(param.XmlSchemaCollectionName, tempLen, 0, stateObj);
-                    }
-                    else
-                    {
-                        WriteShort(0, stateObj);       // No xml schema collection name
-                    }
-                }
-                else
-                {
-                    stateObj.WriteByte(0);       // No schema
-                }
-            }
-            else if (mt.IsCharType)
-            {
-                // if it is not supplied, simply write out our default collation, otherwise, write out the one attached to the parameter
-                SqlCollation outCollation = (param.Collation != null) ? param.Collation : _defaultCollation;
-                Debug.Assert(_defaultCollation != null, "_defaultCollation is null!");
-
-                WriteUnsignedInt(outCollation.info, stateObj);
-                stateObj.WriteByte(outCollation.sortId);
-            }
-
-            if (0 == codePageByteSize)
-            {
-                WriteParameterVarLen(mt, actualSize, isNull, stateObj, isDataFeed);
-            }
-            else
-            {
-                WriteParameterVarLen(mt, codePageByteSize, isNull, stateObj, isDataFeed);
-            }
-
-            Task writeParamTask = null;
-            // write the value now
-            if (!isNull)
-            {
-                if (isSqlVal)
-                {
-                    writeParamTask = WriteSqlValue(value, mt, actualSize, codePageByteSize, param.Offset, stateObj);
-                }
-                else
-                {
-                    // for codePageEncoded types, WriteValue simply expects the number of characters
-                    // For plp types, we also need the encoded byte size
-                    writeParamTask = WriteValue(value, mt, param.GetActualScale(), actualSize, codePageByteSize, param.Offset, stateObj, param.Size, isDataFeed);
-                }
-            }
-            return writeParamTask;
-        }
-
-        // This is in its own method to avoid always allocating the lambda in TDSExecuteRPCParameter
-        private void TDSExecuteRPCParameterSetupWriteCompletion(_SqlRPC[] rpcArray, int timeout, bool inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool isCommandProc, bool sync, TaskCompletionSource<object> completion, int startRpc, int startParam, Task writeParamTask)
-        {
-            AsyncHelper.ContinueTask(
-                writeParamTask,
-                completion,
-                () => TdsExecuteRPC(
-                        rpcArray,
-                        timeout,
-                        inSchema,
-                        notificationRequest,
-                        stateObj,
-                        isCommandProc,
-                        sync,
-                        completion,
-                        startRpc,
-                        startParam
-                      ),
-                onFailure: exc => TdsExecuteRPC_OnFailure(exc, stateObj)
-            );
-        }
-
-        // This is in its own method to avoid always allocating the lambda in  TDSExecuteRPCParameter
-        private void TDSExecuteRPCParameterSetupFlushCompletion(TdsParserStateObject stateObj, TaskCompletionSource<object> completion, Task execFlushTask, bool taskReleaseConnectionLock)
-        {
-            execFlushTask.ContinueWith(tsk => ExecuteFlushTaskCallback(tsk, stateObj, completion, taskReleaseConnectionLock), TaskScheduler.Default);
-        }
-
-        private void FinalizeExecuteRPC(TdsParserStateObject stateObj)
-        {
-            stateObj.SniContext = SniContext.Snix_Read;
-            _asyncWrite = false;
-        }
-
-        private void TdsExecuteRPC_OnFailure(Exception exc, TdsParserStateObject stateObj)
-        {
-            FailureCleanup(stateObj, exc);
-        }
-
-        private void ExecuteFlushTaskCallback(Task tsk, TdsParserStateObject stateObj, TaskCompletionSource<object> completion, bool releaseConnectionLock)
-        {
-            try
-            {
-                FinalizeExecuteRPC(stateObj);
-                if (tsk.Exception != null)
-                {
-                    Exception exc = tsk.Exception.InnerException;
-                    try
-                    {
-                        FailureCleanup(stateObj, tsk.Exception);
-                    }
-                    catch (Exception e)
-                    {
-                        exc = e;
-                    }
-                    completion.SetException(exc);
-                }
-                else
-                {
-                    completion.SetResult(null);
-                }
-            }
-            finally
-            {
-                if (releaseConnectionLock)
-                {
-                    _connHandler._parserLock.Release();
-                }
-            }
-        }
-
-
-        private void WriteParameterName(string parameterName, TdsParserStateObject stateObj)
-        {
-            // paramLen
-            // paramName
-            if (!string.IsNullOrEmpty(parameterName))
-            {
-                Debug.Assert(parameterName.Length <= 0xff, "parameter name can only be 255 bytes, shouldn't get to TdsParser!");
-                int tempLen = parameterName.Length & 0xff;
-                stateObj.WriteByte((byte)tempLen);
-                WriteString(parameterName, tempLen, 0, stateObj);
-            }
-            else
-            {
-                stateObj.WriteByte(0);
-            }
-        }
-
-        private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefault, TdsParserStateObject stateObj)
-        {
-            //
-            // Determine Metadata
-            //
-            ParameterPeekAheadValue peekAhead;
-            MSS.SmiParameterMetaData metaData = param.MetaDataForSmi(out peekAhead);
-
-            if (!_isKatmai)
-            {
-                MetaType mt = MetaType.GetMetaTypeFromSqlDbType(metaData.SqlDbType, metaData.IsMultiValued);
-                throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
-            }
-
-            //
-            //  Determine value to send
-            //
-            object value;
-            MSS.ExtendedClrTypeCode typeCode;
-
-            // if we have an output or default param, set the value to null so we do not send it across to the server
-            if (sendDefault)
-            {
-                // Value for TVP default is empty list, not NULL
-                if (SqlDbType.Structured == metaData.SqlDbType && metaData.IsMultiValued)
-                {
-                    value = Array.Empty<MSS.SqlDataRecord>();
-                    typeCode = MSS.ExtendedClrTypeCode.IEnumerableOfSqlDataRecord;
-                }
-                else
-                {
-                    // Need to send null value for default
-                    value = null;
-                    typeCode = MSS.ExtendedClrTypeCode.DBNull;
-                }
-            }
-            else if (param.Direction == ParameterDirection.Output)
-            {
-                bool isCLRType = param.ParameterIsSqlType;  // We have to forward the TYPE info, we need to know what type we are returning.  Once we null the parameter we will no longer be able to distinguish what type were seeing.
-                param.Value = null;
-                value = null;
-                typeCode = MSS.ExtendedClrTypeCode.DBNull;
-                param.ParameterIsSqlType = isCLRType;
-            }
-            else
-            {
-                value = param.GetCoercedValue();
-                typeCode = MSS.MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType(metaData.SqlDbType, metaData.IsMultiValued, value, null);
-            }
-
-
-            //
-            // Write parameter metadata
-            //
-            WriteSmiParameterMetaData(metaData, sendDefault, stateObj);
-
-            //
-            // Now write the value
-            //
-            TdsParameterSetter paramSetter = new TdsParameterSetter(stateObj, metaData);
-            MSS.ValueUtilsSmi.SetCompatibleValueV200(
-                                        new MSS.SmiEventSink_Default(),  // TDS Errors/events dealt with at lower level for now, just need an object for processing
-                                        paramSetter,
-                                        0,          // ordinal.  TdsParameterSetter only handles one parameter at a time
-                                        metaData,
-                                        value,
-                                        typeCode,
-                                        param.Offset,
-                                        0 < param.Size ? param.Size : -1,
-                                        peekAhead);
-        }
-
-        // Writes metadata portion of parameter stream from an SmiParameterMetaData object.
-        private void WriteSmiParameterMetaData(MSS.SmiParameterMetaData metaData, bool sendDefault, TdsParserStateObject stateObj)
-        {
-            // Determine status
-            byte status = 0;
-            if (ParameterDirection.Output == metaData.Direction || ParameterDirection.InputOutput == metaData.Direction)
-            {
-                status |= TdsEnums.RPC_PARAM_BYREF;
-            }
-
-            if (sendDefault)
-            {
-                status |= TdsEnums.RPC_PARAM_DEFAULT;
-            }
-
-            // Write everything out
-            WriteParameterName(metaData.Name, stateObj);
-            stateObj.WriteByte(status);
-            WriteSmiTypeInfo(metaData, stateObj);
-        }
-
-        // Write a TypeInfo stream
-        // Devnote: we remap the legacy types (text, ntext, and image) to SQLBIGVARCHAR,  SQLNVARCHAR, and SQLBIGVARBINARY
-        private void WriteSmiTypeInfo(MSS.SmiExtendedMetaData metaData, TdsParserStateObject stateObj)
-        {
-            switch (metaData.SqlDbType)
-            {
-                case SqlDbType.BigInt:
-                    stateObj.WriteByte(TdsEnums.SQLINTN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.Binary:
-                    stateObj.WriteByte(TdsEnums.SQLBIGBINARY);
-                    WriteUnsignedShort(checked((ushort)metaData.MaxLength), stateObj);
-                    break;
-                case SqlDbType.Bit:
-                    stateObj.WriteByte(TdsEnums.SQLBITN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.Char:
-                    stateObj.WriteByte(TdsEnums.SQLBIGCHAR);
-                    WriteUnsignedShort(checked((ushort)(metaData.MaxLength)), stateObj);
-                    WriteUnsignedInt(_defaultCollation.info, stateObj);
-                    stateObj.WriteByte(_defaultCollation.sortId);
-                    break;
-                case SqlDbType.DateTime:
-                    stateObj.WriteByte(TdsEnums.SQLDATETIMN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.Decimal:
-                    stateObj.WriteByte(TdsEnums.SQLNUMERICN);
-                    stateObj.WriteByte(checked((byte)MetaType.MetaDecimal.FixedLength));   // SmiMetaData's length and actual wire format's length are different
-                    stateObj.WriteByte(0 == metaData.Precision ? (byte)1 : metaData.Precision);
-                    stateObj.WriteByte(metaData.Scale);
-                    break;
-                case SqlDbType.Float:
-                    stateObj.WriteByte(TdsEnums.SQLFLTN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.Image:
-                    stateObj.WriteByte(TdsEnums.SQLBIGVARBINARY);
-                    WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
-                    break;
-                case SqlDbType.Int:
-                    stateObj.WriteByte(TdsEnums.SQLINTN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.Money:
-                    stateObj.WriteByte(TdsEnums.SQLMONEYN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.NChar:
-                    stateObj.WriteByte(TdsEnums.SQLNCHAR);
-                    WriteUnsignedShort(checked((ushort)(metaData.MaxLength * 2)), stateObj);
-                    WriteUnsignedInt(_defaultCollation.info, stateObj);
-                    stateObj.WriteByte(_defaultCollation.sortId);
-                    break;
-                case SqlDbType.NText:
-                    stateObj.WriteByte(TdsEnums.SQLNVARCHAR);
-                    WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
-                    WriteUnsignedInt(_defaultCollation.info, stateObj);
-                    stateObj.WriteByte(_defaultCollation.sortId);
-                    break;
-                case SqlDbType.NVarChar:
-                    stateObj.WriteByte(TdsEnums.SQLNVARCHAR);
-                    if (MSS.SmiMetaData.UnlimitedMaxLengthIndicator == metaData.MaxLength)
-                    {
-                        WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
-                    }
-                    else
-                    {
-                        WriteUnsignedShort(checked((ushort)(metaData.MaxLength * 2)), stateObj);
-                    }
-                    WriteUnsignedInt(_defaultCollation.info, stateObj);
-                    stateObj.WriteByte(_defaultCollation.sortId);
-                    break;
-                case SqlDbType.Real:
-                    stateObj.WriteByte(TdsEnums.SQLFLTN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.UniqueIdentifier:
-                    stateObj.WriteByte(TdsEnums.SQLUNIQUEID);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.SmallDateTime:
-                    stateObj.WriteByte(TdsEnums.SQLDATETIMN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.SmallInt:
-                    stateObj.WriteByte(TdsEnums.SQLINTN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.SmallMoney:
-                    stateObj.WriteByte(TdsEnums.SQLMONEYN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.Text:
-                    stateObj.WriteByte(TdsEnums.SQLBIGVARCHAR);
-                    WriteUnsignedShort(unchecked((ushort)MSS.SmiMetaData.UnlimitedMaxLengthIndicator), stateObj);
-                    WriteUnsignedInt(_defaultCollation.info, stateObj);
-                    stateObj.WriteByte(_defaultCollation.sortId);
-                    break;
-                case SqlDbType.Timestamp:
-                    stateObj.WriteByte(TdsEnums.SQLBIGBINARY);
-                    WriteShort(checked((int)metaData.MaxLength), stateObj);
-                    break;
-                case SqlDbType.TinyInt:
-                    stateObj.WriteByte(TdsEnums.SQLINTN);
-                    stateObj.WriteByte(checked((byte)metaData.MaxLength));
-                    break;
-                case SqlDbType.VarBinary:
-                    stateObj.WriteByte(TdsEnums.SQLBIGVARBINARY);
-                    WriteUnsignedShort(unchecked((ushort)metaData.MaxLength), stateObj);
-                    break;
-                case SqlDbType.VarChar:
-                    stateObj.WriteByte(TdsEnums.SQLBIGVARCHAR);
-                    WriteUnsignedShort(unchecked((ushort)metaData.MaxLength), stateObj);
-                    WriteUnsignedInt(_defaultCollation.info, stateObj);
-                    stateObj.WriteByte(_defaultCollation.sortId);
-                    break;
-                case SqlDbType.Variant:
-                    stateObj.WriteByte(TdsEnums.SQLVARIANT);
-                    WriteInt(checked((int)metaData.MaxLength), stateObj);
-                    break;
-                case SqlDbType.Xml:
-                    stateObj.WriteByte(TdsEnums.SQLXMLTYPE);
-                    // Is there a schema
-                    if (string.IsNullOrEmpty(metaData.TypeSpecificNamePart1) && string.IsNullOrEmpty(metaData.TypeSpecificNamePart2) &&
-                            string.IsNullOrEmpty(metaData.TypeSpecificNamePart3))
-                    {
-                        stateObj.WriteByte(0);  // schema not present
-                    }
-                    else
-                    {
-                        stateObj.WriteByte(1); // schema present
-                        WriteIdentifier(metaData.TypeSpecificNamePart1, stateObj);
-                        WriteIdentifier(metaData.TypeSpecificNamePart2, stateObj);
-                        WriteIdentifierWithShortLength(metaData.TypeSpecificNamePart3, stateObj);
-                    }
-                    break;
-                case SqlDbType.Udt:
-                    stateObj.WriteByte(TdsEnums.SQLUDT);
-                    WriteIdentifier(metaData.TypeSpecificNamePart1, stateObj);
-                    WriteIdentifier(metaData.TypeSpecificNamePart2, stateObj);
-                    WriteIdentifier(metaData.TypeSpecificNamePart3, stateObj);
-                    break;
-                case SqlDbType.Structured:
-                    if (metaData.IsMultiValued)
-                    {
-                        WriteTvpTypeInfo(metaData, stateObj);
-                    }
-                    else
-                    {
-                        Debug.Fail("SUDTs not yet supported.");
-                    }
-                    break;
-                case SqlDbType.Date:
-                    stateObj.WriteByte(TdsEnums.SQLDATE);
-                    break;
-                case SqlDbType.Time:
-                    stateObj.WriteByte(TdsEnums.SQLTIME);
-                    stateObj.WriteByte(metaData.Scale);
-                    break;
-                case SqlDbType.DateTime2:
-                    stateObj.WriteByte(TdsEnums.SQLDATETIME2);
-                    stateObj.WriteByte(metaData.Scale);
-                    break;
-                case SqlDbType.DateTimeOffset:
-                    stateObj.WriteByte(TdsEnums.SQLDATETIMEOFFSET);
-                    stateObj.WriteByte(metaData.Scale);
-                    break;
-                default:
-                    Debug.Fail("Unknown SqlDbType should have been caught earlier!");
-                    break;
-            }
-        }
-
-        private void WriteTvpTypeInfo(MSS.SmiExtendedMetaData metaData, TdsParserStateObject stateObj)
-        {
-            Debug.Assert(SqlDbType.Structured == metaData.SqlDbType && metaData.IsMultiValued,
-                        "Invalid metadata for TVPs. Type=" + metaData.SqlDbType);
-            // Type token
-            stateObj.WriteByte((byte)TdsEnums.SQLTABLE);
-
-            // 3-part name (DB, Schema, TypeName)
-            WriteIdentifier(metaData.TypeSpecificNamePart1, stateObj);
-            WriteIdentifier(metaData.TypeSpecificNamePart2, stateObj);
-            WriteIdentifier(metaData.TypeSpecificNamePart3, stateObj);
-
-            // TVP_COLMETADATA
-            if (0 == metaData.FieldMetaData.Count)
-            {
-                WriteUnsignedShort((ushort)TdsEnums.TVP_NOMETADATA_TOKEN, stateObj);
-            }
-            else
-            {
-                // COUNT of columns
-                WriteUnsignedShort(checked((ushort)metaData.FieldMetaData.Count), stateObj);
-
-                // TvpColumnMetaData for each column (look for defaults in this loop
-                MSS.SmiDefaultFieldsProperty defaults = (MSS.SmiDefaultFieldsProperty)metaData.ExtendedProperties[MSS.SmiPropertySelector.DefaultFields];
-                for (int i = 0; i < metaData.FieldMetaData.Count; i++)
-                {
-                    WriteTvpColumnMetaData(metaData.FieldMetaData[i], defaults[i], stateObj);
-                }
-
-                // optional OrderUnique metadata
-                WriteTvpOrderUnique(metaData, stateObj);
-            }
-
-            // END of optional metadata
-            stateObj.WriteByte(TdsEnums.TVP_END_TOKEN);
-        }
-
-        // Write a single TvpColumnMetaData stream to the server
-        private void WriteTvpColumnMetaData(MSS.SmiExtendedMetaData md, bool isDefault, TdsParserStateObject stateObj)
-        {
-            // User Type
-            if (SqlDbType.Timestamp == md.SqlDbType)
-            {
-                WriteUnsignedInt(TdsEnums.SQLTIMESTAMP, stateObj);
-            }
-            else
-            {
-                WriteUnsignedInt(0, stateObj);
-            }
-
-            // Flags
-            ushort status = TdsEnums.Nullable;
-            if (isDefault)
-            {
-                status |= TdsEnums.TVP_DEFAULT_COLUMN;
-            }
-            WriteUnsignedShort(status, stateObj);
-
-            // Type info
-            WriteSmiTypeInfo(md, stateObj);
-
-            // Column name
-            // per spec, "ColName is never sent to server or client for TVP, it is required within a TVP to be zero length."
-            WriteIdentifier(null, stateObj);
-        }
-
-        // temporary-results structure used only by WriteTvpOrderUnique
-        //  use class to avoid List<T>'s per-struct-instantiated memory costs.
-        private class TdsOrderUnique
-        {
-            internal short ColumnOrdinal;
-            internal byte Flags;
-
-            internal TdsOrderUnique(short ordinal, byte flags)
-            {
-                ColumnOrdinal = ordinal;
-                Flags = flags;
-            }
-        }
-
-        private void WriteTvpOrderUnique(MSS.SmiExtendedMetaData metaData, TdsParserStateObject stateObj)
-        {
-            // TVP_ORDER_UNIQUE token (uniqueness and sort order)
-
-            // Merge order and unique keys into a single token stream
-
-            MSS.SmiOrderProperty orderProperty = (MSS.SmiOrderProperty)metaData.ExtendedProperties[MSS.SmiPropertySelector.SortOrder];
-            MSS.SmiUniqueKeyProperty uniqueKeyProperty = (MSS.SmiUniqueKeyProperty)metaData.ExtendedProperties[MSS.SmiPropertySelector.UniqueKey];
-
-            // Build list from
-            List<TdsOrderUnique> columnList = new List<TdsOrderUnique>(metaData.FieldMetaData.Count);
-            for (int i = 0; i < metaData.FieldMetaData.Count; i++)
-            {
-                // Add appropriate SortOrder flag
-                byte flags = 0;
-                MSS.SmiOrderProperty.SmiColumnOrder columnOrder = orderProperty[i];
-                if (SortOrder.Ascending == columnOrder.Order)
-                {
-                    flags = TdsEnums.TVP_ORDERASC_FLAG;
-                }
-                else if (SortOrder.Descending == columnOrder.Order)
-                {
-                    flags = TdsEnums.TVP_ORDERDESC_FLAG;
-                }
-
-                // Add unique key flag if appropriate
-                if (uniqueKeyProperty[i])
-                {
-                    flags |= TdsEnums.TVP_UNIQUE_FLAG;
-                }
-
-                // Remember this column if any flags were set
-                if (0 != flags)
-                {
-                    columnList.Add(new TdsOrderUnique(checked((short)(i + 1)), flags));
-                }
-            }
-
-            // Write flagged columns to wire...
-            if (0 < columnList.Count)
-            {
-                stateObj.WriteByte(TdsEnums.TVP_ORDER_UNIQUE_TOKEN);
-                WriteShort(columnList.Count, stateObj);
-                foreach (TdsOrderUnique column in columnList)
-                {
-                    WriteShort(column.ColumnOrdinal, stateObj);
-                    stateObj.WriteByte(column.Flags);
-                }
-            }
-        }
-
-        internal Task WriteBulkCopyDone(TdsParserStateObject stateObj)
-        {
-            // Write DONE packet
-            //
-            if (!(State == TdsParserState.OpenNotLoggedIn || State == TdsParserState.OpenLoggedIn))
-            {
-                throw ADP.ClosedConnectionError();
-            }
-            stateObj.WriteByte(TdsEnums.SQLDONE);
-            WriteShort(0, stateObj);
-            WriteShort(0, stateObj);
-            WriteInt(0, stateObj);
-
-            stateObj._pendingData = true;
-            stateObj._messageStatus = 0;
-            return stateObj.WritePacket(TdsEnums.HARDFLUSH);
-        }
-
-        internal void WriteBulkCopyMetaData(_SqlMetaDataSet metadataCollection, int count, TdsParserStateObject stateObj)
-        {
-            if (!(State == TdsParserState.OpenNotLoggedIn || State == TdsParserState.OpenLoggedIn))
-            {
-                throw ADP.ClosedConnectionError();
-            }
-
-            stateObj.WriteByte(TdsEnums.SQLCOLMETADATA);
-            WriteShort(count, stateObj);
-
-            for (int i = 0; i < metadataCollection.Length; i++)
-            {
-                if (metadataCollection[i] != null)
-                {
-                    _SqlMetaData md = metadataCollection[i];
-
-                    // read user type - 4 bytes Yukon, 2 backwards
-                    WriteInt(0x0, stateObj);
-
-                    ushort flags;
-
-                    flags = (ushort)(md.Updatability << 2);
-                    flags |= (ushort)(md.IsNullable ? (ushort)TdsEnums.Nullable : (ushort)0);
-                    flags |= (ushort)(md.IsIdentity ? (ushort)TdsEnums.Identity : (ushort)0);
-
-                    WriteShort(flags, stateObj);      // write the flags
-
-
-                    switch (md.type)
-                    {
-                        case SqlDbType.Decimal:
-                            stateObj.WriteByte(md.tdsType);
-                            WriteTokenLength(md.tdsType, md.length, stateObj);
-                            stateObj.WriteByte(md.precision);
-                            stateObj.WriteByte(md.scale);
-                            break;
-                        case SqlDbType.Xml:
-                            stateObj.WriteByteArray(s_xmlMetadataSubstituteSequence, s_xmlMetadataSubstituteSequence.Length, 0);
-                            break;
-                        case SqlDbType.Udt:
-                            stateObj.WriteByte(TdsEnums.SQLBIGVARBINARY);
-                            WriteTokenLength(TdsEnums.SQLBIGVARBINARY, md.length, stateObj);
-                            break;
-                        case SqlDbType.Date:
-                            stateObj.WriteByte(md.tdsType);
-                            break;
-                        case SqlDbType.Time:
-                        case SqlDbType.DateTime2:
-                        case SqlDbType.DateTimeOffset:
-                            stateObj.WriteByte(md.tdsType);
-                            stateObj.WriteByte(md.scale);
-                            break;
-                        default:
-                            stateObj.WriteByte(md.tdsType);
-                            WriteTokenLength(md.tdsType, md.length, stateObj);
-                            if (md.metaType.IsCharType)
-                            {
-                                WriteUnsignedInt(md.collation.info, stateObj);
-                                stateObj.WriteByte(md.collation.sortId);
-                            }
-                            break;
-                    }
-
-                    if (md.metaType.IsLong && !md.metaType.IsPlp)
-                    {
-                        WriteShort(md.tableName.Length, stateObj);
-                        WriteString(md.tableName, stateObj);
-                    }
-
-                    stateObj.WriteByte((byte)md.column.Length);
-                    WriteString(md.column, stateObj);
-                }
-            } // end for loop
-        }
-
-        internal Task WriteBulkCopyValue(object value, SqlMetaDataPriv metadata, TdsParserStateObject stateObj, bool isSqlType, bool isDataFeed, bool isNull)
-        {
-            Debug.Assert(!isSqlType || value is INullable, "isSqlType is true, but value can not be type cast to an INullable");
-            Debug.Assert(!isDataFeed ^ value is DataFeed, "Incorrect value for isDataFeed");
-
-            Encoding saveEncoding = _defaultEncoding;
-            SqlCollation saveCollation = _defaultCollation;
-            int saveCodePage = _defaultCodePage;
-            int saveLCID = _defaultLCID;
-            Task resultTask = null;
-            Task internalWriteTask = null;
-
-            if (!(State == TdsParserState.OpenNotLoggedIn || State == TdsParserState.OpenLoggedIn))
-            {
-                throw ADP.ClosedConnectionError();
-            }
-            try
-            {
-                if (metadata.encoding != null)
-                {
-                    _defaultEncoding = metadata.encoding;
-                }
-                if (metadata.collation != null)
-                {
-                    // Replace encoding if it is UTF8
-                    if ((metadata.collation.info & TdsEnums.UTF8_IN_TDSCOLLATION) == TdsEnums.UTF8_IN_TDSCOLLATION)
-                    {
-                        _defaultEncoding = Encoding.UTF8;
-                    }
-
-                    _defaultCollation = metadata.collation;
-                    _defaultLCID = _defaultCollation.LCID;
-                }
-                _defaultCodePage = metadata.codePage;
-
-                MetaType metatype = metadata.metaType;
-                int ccb = 0;
-                int ccbStringBytes = 0;
-
-                if (isNull)
-                {
-                    // For UDT, remember we treat as binary even though it is a PLP
-                    if (metatype.IsPlp && (metatype.NullableType != TdsEnums.SQLUDT || metatype.IsLong))
-                    {
-                        WriteLong(unchecked((long)TdsEnums.SQL_PLP_NULL), stateObj);
-                    }
-                    else if (!metatype.IsFixed && !metatype.IsLong && !metatype.IsVarTime)
-                    {
-                        WriteShort(TdsEnums.VARNULL, stateObj);
-                    }
-                    else
-                    {
-                        stateObj.WriteByte(TdsEnums.FIXEDNULL);
-                    }
-                    return resultTask;
-                }
-
-                if (!isDataFeed)
-                {
-                    switch (metatype.NullableType)
-                    {
-                        case TdsEnums.SQLBIGBINARY:
-                        case TdsEnums.SQLBIGVARBINARY:
-                        case TdsEnums.SQLIMAGE:
-                        case TdsEnums.SQLUDT:
-                            ccb = (isSqlType) ? ((SqlBinary)value).Length : ((byte[])value).Length;
-                            break;
-                        case TdsEnums.SQLUNIQUEID:
-                            ccb = GUID_SIZE;
-                            break;
-                        case TdsEnums.SQLBIGCHAR:
-                        case TdsEnums.SQLBIGVARCHAR:
-                        case TdsEnums.SQLTEXT:
-                            if (null == _defaultEncoding)
-                            {
-                                ThrowUnsupportedCollationEncountered(null); // stateObject only when reading
-                            }
-
-                            string stringValue = null;
-                            if (isSqlType)
-                            {
-                                stringValue = ((SqlString)value).Value;
-                            }
-                            else
-                            {
-                                stringValue = (string)value;
-                            }
-
-                            ccb = stringValue.Length;
-                            ccbStringBytes = _defaultEncoding.GetByteCount(stringValue);
-                            break;
-                        case TdsEnums.SQLNCHAR:
-                        case TdsEnums.SQLNVARCHAR:
-                        case TdsEnums.SQLNTEXT:
-                            ccb = ((isSqlType) ? ((SqlString)value).Value.Length : ((string)value).Length) * 2;
-                            break;
-                        case TdsEnums.SQLXMLTYPE:
-                            // Value here could be string or XmlReader
-                            if (value is XmlReader)
-                            {
-                                value = MetaType.GetStringFromXml((XmlReader)value);
-                            }
-                            ccb = ((isSqlType) ? ((SqlString)value).Value.Length : ((string)value).Length) * 2;
-                            break;
-
-                        default:
-                            ccb = metadata.length;
-                            break;
-                    }
-                }
-                else
-                {
-                    Debug.Assert(metatype.IsLong &&
-                        ((metatype.SqlDbType == SqlDbType.VarBinary && value is StreamDataFeed) ||
-                         ((metatype.SqlDbType == SqlDbType.VarChar || metatype.SqlDbType == SqlDbType.NVarChar) && value is TextDataFeed) ||
-                         (metatype.SqlDbType == SqlDbType.Xml && value is XmlDataFeed)),
-                   "Stream data feed should only be assigned to VarBinary(max), Text data feed should only be assigned to [N]VarChar(max), Xml data feed should only be assigned to XML(max)");
-                }
-
-
-                // Expected the text length in data stream for bulk copy of text, ntext, or image data.
-                //
-                if (metatype.IsLong)
-                {
-                    switch (metatype.SqlDbType)
-                    {
-                        case SqlDbType.Text:
-                        case SqlDbType.NText:
-                        case SqlDbType.Image:
-                            stateObj.WriteByteArray(s_longDataHeader, s_longDataHeader.Length, 0);
-                            WriteTokenLength(metadata.tdsType, ccbStringBytes == 0 ? ccb : ccbStringBytes, stateObj);
-                            break;
-
-                        case SqlDbType.VarChar:
-                        case SqlDbType.NVarChar:
-                        case SqlDbType.VarBinary:
-                        case SqlDbType.Xml:
-                        case SqlDbType.Udt:
-                            // plp data
-                            WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, stateObj);
-                            break;
-                    }
-                }
-                else
-                {
-                    WriteTokenLength(metadata.tdsType, ccbStringBytes == 0 ? ccb : ccbStringBytes, stateObj);
-                }
-
-                if (isSqlType)
-                {
-                    internalWriteTask = WriteSqlValue(value, metatype, ccb, ccbStringBytes, 0, stateObj);
-                }
-                else if (metatype.SqlDbType != SqlDbType.Udt || metatype.IsLong)
-                {
-                    internalWriteTask = WriteValue(value, metatype, metadata.scale, ccb, ccbStringBytes, 0, stateObj, metadata.length, isDataFeed);
-                    if ((internalWriteTask == null) && (_asyncWrite))
-                    {
-                        internalWriteTask = stateObj.WaitForAccumulatedWrites();
-                    }
-                    Debug.Assert(_asyncWrite || stateObj.WaitForAccumulatedWrites() == null, "Should not have accumulated writes when writing sync");
-                }
-                else
-                {
-                    WriteShort(ccb, stateObj);
-                    internalWriteTask = stateObj.WriteByteArray((byte[])value, ccb, 0);
-                }
-
-#if DEBUG
-                //In DEBUG mode, when SetAlwaysTaskOnWrite is true, we create a task. Allows us to verify async execution paths.
-                if (_asyncWrite && internalWriteTask == null && SqlBulkCopy.SetAlwaysTaskOnWrite == true)
-                {
-                    internalWriteTask = Task.FromResult<object>(null);
-                }
-#endif
-                if (internalWriteTask != null)
-                { //i.e. the write was async.
-                    resultTask = WriteBulkCopyValueSetupContinuation(internalWriteTask, saveEncoding, saveCollation, saveCodePage, saveLCID);
-                }
-            }
-            finally
-            {
-                if (internalWriteTask == null)
-                {
-                    _defaultEncoding = saveEncoding;
-                    _defaultCollation = saveCollation;
-                    _defaultCodePage = saveCodePage;
-                    _defaultLCID = saveLCID;
-                }
-            }
-            return resultTask;
-        }
-
-        // This is in its own method to avoid always allocating the lambda in WriteBulkCopyValue
-        private Task WriteBulkCopyValueSetupContinuation(Task internalWriteTask, Encoding saveEncoding, SqlCollation saveCollation, int saveCodePage, int saveLCID)
-        {
-            return internalWriteTask.ContinueWith<Task>(t =>
-            {
-                _defaultEncoding = saveEncoding;
-                _defaultCollation = saveCollation;
-                _defaultCodePage = saveCodePage;
-                _defaultLCID = saveLCID;
-                return t;
-            }, TaskScheduler.Default).Unwrap();
-        }
-
-        // Write mars header data, not including the mars header length
-        private void WriteMarsHeaderData(TdsParserStateObject stateObj, SqlInternalTransaction transaction)
-        {
-            // Function to send over additional payload header data for Yukon and beyond only.
-
-            // These are not necessary - can have local started in distributed.
-            // Debug.Assert(!(null != sqlTransaction && null != distributedTransaction), "Error to have local (api started) and distributed transaction at the same time!");
-            // Debug.Assert(!(null != _userStartedLocalTransaction && null != distributedTransaction), "Error to have local (started outside of the api) and distributed transaction at the same time!");
-
-            // We may need to update the mars header length if mars header is changed in the future
-
-            WriteShort(TdsEnums.HEADERTYPE_MARS, stateObj);
-
-            if (null != transaction && SqlInternalTransaction.NullTransactionId != transaction.TransactionId)
-            {
-                WriteLong(transaction.TransactionId, stateObj);
-                WriteInt(stateObj.IncrementAndObtainOpenResultCount(transaction), stateObj);
-            }
-            else
-            {
-                WriteLong(SqlInternalTransaction.NullTransactionId, stateObj);
-                WriteInt(stateObj.IncrementAndObtainOpenResultCount(null), stateObj);
-            }
-        }
-
-        private int GetNotificationHeaderSize(SqlNotificationRequest notificationRequest)
-        {
-            if (null != notificationRequest)
-            {
-                string callbackId = notificationRequest.UserData;
-                string service = notificationRequest.Options;
-                int timeout = notificationRequest.Timeout;
-
-                if (null == callbackId)
-                {
-                    throw ADP.ArgumentNull(nameof(callbackId));
-                }
-                else if (ushort.MaxValue < callbackId.Length)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(callbackId));
-                }
-
-                if (null == service)
-                {
-                    throw ADP.ArgumentNull(nameof(service));
-                }
-                else if (ushort.MaxValue < service.Length)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(service));
-                }
-
-                if (-1 > timeout)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(timeout));
-                }
-
-                // Header Length (uint) (included in size) (already written to output buffer)
-                // Header Type (ushort)
-                // NotifyID Length (ushort)
-                // NotifyID UnicodeStream (unicode text)
-                // SSBDeployment Length (ushort)
-                // SSBDeployment UnicodeStream (unicode text)
-                // Timeout (uint) -- optional
-                // Don't send timeout value if it is 0
-
-                int headerLength = 4 + 2 + 2 + (callbackId.Length * 2) + 2 + (service.Length * 2);
-                if (timeout > 0)
-                    headerLength += 4;
-                return headerLength;
-            }
-            else
-            {
-                return 0;
-            }
-        }
-
-        // Write query notificaiton header data, not including the notificaiton header length
-        private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj)
-        {
-            Debug.Assert(_isYukon, "WriteQueryNotificationHeaderData called on a non-Yukon server");
-
-            // We may need to update the notification header length if the header is changed in the future
-
-            Debug.Assert(null != notificationRequest, "notificaitonRequest is null");
-
-            string callbackId = notificationRequest.UserData;
-            string service = notificationRequest.Options;
-            int timeout = notificationRequest.Timeout;
-
-            // we did verification in GetNotificationHeaderSize, so just assert here.
-            Debug.Assert(null != callbackId, "CallbackId is null");
-            Debug.Assert(ushort.MaxValue >= callbackId.Length, "CallbackId length is out of range");
-            Debug.Assert(null != service, "Service is null");
-            Debug.Assert(ushort.MaxValue >= service.Length, "Service length is out of range");
-            Debug.Assert(-1 <= timeout, "Timeout");
-
-            WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj);      // Query notifications Type
-
-            WriteShort(callbackId.Length * 2, stateObj); // Length in bytes
-            WriteString(callbackId, stateObj);
-
-            WriteShort(service.Length * 2, stateObj); // Length in bytes
-            WriteString(service, stateObj);
-            if (timeout > 0)
-                WriteInt(timeout, stateObj);
-        }
-
-        private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest)
-        {
-            /* Header:
-               TotalLength  - DWORD  - including all headers and lengths, including itself
-               Each Data Session:
-               {
-                     HeaderLength - DWORD  - including all header length fields, including itself
-                     HeaderType   - USHORT
-                     HeaderData
-               }
-            */
-
-            int notificationHeaderSize = GetNotificationHeaderSize(notificationRequest);
-
-            const int marsHeaderSize = 18; // 4 + 2 + 8 + 4
-
-            int totalHeaderLength = 4 + marsHeaderSize + notificationHeaderSize;
-            Debug.Assert(stateObj._outBytesUsed == stateObj._outputHeaderLen, "Output bytes written before total header length");
-            // Write total header length
-            WriteInt(totalHeaderLength, stateObj);
-
-            // Write Mars header length
-            WriteInt(marsHeaderSize, stateObj);
-            // Write Mars header data
-            WriteMarsHeaderData(stateObj, CurrentTransaction);
-
-            if (0 != notificationHeaderSize)
-            {
-                // Write Notification header length
-                WriteInt(notificationHeaderSize, stateObj);
-                // Write notificaiton header data
-                WriteQueryNotificationHeaderData(notificationRequest, stateObj);
-            }
-        }
-
-
-        //
-        // Reverse function of GetTokenLength
-        //
-        private void WriteTokenLength(byte token, int length, TdsParserStateObject stateObj)
-        {
-            int tokenLength = 0;
-
-            Debug.Assert(token != 0, "0 length token!");
-
-            // For Plp fields, this should only be used when writing to metadata header.
-            // For actual data length, WriteDataLength should be used.
-            // For Xml fields, there is no token length field. For MAX fields it is 0xffff.
-            {
-                if (TdsEnums.SQLUDT == token)
-                {
-                    tokenLength = 8;
-                }
-                else if (token == TdsEnums.SQLXMLTYPE)
-                {
-                    tokenLength = 8;
-                }
-            }
-
-            if (tokenLength == 0)
-            {
-                switch (token & TdsEnums.SQLLenMask)
-                {
-                    case TdsEnums.SQLFixedLen:
-                        Debug.Assert(length == 0x01 << ((token & 0x0c) >> 2), "length does not match encoded length in token");
-                        tokenLength = 0;
-                        break;
-
-                    case TdsEnums.SQLZeroLen:
-                        tokenLength = 0;
-                        break;
-
-                    case TdsEnums.SQLVarLen:
-                    case TdsEnums.SQLVarCnt:
-                        if (0 != (token & 0x80))
-                            tokenLength = 2;
-                        else if (0 == (token & 0x0c))
-                            tokenLength = 4;
-                        else
-                            tokenLength = 1;
-
-                        break;
-
-                    default:
-                        Debug.Fail("Unknown token length!");
-                        break;
-                }
-
-                switch (tokenLength)
-                {
-                    case 1:
-                        stateObj.WriteByte((byte)length);
-                        break;
-
-                    case 2:
-                        WriteShort(length, stateObj);
-                        break;
-
-                    case 4:
-                        WriteInt(length, stateObj);
-                        break;
-
-                    case 8:
-                        // In the metadata case we write 0xffff for partial length prefixed types.
-                        //  For actual data length preceding data, WriteDataLength should be used.
-                        WriteShort(TdsEnums.SQL_USHORTVARMAXLEN, stateObj);
-                        break;
-                } // end switch
-            }
-        }
-
-        // Returns true if BOM byte mark is needed for an XML value
-        private bool IsBOMNeeded(MetaType type, object value)
-        {
-            if (type.NullableType == TdsEnums.SQLXMLTYPE)
-            {
-                Type currentType = value.GetType();
-
-                if (currentType == typeof(SqlString))
-                {
-                    if (!((SqlString)value).IsNull && ((((SqlString)value).Value).Length > 0))
-                    {
-                        if ((((SqlString)value).Value[0] & 0xff) != 0xff)
-                            return true;
-                    }
-                }
-                else if ((currentType == typeof(string)) && (((string)value).Length > 0))
-                {
-                    if ((value != null) && (((string)value)[0] & 0xff) != 0xff)
-                        return true;
-                }
-                else if (currentType == typeof(SqlXml))
-                {
-                    if (!((SqlXml)value).IsNull)
-                        return true;
-                }
-                else if (currentType == typeof(XmlDataFeed))
-                {
-                    return true;             // Values will eventually converted to unicode string here
-                }
-            }
-            return false;
-        }
-
-        private Task GetTerminationTask(Task unterminatedWriteTask, object value, MetaType type, int actualLength, TdsParserStateObject stateObj, bool isDataFeed)
-        {
-            if (type.IsPlp && ((actualLength > 0) || isDataFeed))
-            {
-                if (unterminatedWriteTask == null)
-                {
-                    WriteInt(0, stateObj);
-                    return null;
-                }
-                else
-                {
-                    return AsyncHelper.CreateContinuationTask<int, TdsParserStateObject>(unterminatedWriteTask, WriteInt, 0, stateObj);
-                }
-            }
-            else
-            {
-                return unterminatedWriteTask;
-            }
-        }
-
-
-        private Task WriteSqlValue(object value, MetaType type, int actualLength, int codePageByteSize, int offset, TdsParserStateObject stateObj)
-        {
-            return GetTerminationTask(
-                WriteUnterminatedSqlValue(value, type, actualLength, codePageByteSize, offset, stateObj),
-                value, type, actualLength, stateObj, false);
-        }
-
-        // For MAX types, this method can only write everything in one big chunk. If multiple
-        // chunk writes needed, please use WritePlpBytes/WritePlpChars
-        private Task WriteUnterminatedSqlValue(object value, MetaType type, int actualLength, int codePageByteSize, int offset, TdsParserStateObject stateObj)
-        {
-            Debug.Assert(((type.NullableType == TdsEnums.SQLXMLTYPE) ||
-                   (value is INullable && !((INullable)value).IsNull)),
-                   "unexpected null SqlType!");
-
-            // parameters are always sent over as BIG or N types
-            switch (type.NullableType)
-            {
-                case TdsEnums.SQLFLTN:
-                    if (type.FixedLength == 4)
-                        WriteFloat(((SqlSingle)value).Value, stateObj);
-                    else
-                    {
-                        Debug.Assert(type.FixedLength == 8, "Invalid length for SqlDouble type!");
-                        WriteDouble(((SqlDouble)value).Value, stateObj);
-                    }
-
-                    break;
-
-                case TdsEnums.SQLBIGBINARY:
-                case TdsEnums.SQLBIGVARBINARY:
-                case TdsEnums.SQLIMAGE:
-                    {
-                        if (type.IsPlp)
-                        {
-                            WriteInt(actualLength, stateObj);               // chunk length
-                        }
-
-                        if (value is SqlBinary)
-                        {
-                            return stateObj.WriteByteArray(((SqlBinary)value).Value, actualLength, offset, canAccumulate: false);
-                        }
-                        else
-                        {
-                            Debug.Assert(value is SqlBytes);
-                            return stateObj.WriteByteArray(((SqlBytes)value).Value, actualLength, offset, canAccumulate: false);
-                        }
-                    }
-
-                case TdsEnums.SQLUNIQUEID:
-                    {
-                        Debug.Assert(actualLength == 16, "Invalid length for guid type in com+ object");
-                        Span<byte> b = stackalloc byte[16];
-                        SqlGuid sqlGuid = (SqlGuid)value;
-                        if (sqlGuid.IsNull)
-                        {
-                            b.Clear(); // this is needed because initlocals may be supressed in framework assemblies meaning the memory is not automaticaly zeroed
-                        }
-                        else
-                        {
-                            FillGuidBytes(sqlGuid.Value, b);
-                        }
-                        stateObj.WriteByteSpan(b);
-                        break;
-                    }
-
-                case TdsEnums.SQLBITN:
-                    {
-                        Debug.Assert(type.FixedLength == 1, "Invalid length for SqlBoolean type");
-                        if (((SqlBoolean)value).Value == true)
-                            stateObj.WriteByte(1);
-                        else
-                            stateObj.WriteByte(0);
-
-                        break;
-                    }
-
-                case TdsEnums.SQLINTN:
-                    if (type.FixedLength == 1)
-                        stateObj.WriteByte(((SqlByte)value).Value);
-                    else
-                        if (type.FixedLength == 2)
-                        WriteShort(((SqlInt16)value).Value, stateObj);
-                    else
-                            if (type.FixedLength == 4)
-                        WriteInt(((SqlInt32)value).Value, stateObj);
-                    else
-                    {
-                        Debug.Assert(type.FixedLength == 8, "invalid length for SqlIntN type:  " + type.FixedLength.ToString(CultureInfo.InvariantCulture));
-                        WriteLong(((SqlInt64)value).Value, stateObj);
-                    }
-
-                    break;
-
-                case TdsEnums.SQLBIGCHAR:
-                case TdsEnums.SQLBIGVARCHAR:
-                case TdsEnums.SQLTEXT:
-                    if (type.IsPlp)
-                    {
-                        WriteInt(codePageByteSize, stateObj);               // chunk length
-                    }
-                    if (value is SqlChars)
-                    {
-                        string sch = new string(((SqlChars)value).Value);
-
-                        return WriteEncodingChar(sch, actualLength, offset, _defaultEncoding, stateObj, canAccumulate: false);
-                    }
-                    else
-                    {
-                        Debug.Assert(value is SqlString);
-                        return WriteEncodingChar(((SqlString)value).Value, actualLength, offset, _defaultEncoding, stateObj, canAccumulate: false);
-                    }
-
-
-                case TdsEnums.SQLNCHAR:
-                case TdsEnums.SQLNVARCHAR:
-                case TdsEnums.SQLNTEXT:
-                case TdsEnums.SQLXMLTYPE:
-
-                    if (type.IsPlp)
-                    {
-                        if (IsBOMNeeded(type, value))
-                        {
-                            WriteInt(actualLength + 2, stateObj);               // chunk length
-                            WriteShort(TdsEnums.XMLUNICODEBOM, stateObj);
-                        }
-                        else
-                        {
-                            WriteInt(actualLength, stateObj);               // chunk length
-                        }
-                    }
-
-                    // convert to cchars instead of cbytes
-                    // Xml type is already converted to string through GetCoercedValue
-                    if (actualLength != 0)
-                        actualLength >>= 1;
-
-                    if (value is SqlChars)
-                    {
-                        return WriteCharArray(((SqlChars)value).Value, actualLength, offset, stateObj, canAccumulate: false);
-                    }
-                    else
-                    {
-                        Debug.Assert(value is SqlString);
-                        return WriteString(((SqlString)value).Value, actualLength, offset, stateObj, canAccumulate: false);
-                    }
-
-                case TdsEnums.SQLNUMERICN:
-                    Debug.Assert(type.FixedLength <= 17, "Decimal length cannot be greater than 17 bytes");
-                    WriteSqlDecimal((SqlDecimal)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLDATETIMN:
-                    SqlDateTime dt = (SqlDateTime)value;
-
-                    if (type.FixedLength == 4)
-                    {
-                        if (0 > dt.DayTicks || dt.DayTicks > ushort.MaxValue)
-                            throw SQL.SmallDateTimeOverflow(dt.ToString());
-
-                        WriteShort(dt.DayTicks, stateObj);
-                        WriteShort(dt.TimeTicks / SqlDateTime.SQLTicksPerMinute, stateObj);
-                    }
-                    else
-                    {
-                        WriteInt(dt.DayTicks, stateObj);
-                        WriteInt(dt.TimeTicks, stateObj);
-                    }
-
-                    break;
-
-                case TdsEnums.SQLMONEYN:
-                    {
-                        WriteSqlMoney((SqlMoney)value, type.FixedLength, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLUDT:
-                    Debug.Fail("Called WriteSqlValue on UDT param.Should have already been handled");
-                    throw SQL.UDTUnexpectedResult(value.GetType().AssemblyQualifiedName);
-
-                default:
-                    Debug.Fail("Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
-                    break;
-            } // switch
-            // return point for accumulated writes, note: non-accumulated writes returned from their case statements
-            return null;
-        }
-
-        private sealed class TdsOutputStream : Stream
-        {
-            private readonly TdsParser _parser;
-            private readonly TdsParserStateObject _stateObj;
-            private byte[] _preambleToStrip;
-
-            public TdsOutputStream(TdsParser parser, TdsParserStateObject stateObj, byte[] preambleToStrip)
-            {
-                _parser = parser;
-                _stateObj = stateObj;
-                _preambleToStrip = preambleToStrip;
-            }
-
-            public override bool CanRead
-            {
-                get { return false; }
-            }
-
-            public override bool CanSeek
-            {
-                get { return false; }
-            }
-
-            public override bool CanWrite
-            {
-                get { return true; }
-            }
-
-            public override void Flush()
-            {
-                // NOOP
-            }
-
-            public override long Length
-            {
-                get { throw new NotSupportedException(); }
-            }
-
-            public override long Position
-            {
-                get
-                {
-                    throw new NotSupportedException();
-                }
-                set
-                {
-                    throw new NotSupportedException();
-                }
-            }
-
-            public override int Read(byte[] buffer, int offset, int count)
-            {
-                throw new NotSupportedException();
-            }
-
-            public override long Seek(long offset, SeekOrigin origin)
-            {
-                throw new NotSupportedException();
-            }
-
-            public override void SetLength(long value)
-            {
-                throw new NotSupportedException();
-            }
-
-            private void StripPreamble(byte[] buffer, ref int offset, ref int count)
-            {
-                if (_preambleToStrip != null && count >= _preambleToStrip.Length)
-                {
-                    for (int idx = 0; idx < _preambleToStrip.Length; idx++)
-                    {
-                        if (_preambleToStrip[idx] != buffer[idx])
-                        {
-                            _preambleToStrip = null;
-                            return;
-                        }
-                    }
-
-                    offset += _preambleToStrip.Length;
-                    count -= _preambleToStrip.Length;
-                }
-                _preambleToStrip = null;
-            }
-
-            public override void Write(byte[] buffer, int offset, int count)
-            {
-                Debug.Assert(!_parser._asyncWrite);
-                ValidateWriteParameters(buffer, offset, count);
-
-                StripPreamble(buffer, ref offset, ref count);
-
-                if (count > 0)
-                {
-                    _parser.WriteInt(count, _stateObj); // write length of chunk
-                    _stateObj.WriteByteArray(buffer, count, offset);
-                }
-            }
-
-            public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
-            {
-                Debug.Assert(_parser._asyncWrite);
-                ValidateWriteParameters(buffer, offset, count);
-
-                StripPreamble(buffer, ref offset, ref count);
-
-                Task task = null;
-                if (count > 0)
-                {
-                    _parser.WriteInt(count, _stateObj); // write length of chunk
-                    task = _stateObj.WriteByteArray(buffer, count, offset, canAccumulate: false);
-                }
-
-                return task ?? Task.CompletedTask;
-            }
-
-            internal static void ValidateWriteParameters(byte[] buffer, int offset, int count)
-            {
-                if (buffer == null)
-                {
-                    throw ADP.ArgumentNull(nameof(buffer));
-                }
-                if (offset < 0)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(offset));
-                }
-                if (count < 0)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(count));
-                }
-                try
-                {
-                    if (checked(offset + count) > buffer.Length)
-                    {
-                        throw ExceptionBuilder.InvalidOffsetLength();
-                    }
-                }
-                catch (OverflowException)
-                {
-                    // If we've overflowed when adding offset and count, then they never would have fit into buffer anyway
-                    throw ExceptionBuilder.InvalidOffsetLength();
-                }
-            }
-        }
-
-        private sealed class ConstrainedTextWriter : TextWriter
-        {
-            private readonly TextWriter _next;
-            private readonly int _size;
-            private int _written;
-
-            public ConstrainedTextWriter(TextWriter next, int size)
-            {
-                _next = next;
-                _size = size;
-                _written = 0;
-
-                if (_size < 1)
-                {
-                    _size = int.MaxValue;
-                }
-            }
-
-            public bool IsComplete
-            {
-                get
-                {
-                    return _size > 0 && _written >= _size;
-                }
-            }
-
-            public override Encoding Encoding
-            {
-                get { return _next.Encoding; }
-            }
-
-            public override void Flush()
-            {
-                _next.Flush();
-            }
-
-            public override Task FlushAsync()
-            {
-                return _next.FlushAsync();
-            }
-
-            public override void Write(char value)
-            {
-                if (_written < _size)
-                {
-                    _next.Write(value);
-                    _written++;
-                }
-                Debug.Assert(_size < 0 || _written <= _size, $"Length of data written exceeds specified length.  Written: {_written}, specified: {_size}");
-            }
-
-            public override void Write(char[] buffer, int index, int count)
-            {
-                ValidateWriteParameters(buffer, index, count);
-
-                Debug.Assert(_size >= _written);
-                count = Math.Min(_size - _written, count);
-                if (count > 0)
-                {
-                    _next.Write(buffer, index, count);
-                }
-                _written += count;
-            }
-
-            public override Task WriteAsync(char value)
-            {
-                if (_written < _size)
-                {
-                    _written++;
-                    return _next.WriteAsync(value);
-                }
-
-                return Task.CompletedTask;
-            }
-
-            public override Task WriteAsync(char[] buffer, int index, int count)
-            {
-                ValidateWriteParameters(buffer, index, count);
-
-                Debug.Assert(_size >= _written);
-                count = Math.Min(_size - _written, count);
-                if (count > 0)
-                {
-                    _written += count;
-                    return _next.WriteAsync(buffer, index, count);
-                }
-
-                return Task.CompletedTask;
-            }
-
-            public override Task WriteAsync(string value)
-            {
-                return WriteAsync(value.ToCharArray());
-            }
-
-            internal static void ValidateWriteParameters(char[] buffer, int offset, int count)
-            {
-                if (buffer == null)
-                {
-                    throw ADP.ArgumentNull(nameof(buffer));
-                }
-                if (offset < 0)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(offset));
-                }
-                if (count < 0)
-                {
-                    throw ADP.ArgumentOutOfRange(nameof(count));
-                }
-                try
-                {
-                    if (checked(offset + count) > buffer.Length)
-                    {
-                        throw ExceptionBuilder.InvalidOffsetLength();
-                    }
-                }
-                catch (OverflowException)
-                {
-                    // If we've overflowed when adding offset and count, then they never would have fit into buffer anyway
-                    throw ExceptionBuilder.InvalidOffsetLength();
-                }
-            }
-        }
-
-        private async Task WriteXmlFeed(XmlDataFeed feed, TdsParserStateObject stateObj, bool needBom, Encoding encoding, int size)
-        {
-            byte[] preambleToSkip = null;
-            if (!needBom)
-            {
-                preambleToSkip = encoding.GetPreamble();
-            }
-            XmlWriterSettings writerSettings = new XmlWriterSettings();
-            writerSettings.CloseOutput = false;     // don't close the memory stream
-            writerSettings.ConformanceLevel = ConformanceLevel.Fragment;
-            if (_asyncWrite)
-            {
-                writerSettings.Async = true;
-            }
-            using (ConstrainedTextWriter writer = new ConstrainedTextWriter(new StreamWriter(new TdsOutputStream(this, stateObj, preambleToSkip), encoding), size))
-            using (XmlWriter ww = XmlWriter.Create(writer, writerSettings))
-            {
-                if (feed._source.ReadState == ReadState.Initial)
-                {
-                    feed._source.Read();
-                }
-
-                while (!feed._source.EOF && !writer.IsComplete)
-                {
-                    // We are copying nodes from a reader to a writer.  This will cause the
-                    // XmlDeclaration to be emitted despite ConformanceLevel.Fragment above.
-                    // Therefore, we filter out the XmlDeclaration while copying.
-                    if (feed._source.NodeType == XmlNodeType.XmlDeclaration)
-                    {
-                        feed._source.Read();
-                        continue;
-                    }
-
-                    if (_asyncWrite)
-                    {
-                        await ww.WriteNodeAsync(feed._source, true).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        ww.WriteNode(feed._source, true);
-                    }
-                }
-
-                if (_asyncWrite)
-                {
-                    await ww.FlushAsync().ConfigureAwait(false);
-                }
-                else
-                {
-                    ww.Flush();
-                }
-            }
-        }
-
-        private async Task WriteTextFeed(TextDataFeed feed, Encoding encoding, bool needBom, TdsParserStateObject stateObj, int size)
-        {
-            Debug.Assert(encoding == null || !needBom);
-            char[] inBuff = ArrayPool<char>.Shared.Rent(constTextBufferSize);
-
-            encoding = encoding ?? TextDataFeed.DefaultEncoding;
-
-            using (ConstrainedTextWriter writer = new ConstrainedTextWriter(new StreamWriter(new TdsOutputStream(this, stateObj, null), encoding), size))
-            {
-                if (needBom)
-                {
-                    if (_asyncWrite)
-                    {
-                        await writer.WriteAsync((char)TdsEnums.XMLUNICODEBOM).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        writer.Write((char)TdsEnums.XMLUNICODEBOM);
-                    }
-                }
-
-                int nWritten = 0;
-                do
-                {
-                    int nRead = 0;
-
-                    if (_asyncWrite)
-                    {
-                        nRead = await feed._source.ReadBlockAsync(inBuff, 0, constTextBufferSize).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        nRead = feed._source.ReadBlock(inBuff, 0, constTextBufferSize);
-                    }
-
-                    if (nRead == 0)
-                    {
-                        break;
-                    }
-
-                    if (_asyncWrite)
-                    {
-                        await writer.WriteAsync(inBuff, 0, nRead).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        writer.Write(inBuff, 0, nRead);
-                    }
-
-                    nWritten += nRead;
-                } while (!writer.IsComplete);
-
-                if (_asyncWrite)
-                {
-                    await writer.FlushAsync().ConfigureAwait(false);
-                }
-                else
-                {
-                    writer.Flush();
-                }
-            }
-
-            ArrayPool<char>.Shared.Return(inBuff, clearArray: true);
-        }
-
-        private async Task WriteStreamFeed(StreamDataFeed feed, TdsParserStateObject stateObj, int len)
-        {
-            byte[] buff = ArrayPool<byte>.Shared.Rent(constBinBufferSize);
-
-            using (TdsOutputStream output = new TdsOutputStream(this, stateObj, null))
-            {
-                int nWritten = 0;
-                do
-                {
-                    int nRead = 0;
-                    int readSize = constBinBufferSize;
-                    if (len > 0 && nWritten + readSize > len)
-                    {
-                        readSize = len - nWritten;
-                    }
-
-                    Debug.Assert(readSize >= 0);
-
-                    if (_asyncWrite)
-                    {
-                        nRead = await feed._source.ReadAsync(buff, 0, readSize).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        nRead = feed._source.Read(buff, 0, readSize);
-                    }
-
-                    if (nRead == 0)
-                    {
-                        return;
-                    }
-
-                    if (_asyncWrite)
-                    {
-                        await output.WriteAsync(buff, 0, nRead).ConfigureAwait(false);
-                    }
-                    else
-                    {
-                        output.Write(buff, 0, nRead);
-                    }
-
-                    nWritten += nRead;
-                } while (len <= 0 || nWritten < len);
-            }
-
-            ArrayPool<byte>.Shared.Return(buff, clearArray: true);
-        }
-
-        private Task NullIfCompletedWriteTask(Task task)
-        {
-            if (task == null)
-            {
-                return null;
-            }
-            return task.Status switch
-            {
-                TaskStatus.RanToCompletion => null,
-                TaskStatus.Faulted => throw task.Exception.InnerException,
-                TaskStatus.Canceled => throw SQL.OperationCancelled(),
-                _ => task,
-            };
-        }
-
-        private Task WriteValue(object value, MetaType type, byte scale, int actualLength, int encodingByteSize, int offset, TdsParserStateObject stateObj, int paramSize, bool isDataFeed)
-        {
-            return GetTerminationTask(WriteUnterminatedValue(value, type, scale, actualLength, encodingByteSize, offset, stateObj, paramSize, isDataFeed),
-                value, type, actualLength, stateObj, isDataFeed);
-        }
-
-        // For MAX types, this method can only write everything in one big chunk. If multiple
-        // chunk writes needed, please use WritePlpBytes/WritePlpChars
-        private Task WriteUnterminatedValue(object value, MetaType type, byte scale, int actualLength, int encodingByteSize, int offset, TdsParserStateObject stateObj, int paramSize, bool isDataFeed)
-        {
-            Debug.Assert((null != value) && (DBNull.Value != value), "unexpected missing or empty object");
-
-            // parameters are always sent over as BIG or N types
-            switch (type.NullableType)
-            {
-                case TdsEnums.SQLFLTN:
-                    if (type.FixedLength == 4)
-                        WriteFloat((float)value, stateObj);
-                    else
-                    {
-                        Debug.Assert(type.FixedLength == 8, "Invalid length for SqlDouble type!");
-                        WriteDouble((double)value, stateObj);
-                    }
-
-                    break;
-
-                case TdsEnums.SQLBIGBINARY:
-                case TdsEnums.SQLBIGVARBINARY:
-                case TdsEnums.SQLIMAGE:
-                case TdsEnums.SQLUDT:
-                    {
-                        // An array should be in the object
-                        Debug.Assert(isDataFeed || value is byte[], "Value should be an array of bytes");
-                        Debug.Assert(!isDataFeed || value is StreamDataFeed, "Value should be a stream");
-
-                        if (isDataFeed)
-                        {
-                            Debug.Assert(type.IsPlp, "Stream assigned to non-PLP was not converted!");
-                            return NullIfCompletedWriteTask(WriteStreamFeed((StreamDataFeed)value, stateObj, paramSize));
-                        }
-                        else
-                        {
-                            if (type.IsPlp)
-                            {
-                                WriteInt(actualLength, stateObj);               // chunk length
-                            }
-                            return stateObj.WriteByteArray((byte[])value, actualLength, offset, canAccumulate: false);
-                        }
-                    }
-
-                case TdsEnums.SQLUNIQUEID:
-                    {
-                        Debug.Assert(actualLength == 16, "Invalid length for guid type in com+ object");
-                        Span<byte> b = stackalloc byte[16];
-                        FillGuidBytes((System.Guid)value, b);
-                        stateObj.WriteByteSpan(b);
-
-                        break;
-                    }
-
-                case TdsEnums.SQLBITN:
-                    {
-                        Debug.Assert(type.FixedLength == 1, "Invalid length for SqlBoolean type");
-                        if ((bool)value == true)
-                            stateObj.WriteByte(1);
-                        else
-                            stateObj.WriteByte(0);
-
-                        break;
-                    }
-
-                case TdsEnums.SQLINTN:
-                    if (type.FixedLength == 1)
-                        stateObj.WriteByte((byte)value);
-                    else if (type.FixedLength == 2)
-                        WriteShort((short)value, stateObj);
-                    else if (type.FixedLength == 4)
-                        WriteInt((int)value, stateObj);
-                    else
-                    {
-                        Debug.Assert(type.FixedLength == 8, "invalid length for SqlIntN type:  " + type.FixedLength.ToString(CultureInfo.InvariantCulture));
-                        WriteLong((long)value, stateObj);
-                    }
-
-                    break;
-
-                case TdsEnums.SQLBIGCHAR:
-                case TdsEnums.SQLBIGVARCHAR:
-                case TdsEnums.SQLTEXT:
-                    {
-                        Debug.Assert(!isDataFeed || (value is TextDataFeed || value is XmlDataFeed), "Value must be a TextReader or XmlReader");
-                        Debug.Assert(isDataFeed || (value is string || value is byte[]), "Value is a byte array or string");
-
-                        if (isDataFeed)
-                        {
-                            Debug.Assert(type.IsPlp, "Stream assigned to non-PLP was not converted!");
-                            TextDataFeed tdf = value as TextDataFeed;
-                            if (tdf == null)
-                            {
-                                return NullIfCompletedWriteTask(WriteXmlFeed((XmlDataFeed)value, stateObj, needBom: true, encoding: _defaultEncoding, size: paramSize));
-                            }
-                            else
-                            {
-                                return NullIfCompletedWriteTask(WriteTextFeed(tdf, _defaultEncoding, false, stateObj, paramSize));
-                            }
-                        }
-                        else
-                        {
-                            if (type.IsPlp)
-                            {
-                                WriteInt(encodingByteSize, stateObj);               // chunk length
-                            }
-                            if (value is byte[])
-                            { // If LazyMat non-filled blob, send cookie rather than value
-                                return stateObj.WriteByteArray((byte[])value, actualLength, 0, canAccumulate: false);
-                            }
-                            else
-                            {
-                                return WriteEncodingChar((string)value, actualLength, offset, _defaultEncoding, stateObj, canAccumulate: false);
-                            }
-                        }
-                    }
-                case TdsEnums.SQLNCHAR:
-                case TdsEnums.SQLNVARCHAR:
-                case TdsEnums.SQLNTEXT:
-                case TdsEnums.SQLXMLTYPE:
-                    {
-                        Debug.Assert(!isDataFeed || (value is TextDataFeed || value is XmlDataFeed), "Value must be a TextReader or XmlReader");
-                        Debug.Assert(isDataFeed || (value is string || value is byte[]), "Value is a byte array or string");
-
-                        if (isDataFeed)
-                        {
-                            Debug.Assert(type.IsPlp, "Stream assigned to non-PLP was not converted!");
-                            TextDataFeed tdf = value as TextDataFeed;
-                            if (tdf == null)
-                            {
-                                return NullIfCompletedWriteTask(WriteXmlFeed((XmlDataFeed)value, stateObj, IsBOMNeeded(type, value), Encoding.Unicode, paramSize));
-                            }
-                            else
-                            {
-                                return NullIfCompletedWriteTask(WriteTextFeed(tdf, null, IsBOMNeeded(type, value), stateObj, paramSize));
-                            }
-                        }
-                        else
-                        {
-                            if (type.IsPlp)
-                            {
-                                if (IsBOMNeeded(type, value))
-                                {
-                                    WriteInt(actualLength + 2, stateObj);               // chunk length
-                                    WriteShort(TdsEnums.XMLUNICODEBOM, stateObj);
-                                }
-                                else
-                                {
-                                    WriteInt(actualLength, stateObj);               // chunk length
-                                }
-                            }
-                            if (value is byte[])
-                            { // If LazyMat non-filled blob, send cookie rather than value
-                                return stateObj.WriteByteArray((byte[])value, actualLength, 0, canAccumulate: false);
-                            }
-                            else
-                            {
-                                // convert to cchars instead of cbytes
-                                actualLength >>= 1;
-                                return WriteString((string)value, actualLength, offset, stateObj, canAccumulate: false);
-                            }
-                        }
-                    }
-                case TdsEnums.SQLNUMERICN:
-                    Debug.Assert(type.FixedLength <= 17, "Decimal length cannot be greater than 17 bytes");
-                    WriteDecimal((decimal)value, stateObj);
-                    break;
-
-                case TdsEnums.SQLDATETIMN:
-                    Debug.Assert(type.FixedLength <= 0xff, "Invalid Fixed Length");
-
-                    TdsDateTime dt = MetaType.FromDateTime((DateTime)value, (byte)type.FixedLength);
-
-                    if (type.FixedLength == 4)
-                    {
-                        if (0 > dt.days || dt.days > ushort.MaxValue)
-                            throw SQL.SmallDateTimeOverflow(MetaType.ToDateTime(dt.days, dt.time, 4).ToString(CultureInfo.InvariantCulture));
-
-                        WriteShort(dt.days, stateObj);
-                        WriteShort(dt.time, stateObj);
-                    }
-                    else
-                    {
-                        WriteInt(dt.days, stateObj);
-                        WriteInt(dt.time, stateObj);
-                    }
-
-                    break;
-
-                case TdsEnums.SQLMONEYN:
-                    {
-                        WriteCurrency((decimal)value, type.FixedLength, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLDATE:
-                    {
-                        WriteDate((DateTime)value, stateObj);
-                        break;
-                    }
-
-                case TdsEnums.SQLTIME:
-                    if (scale > TdsEnums.DEFAULT_VARTIME_SCALE)
-                    {
-                        throw SQL.TimeScaleValueOutOfRange(scale);
-                    }
-                    WriteTime((TimeSpan)value, scale, actualLength, stateObj);
-                    break;
-
-                case TdsEnums.SQLDATETIME2:
-                    if (scale > TdsEnums.DEFAULT_VARTIME_SCALE)
-                    {
-                        throw SQL.TimeScaleValueOutOfRange(scale);
-                    }
-                    WriteDateTime2((DateTime)value, scale, actualLength, stateObj);
-                    break;
-
-                case TdsEnums.SQLDATETIMEOFFSET:
-                    WriteDateTimeOffset((DateTimeOffset)value, scale, actualLength, stateObj);
-                    break;
-
-                default:
-                    Debug.Fail("Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
-                    break;
-            } // switch
-            // return point for accumulated writes, note: non-accumulated writes returned from their case statements
-            return null;
-            // Debug.WriteLine("value:  " + value.ToString(CultureInfo.InvariantCulture));
-        }
-
-        //
-        // we always send over nullable types for parameters so we always write the varlen fields
-        //
-
-        internal void WriteParameterVarLen(MetaType type, int size, bool isNull, TdsParserStateObject stateObj, bool unknownLength = false)
-        {
-            if (type.IsLong)
-            { // text/image/SQLVariant have a 4 byte length, plp datatypes have 8 byte lengths
-                if (isNull)
-                {
-                    if (type.IsPlp)
-                    {
-                        WriteLong(unchecked((long)TdsEnums.SQL_PLP_NULL), stateObj);
-                    }
-                    else
-                    {
-                        WriteInt(unchecked((int)TdsEnums.VARLONGNULL), stateObj);
-                    }
-                }
-                else if (type.NullableType == TdsEnums.SQLXMLTYPE || unknownLength)
-                {
-                    WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, stateObj);
-                }
-                else if (type.IsPlp)
-                {
-                    // Non-xml plp types
-                    WriteLong((long)size, stateObj);
-                }
-                else
-                {
-                    WriteInt(size, stateObj);
-                }
-            }
-            else if (type.IsVarTime)
-            {
-                if (isNull)
-                {
-                    stateObj.WriteByte(TdsEnums.FIXEDNULL);
-                }
-                else
-                {
-                    stateObj.WriteByte((byte)size);
-                }
-            }
-            else if (false == type.IsFixed)
-            { // non-long but variable length column, must be a BIG* type: 2 byte length
-                if (isNull)
-                {
-                    WriteShort(TdsEnums.VARNULL, stateObj);
-                }
-                else
-                {
-                    WriteShort(size, stateObj);
-                }
-            }
-            else
-            {
-                if (isNull)
-                {
-                    stateObj.WriteByte(TdsEnums.FIXEDNULL);
-                }
-                else
-                {
-                    Debug.Assert(type.FixedLength <= 0xff, "WriteParameterVarLen: invalid one byte length!");
-                    stateObj.WriteByte((byte)(type.FixedLength & 0xff)); // 1 byte for everything else
-                }
-            }
-        }
-
-        // Reads the next chunk in a nvarchar(max) data stream.
-        // This call must be preceded by a call to ReadPlpLength or ReadDataLength.
-        // Will not start reading into the next chunk if bytes requested is larger than
-        // the current chunk length. Do another ReadPlpLength, ReadPlpUnicodeChars in that case.
-        // Returns the actual chars read
-        private bool TryReadPlpUnicodeCharsChunk(char[] buff, int offst, int len, TdsParserStateObject stateObj, out int charsRead)
-        {
-            Debug.Assert((buff == null && len == 0) || (buff.Length >= offst + len), "Invalid length sent to ReadPlpUnicodeChars()!");
-            Debug.Assert((stateObj._longlen != 0) && (stateObj._longlen != TdsEnums.SQL_PLP_NULL),
-                        "Out of sync plp read request");
-            if (stateObj._longlenleft == 0)
-            {
-                Debug.Fail("Out of sync read request");
-                charsRead = 0;
-                return true;
-            }
-
-            charsRead = len;
-
-            // stateObj._longlenleft is in bytes
-            if ((stateObj._longlenleft >> 1) < (ulong)len)
-                charsRead = (int)(stateObj._longlenleft >> 1);
-
-            for (int ii = 0; ii < charsRead; ii++)
-            {
-                if (!stateObj.TryReadChar(out buff[offst + ii]))
-                {
-                    return false;
-                }
-            }
-
-            stateObj._longlenleft -= ((ulong)charsRead << 1);
-            return true;
-        }
-
-        internal int ReadPlpUnicodeChars(ref char[] buff, int offst, int len, TdsParserStateObject stateObj)
-        {
-            int charsRead;
-            Debug.Assert(stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryReadPlpUnicodeChars(ref buff, offst, len, stateObj, out charsRead);
-            if (!result)
-            { throw SQL.SynchronousCallMayNotPend(); }
-            return charsRead;
-        }
-
-        // Reads the requested number of chars from a plp data stream, or the entire data if
-        // requested length is -1 or larger than the actual length of data. First call to this method
-        //  should be preceded by a call to ReadPlpLength or ReadDataLength.
-        // Returns the actual chars read.
-        internal bool TryReadPlpUnicodeChars(ref char[] buff, int offst, int len, TdsParserStateObject stateObj, out int totalCharsRead)
-        {
-            int charsRead = 0;
-            int charsLeft = 0;
-            char[] newbuf;
-
-            if (stateObj._longlen == 0)
-            {
-                Debug.Assert(stateObj._longlenleft == 0);
-                totalCharsRead = 0;
-                return true;       // No data
-            }
-
-            Debug.Assert(((ulong)stateObj._longlen != TdsEnums.SQL_PLP_NULL),
-                    "Out of sync plp read request");
-
-            Debug.Assert((buff == null && offst == 0) || (buff.Length >= offst + len), "Invalid length sent to ReadPlpUnicodeChars()!");
-            charsLeft = len;
-
-            // If total length is known up front, allocate the whole buffer in one shot instead of realloc'ing and copying over each time
-            if (buff == null && stateObj._longlen != TdsEnums.SQL_PLP_UNKNOWNLEN)
-            {
-                buff = new char[(int)Math.Min((int)stateObj._longlen, len)];
-            }
-
-            if (stateObj._longlenleft == 0)
-            {
-                ulong ignored;
-                if (!stateObj.TryReadPlpLength(false, out ignored))
-                {
-                    totalCharsRead = 0;
-                    return false;
-                }
-                if (stateObj._longlenleft == 0)
-                { // Data read complete
-                    totalCharsRead = 0;
-                    return true;
-                }
-            }
-
-            totalCharsRead = 0;
-
-            while (charsLeft > 0)
-            {
-                charsRead = (int)Math.Min((stateObj._longlenleft + 1) >> 1, (ulong)charsLeft);
-                if ((buff == null) || (buff.Length < (offst + charsRead)))
-                {
-                    // Grow the array
-                    newbuf = new char[offst + charsRead];
-                    if (buff != null)
-                    {
-                        Buffer.BlockCopy(buff, 0, newbuf, 0, offst * 2);
-                    }
-                    buff = newbuf;
-                }
-                if (charsRead > 0)
-                {
-                    if (!TryReadPlpUnicodeCharsChunk(buff, offst, charsRead, stateObj, out charsRead))
-                    {
-                        return false;
-                    }
-                    charsLeft -= charsRead;
-                    offst += charsRead;
-                    totalCharsRead += charsRead;
-                }
-                // Special case single byte left
-                if (stateObj._longlenleft == 1 && (charsLeft > 0))
-                {
-                    byte b1;
-                    if (!stateObj.TryReadByte(out b1))
-                    {
-                        return false;
-                    }
-                    stateObj._longlenleft--;
-                    ulong ignored;
-                    if (!stateObj.TryReadPlpLength(false, out ignored))
-                    {
-                        return false;
-                    }
-                    Debug.Assert((stateObj._longlenleft != 0), "ReadPlpUnicodeChars: Odd byte left at the end!");
-                    byte b2;
-                    if (!stateObj.TryReadByte(out b2))
-                    {
-                        return false;
-                    }
-                    stateObj._longlenleft--;
-                    // Put it at the end of the array. At this point we know we have an extra byte.
-                    buff[offst] = (char)(((b2 & 0xff) << 8) + (b1 & 0xff));
-                    offst = checked((int)offst + 1);
-                    charsRead++;
-                    charsLeft--;
-                    totalCharsRead++;
-                }
-                if (stateObj._longlenleft == 0)
-                { // Read the next chunk or cleanup state if hit the end
-                    ulong ignored;
-                    if (!stateObj.TryReadPlpLength(false, out ignored))
-                    {
-                        return false;
-                    }
-                }
-
-                if (stateObj._longlenleft == 0)   // Data read complete
-                    break;
-            }
-            return true;
-        }
-
-        internal int ReadPlpAnsiChars(ref char[] buff, int offst, int len, SqlMetaDataPriv metadata, TdsParserStateObject stateObj)
-        {
-            int charsRead = 0;
-            int charsLeft = 0;
-            int bytesRead = 0;
-            int totalcharsRead = 0;
-
-            if (stateObj._longlen == 0)
-            {
-                Debug.Assert(stateObj._longlenleft == 0);
-                return 0;       // No data
-            }
-
-            Debug.Assert(((ulong)stateObj._longlen != TdsEnums.SQL_PLP_NULL),
-                    "Out of sync plp read request");
-
-            Debug.Assert((buff == null && offst == 0) || (buff.Length >= offst + len), "Invalid length sent to ReadPlpAnsiChars()!");
-            charsLeft = len;
-
-            if (stateObj._longlenleft == 0)
-            {
-                stateObj.ReadPlpLength(false);
-                if (stateObj._longlenleft == 0)
-                {// Data read complete
-                    stateObj._plpdecoder = null;
-                    return 0;
-                }
-            }
-
-            if (stateObj._plpdecoder == null)
-            {
-                Encoding enc = metadata.encoding;
-
-                if (enc == null)
-                {
-                    if (null == _defaultEncoding)
-                    {
-                        ThrowUnsupportedCollationEncountered(stateObj);
-                    }
-
-                    enc = _defaultEncoding;
-                }
-                stateObj._plpdecoder = enc.GetDecoder();
-            }
-
-            while (charsLeft > 0)
-            {
-                bytesRead = (int)Math.Min(stateObj._longlenleft, (ulong)charsLeft);
-                if ((stateObj._bTmp == null) || (stateObj._bTmp.Length < bytesRead))
-                {
-                    // Grow the array
-                    stateObj._bTmp = new byte[bytesRead];
-                }
-
-                bytesRead = stateObj.ReadPlpBytesChunk(stateObj._bTmp, 0, bytesRead);
-
-                charsRead = stateObj._plpdecoder.GetChars(stateObj._bTmp, 0, bytesRead, buff, offst);
-                charsLeft -= charsRead;
-                offst += charsRead;
-                totalcharsRead += charsRead;
-                if (stateObj._longlenleft == 0)  // Read the next chunk or cleanup state if hit the end
-                    stateObj.ReadPlpLength(false);
-
-                if (stateObj._longlenleft == 0)
-                { // Data read complete
-                    stateObj._plpdecoder = null;
-                    break;
-                }
-            }
-            return (totalcharsRead);
-        }
-
-        // ensure value is not null and does not have an NBC bit set for it before using this method
-        internal ulong SkipPlpValue(ulong cb, TdsParserStateObject stateObj)
-        {
-            ulong skipped;
-            Debug.Assert(stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TrySkipPlpValue(cb, stateObj, out skipped);
-            if (!result)
-            { throw SQL.SynchronousCallMayNotPend(); }
-            return skipped;
-        }
-
-        internal bool TrySkipPlpValue(ulong cb, TdsParserStateObject stateObj, out ulong totalBytesSkipped)
-        {
-            // Read and skip cb bytes or until  ReadPlpLength returns 0.
-            int bytesSkipped;
-            totalBytesSkipped = 0;
-
-            if (stateObj._longlenleft == 0)
-            {
-                ulong ignored;
-                if (!stateObj.TryReadPlpLength(false, out ignored))
-                {
-                    return false;
-                }
-            }
-
-            while ((totalBytesSkipped < cb) &&
-                    (stateObj._longlenleft > 0))
-            {
-                if (stateObj._longlenleft > int.MaxValue)
-                    bytesSkipped = int.MaxValue;
-                else
-                    bytesSkipped = (int)stateObj._longlenleft;
-                bytesSkipped = ((cb - totalBytesSkipped) < (ulong)bytesSkipped) ? (int)(cb - totalBytesSkipped) : bytesSkipped;
-
-                if (!stateObj.TrySkipBytes(bytesSkipped))
-                {
-                    return false;
-                }
-                stateObj._longlenleft -= (ulong)bytesSkipped;
-                totalBytesSkipped += (ulong)bytesSkipped;
-
-                if (stateObj._longlenleft == 0)
-                {
-                    ulong ignored;
-                    if (!stateObj.TryReadPlpLength(false, out ignored))
-                    {
-                        return false;
-                    }
-                }
-            }
-
-            return true;
-        }
-
-        internal ulong PlpBytesLeft(TdsParserStateObject stateObj)
-        {
-            if ((stateObj._longlen != 0) && (stateObj._longlenleft == 0))
-                stateObj.ReadPlpLength(false);
-
-            return stateObj._longlenleft;
-        }
-
-        internal bool TryPlpBytesLeft(TdsParserStateObject stateObj, out ulong left)
-        {
-            if ((stateObj._longlen != 0) && (stateObj._longlenleft == 0))
-            {
-                if (!stateObj.TryReadPlpLength(false, out left))
-                {
-                    return false;
-                }
-            }
-
-            left = stateObj._longlenleft;
-            return true;
-        }
-
-        private const ulong _indeterminateSize = 0xffffffffffffffff;        // Represents unknown size
-
-        internal ulong PlpBytesTotalLength(TdsParserStateObject stateObj)
-        {
-            if (stateObj._longlen == TdsEnums.SQL_PLP_UNKNOWNLEN)
-                return _indeterminateSize;
-            else if (stateObj._longlen == TdsEnums.SQL_PLP_NULL)
-                return 0;
-
-            return stateObj._longlen;
-        }
-
-        private bool TryProcessUDTMetaData(SqlMetaDataPriv metaData, TdsParserStateObject stateObj)
-        {
-
-            ushort shortLength;
-            byte byteLength;
-
-            if (!stateObj.TryReadUInt16(out shortLength))
-            { // max byte size
-                return false;
-            }
-            metaData.length = shortLength;
-
-            // database name
-            if (!stateObj.TryReadByte(out byteLength))
-            {
-                return false;
-            }
-            if (metaData.udt is null)
-            {
-                metaData.udt = new SqlMetaDataUdt();
-            }
-
-            if (byteLength != 0)
-            {
-                if (!stateObj.TryReadString(byteLength, out metaData.udt.DatabaseName))
-                {
-                    return false;
-                }
-            }
-
-            // schema name
-            if (!stateObj.TryReadByte(out byteLength))
-            {
-                return false;
-            }
-            if (byteLength != 0)
-            {
-                if (!stateObj.TryReadString(byteLength, out metaData.udt.SchemaName))
-                {
-                    return false;
-                }
-            }
-
-            // type name
-            if (!stateObj.TryReadByte(out byteLength))
-            {
-                return false;
-            }
-            if (byteLength != 0)
-            {
-                if (!stateObj.TryReadString(byteLength, out metaData.udt.TypeName))
-                {
-                    return false;
-                }
-            }
-
-            if (!stateObj.TryReadUInt16(out shortLength))
-            {
-                return false;
-            }
-            if (shortLength != 0)
-            {
-                if (!stateObj.TryReadString(shortLength, out metaData.udt.AssemblyQualifiedName))
-                {
-                    return false;
-                }
-            }
-
-            return true;
-        }
-    }    // tdsparser
-}//namespace
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserHelperClasses.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserHelperClasses.cs
deleted file mode 100644 (file)
index f8e3f6e..0000000
+++ /dev/null
@@ -1,837 +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.Buffers;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Data.Common;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Security;
-using System.Text;
-using System.Threading;
-using Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    internal enum CallbackType
-    {
-        Read = 0,
-        Write = 1
-    }
-
-    internal enum EncryptionOptions
-    {
-        OFF,
-        ON,
-        NOT_SUP,
-        REQ,
-        LOGIN
-    }
-
-    internal enum PreLoginHandshakeStatus
-    {
-        Successful,
-        InstanceFailure
-    }
-
-    internal enum PreLoginOptions
-    {
-        VERSION,
-        ENCRYPT,
-        INSTANCE,
-        THREADID,
-        MARS,
-        TRACEID,
-        FEDAUTHREQUIRED,
-        NUMOPT,
-        LASTOPT = 255
-    }
-
-    internal enum RunBehavior
-    {
-        UntilDone = 1, // 0001 binary
-        ReturnImmediately = 2, // 0010 binary
-        Clean = 5, // 0101 binary - Clean AND UntilDone
-        Attention = 13  // 1101 binary - Clean AND UntilDone AND Attention
-    }
-
-    internal enum TdsParserState
-    {
-        Closed,
-        OpenNotLoggedIn,
-        OpenLoggedIn,
-        Broken,
-    }
-
-    /// <summary>
-    /// Struct encapsulating the data to be sent to the server as part of Federated Authentication Feature Extension.
-    /// </summary>
-    internal struct FederatedAuthenticationFeatureExtensionData
-    {
-        internal TdsEnums.FedAuthLibrary libraryType;
-        internal bool fedAuthRequiredPreLoginResponse;
-        internal byte[] accessToken;
-    }
-
-    internal sealed class SqlCollation
-    {
-        // First 20 bits of info field represent the lcid, bits 21-25 are compare options
-        private const uint IgnoreCase = 1 << 20; // bit 21 - IgnoreCase
-        private const uint IgnoreNonSpace = 1 << 21; // bit 22 - IgnoreNonSpace / IgnoreAccent
-        private const uint IgnoreWidth = 1 << 22; // bit 23 - IgnoreWidth
-        private const uint IgnoreKanaType = 1 << 23; // bit 24 - IgnoreKanaType
-        private const uint BinarySort = 1 << 24; // bit 25 - BinarySort
-
-        internal const uint MaskLcid = 0xfffff;
-        private const int LcidVersionBitOffset = 28;
-        private const uint MaskLcidVersion = unchecked((uint)(0xf << LcidVersionBitOffset));
-        private const uint MaskCompareOpt = IgnoreCase | IgnoreNonSpace | IgnoreWidth | IgnoreKanaType | BinarySort;
-
-        internal uint info;
-        internal byte sortId;
-
-        private static int FirstSupportedCollationVersion(int lcid) =>
-            // NOTE: switch-case works ~3 times faster in this case than search with Dictionary
-            lcid switch
-            {
-                1044 => 2, // Norwegian_100_BIN
-                1047 => 2, // Romansh_100_BIN
-                1056 => 2, // Urdu_100_BIN
-                1065 => 2, // Persian_100_BIN
-                1068 => 2, // Azeri_Latin_100_BIN
-                1070 => 2, // Upper_Sorbian_100_BIN
-                1071 => 1, // Macedonian_FYROM_90_BIN
-                1081 => 1, // Indic_General_90_BIN
-                1082 => 2, // Maltese_100_BIN
-                1083 => 2, // Sami_Norway_100_BIN
-                1087 => 1, // Kazakh_90_BIN
-                1090 => 2, // Turkmen_100_BIN
-                1091 => 1, // Uzbek_Latin_90_BIN
-                1092 => 1, // Tatar_90_BIN
-                1093 => 2, // Bengali_100_BIN
-                1101 => 2, // Assamese_100_BIN
-                1105 => 2, // Tibetan_100_BIN
-                1106 => 2, // Welsh_100_BIN
-                1107 => 2, // Khmer_100_BIN
-                1108 => 2, // Lao_100_BIN
-                1114 => 1, // Syriac_90_BIN
-                1121 => 2, // Nepali_100_BIN
-                1122 => 2, // Frisian_100_BIN
-                1123 => 2, // Pashto_100_BIN
-                1125 => 1, // Divehi_90_BIN
-                1133 => 2, // Bashkir_100_BIN
-                1146 => 2, // Mapudungan_100_BIN
-                1148 => 2, // Mohawk_100_BIN
-                1150 => 2, // Breton_100_BIN
-                1152 => 2, // Uighur_100_BIN
-                1153 => 2, // Maori_100_BIN
-                1155 => 2, // Corsican_100_BIN
-                1157 => 2, // Yakut_100_BIN
-                1164 => 2, // Dari_100_BIN
-                2074 => 2, // Serbian_Latin_100_BIN
-                2092 => 2, // Azeri_Cyrillic_100_BIN
-                2107 => 2, // Sami_Sweden_Finland_100_BIN
-                2143 => 2, // Tamazight_100_BIN
-                3076 => 1, // Chinese_Hong_Kong_Stroke_90_BIN
-                3098 => 2, // Serbian_Cyrillic_100_BIN
-                5124 => 2, // Chinese_Traditional_Pinyin_100_BIN
-                5146 => 2, // Bosnian_Latin_100_BIN
-                8218 => 2, // Bosnian_Cyrillic_100_BIN
-
-                _ => 0,   // other LCIDs have collation with version 0
-            };
-
-        internal int LCID
-        {
-            // First 20 bits of info field represent the lcid
-            get
-            {
-                return unchecked((int)(info & MaskLcid));
-            }
-            set
-            {
-                int lcid = value & (int)MaskLcid;
-                Debug.Assert(lcid == value, "invalid set_LCID value");
-
-                // Some new Katmai LCIDs do not have collation with version = 0
-                // since user has no way to specify collation version, we set the first (minimal) supported version for these collations
-                int versionBits = FirstSupportedCollationVersion(lcid) << LcidVersionBitOffset;
-                Debug.Assert((versionBits & MaskLcidVersion) == versionBits, "invalid version returned by FirstSupportedCollationVersion");
-
-                // combine the current compare options with the new locale ID and its first supported version
-                info = (info & MaskCompareOpt) | unchecked((uint)lcid) | unchecked((uint)versionBits);
-            }
-        }
-
-        internal SqlCompareOptions SqlCompareOptions
-        {
-            get
-            {
-                SqlCompareOptions options = SqlCompareOptions.None;
-                if (0 != (info & IgnoreCase))
-                    options |= SqlCompareOptions.IgnoreCase;
-                if (0 != (info & IgnoreNonSpace))
-                    options |= SqlCompareOptions.IgnoreNonSpace;
-                if (0 != (info & IgnoreWidth))
-                    options |= SqlCompareOptions.IgnoreWidth;
-                if (0 != (info & IgnoreKanaType))
-                    options |= SqlCompareOptions.IgnoreKanaType;
-                if (0 != (info & BinarySort))
-                    options |= SqlCompareOptions.BinarySort;
-                return options;
-            }
-            set
-            {
-                Debug.Assert((value & SqlTypeWorkarounds.SqlStringValidSqlCompareOptionMask) == value, "invalid set_SqlCompareOptions value");
-                uint tmp = 0;
-                if (0 != (value & SqlCompareOptions.IgnoreCase))
-                    tmp |= IgnoreCase;
-                if (0 != (value & SqlCompareOptions.IgnoreNonSpace))
-                    tmp |= IgnoreNonSpace;
-                if (0 != (value & SqlCompareOptions.IgnoreWidth))
-                    tmp |= IgnoreWidth;
-                if (0 != (value & SqlCompareOptions.IgnoreKanaType))
-                    tmp |= IgnoreKanaType;
-                if (0 != (value & SqlCompareOptions.BinarySort))
-                    tmp |= BinarySort;
-                info = (info & MaskLcid) | tmp;
-            }
-        }
-
-
-        internal static bool AreSame(SqlCollation a, SqlCollation b)
-        {
-            if (a == null || b == null)
-            {
-                return a == b;
-            }
-            else
-            {
-                return a.info == b.info && a.sortId == b.sortId;
-            }
-        }
-    }
-
-    internal class RoutingInfo
-    {
-        internal byte Protocol { get; private set; }
-        internal ushort Port { get; private set; }
-        internal string ServerName { get; private set; }
-
-        internal RoutingInfo(byte protocol, ushort port, string servername)
-        {
-            Protocol = protocol;
-            Port = port;
-            ServerName = servername;
-        }
-    }
-
-    internal sealed class SqlEnvChange
-    {
-        internal byte type;
-        internal byte oldLength;
-        internal int newLength; // 7206 TDS changes makes this length an int
-        internal int length;
-        internal string newValue;
-        internal string oldValue;
-        /// <summary>
-        /// contains binary data, before using this field check newBinRented to see if you can take the field array or whether you should allocate and copy
-        /// </summary>
-        internal byte[] newBinValue;
-        /// <summary>
-        /// contains binary data, before using this field check newBinRented to see if you can take the field array or whether you should allocate and copy
-        /// </summary>
-        internal byte[] oldBinValue;
-        internal long newLongValue;
-        internal long oldLongValue;
-        internal SqlCollation newCollation;
-        internal SqlCollation oldCollation;
-        internal RoutingInfo newRoutingInfo;
-        internal bool newBinRented;
-        internal bool oldBinRented;
-
-        internal SqlEnvChange Next;
-
-        internal void Clear()
-        {
-            type = 0;
-            oldLength = 0;
-            newLength = 0;
-            length = 0;
-            newValue = null;
-            oldValue = null;
-            if (newBinValue != null)
-            {
-                Array.Clear(newBinValue, 0, newBinValue.Length);
-                if (newBinRented)
-                {
-                    ArrayPool<byte>.Shared.Return(newBinValue);
-                }
-
-                newBinValue = null;
-            }
-            if (oldBinValue != null)
-            {
-                Array.Clear(oldBinValue, 0, oldBinValue.Length);
-                if (oldBinRented)
-                {
-                    ArrayPool<byte>.Shared.Return(oldBinValue);
-                }
-                oldBinValue = null;
-            }
-            newBinRented = false;
-            oldBinRented = false;
-            newLongValue = 0;
-            oldLongValue = 0;
-            newCollation = null;
-            oldCollation = null;
-            newRoutingInfo = null;
-            Next = null;
-        }
-    }
-
-    internal sealed class SqlLogin
-    {
-        internal int timeout;                                                       // login timeout
-        internal bool userInstance = false;                                   // user instance
-        internal string hostName = "";                                      // client machine name
-        internal string userName = "";                                      // user id
-        internal string password = "";                                      // password
-        internal string applicationName = "";                                      // application name
-        internal string serverName = "";                                      // server name
-        internal string language = "";                                      // initial language
-        internal string database = "";                                      // initial database
-        internal string attachDBFilename = "";                                      // DB filename to be attached
-        internal bool useReplication = false;                                   // user login for replication
-        internal string newPassword = "";                                   // new password for reset password
-        internal bool useSSPI = false;                                   // use integrated security
-        internal int packetSize = SqlConnectionString.DEFAULT.Packet_Size; // packet size
-        internal bool readOnlyIntent = false;                                   // read-only intent
-        internal SqlCredential credential;                                      // user id and password in SecureString
-        internal SecureString newSecurePassword;
-    }
-
-    internal sealed class SqlLoginAck
-    {
-        internal byte majorVersion;
-        internal byte minorVersion;
-        internal short buildNum;
-        internal uint tdsVersion;
-    }
-
-    internal sealed class _SqlMetaData : SqlMetaDataPriv
-    {
-        [Flags]
-        private enum _SqlMetadataFlags : int
-        {
-            None = 0,
-
-            Updatable = 1 << 0,
-            UpdateableUnknown = 1 << 1,
-            IsDifferentName = 1 << 2,
-            IsKey = 1 << 3,
-            IsHidden = 1 << 4,
-            IsExpression = 1 << 5,
-            IsIdentity = 1 << 6,
-            IsColumnSet = 1 << 7,
-
-            IsUpdatableMask = (Updatable | UpdateableUnknown) // two bit field (0 is read only, 1 is updatable, 2 is updatability unknown)
-        }
-
-        internal string column;
-        internal string baseColumn;
-        internal MultiPartTableName multiPartTableName;
-        internal readonly int ordinal;
-        internal byte tableNum;
-        internal byte op;        // for altrow-columns only
-        internal ushort operand; // for altrow-columns only
-        private _SqlMetadataFlags flags;
-
-
-        internal _SqlMetaData(int ordinal) : base()
-        {
-            this.ordinal = ordinal;
-        }
-
-        internal string serverName
-        {
-            get
-            {
-                return multiPartTableName.ServerName;
-            }
-        }
-        internal string catalogName
-        {
-            get
-            {
-                return multiPartTableName.CatalogName;
-            }
-        }
-        internal string schemaName
-        {
-            get
-            {
-                return multiPartTableName.SchemaName;
-            }
-        }
-        internal string tableName
-        {
-            get
-            {
-                return multiPartTableName.TableName;
-            }
-        }
-
-
-        public byte Updatability
-        {
-            get => (byte)(flags & _SqlMetadataFlags.IsUpdatableMask);
-            set => flags = (_SqlMetadataFlags)((value & 0x3) | ((int)flags & ~0x03));
-        }
-
-        public bool IsReadOnly
-        {
-            get => (flags & _SqlMetadataFlags.IsUpdatableMask) == 0;
-        }
-
-        public bool IsDifferentName
-        {
-            get => flags.HasFlag(_SqlMetadataFlags.IsDifferentName);
-            set => Set(_SqlMetadataFlags.IsDifferentName, value);
-        }
-
-        public bool IsKey
-        {
-            get => flags.HasFlag(_SqlMetadataFlags.IsKey);
-            set => Set(_SqlMetadataFlags.IsKey, value);
-        }
-
-        public bool IsHidden
-        {
-            get => flags.HasFlag(_SqlMetadataFlags.IsHidden);
-            set => Set(_SqlMetadataFlags.IsHidden, value);
-        }
-
-        public bool IsExpression
-        {
-            get => flags.HasFlag(_SqlMetadataFlags.IsExpression);
-            set => Set(_SqlMetadataFlags.IsExpression, value);
-        }
-
-        public bool IsIdentity
-        {
-            get => flags.HasFlag(_SqlMetadataFlags.IsIdentity);
-            set => Set(_SqlMetadataFlags.IsIdentity, value);
-        }
-
-        public bool IsColumnSet
-        {
-            get => flags.HasFlag(_SqlMetadataFlags.IsColumnSet);
-            set => Set(_SqlMetadataFlags.IsColumnSet, value);
-        }
-
-        private void Set(_SqlMetadataFlags flag, bool value)
-        {
-            flags = value ? flags | flag : flags & ~flag;
-        }
-
-        internal bool IsNewKatmaiDateTimeType
-        {
-            get
-            {
-                return SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type;
-            }
-        }
-
-        internal bool IsLargeUdt
-        {
-            get
-            {
-                return type == SqlDbType.Udt && length == int.MaxValue;
-            }
-        }
-
-        public object Clone()
-        {
-            _SqlMetaData result = new _SqlMetaData(ordinal);
-            result.CopyFrom(this);
-            result.column = column;
-            result.baseColumn = baseColumn;
-            result.multiPartTableName = multiPartTableName;
-            result.tableNum = tableNum;
-            result.flags = flags;
-            result.op = op;
-            result.operand = operand;
-            return result;
-        }
-    }
-
-    internal sealed class _SqlMetaDataSet
-    {
-        internal ushort id;             // for altrow-columns only
-        internal int[] indexMap;
-        internal int visibleColumns;
-        internal DataTable schemaTable;
-        private readonly _SqlMetaData[] _metaDataArray;
-        internal ReadOnlyCollection<DbColumn> dbColumnSchema;
-
-        internal _SqlMetaDataSet(int count)
-        {
-            _metaDataArray = new _SqlMetaData[count];
-            for (int i = 0; i < _metaDataArray.Length; ++i)
-            {
-                _metaDataArray[i] = new _SqlMetaData(i);
-            }
-        }
-
-        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;
-            if (original._metaDataArray == null)
-            {
-                _metaDataArray = null;
-            }
-            else
-            {
-                _metaDataArray = new _SqlMetaData[original._metaDataArray.Length];
-                for (int idx = 0; idx < _metaDataArray.Length; idx++)
-                {
-                    _metaDataArray[idx] = (_SqlMetaData)original._metaDataArray[idx].Clone();
-                }
-            }
-        }
-
-        internal int Length
-        {
-            get
-            {
-                return _metaDataArray.Length;
-            }
-        }
-
-        internal _SqlMetaData this[int index]
-        {
-            get
-            {
-                return _metaDataArray[index];
-            }
-            set
-            {
-                Debug.Assert(null == value, "used only by SqlBulkCopy");
-                _metaDataArray[index] = value;
-            }
-        }
-
-        public object Clone()
-        {
-            return new _SqlMetaDataSet(this);
-        }
-    }
-
-    internal sealed class _SqlMetaDataSetCollection
-    {
-        private readonly List<_SqlMetaDataSet> _altMetaDataSetArray;
-        internal _SqlMetaDataSet metaDataSet;
-
-        internal _SqlMetaDataSetCollection()
-        {
-            _altMetaDataSetArray = new List<_SqlMetaDataSet>();
-        }
-
-        internal void SetAltMetaData(_SqlMetaDataSet altMetaDataSet)
-        {
-            // If altmetadata with same id is found, override it rather than adding a new one
-            int newId = altMetaDataSet.id;
-            for (int i = 0; i < _altMetaDataSetArray.Count; i++)
-            {
-                if (_altMetaDataSetArray[i].id == newId)
-                {
-                    // override the existing metadata with the same id
-                    _altMetaDataSetArray[i] = altMetaDataSet;
-                    return;
-                }
-            }
-
-            // if we did not find metadata to override, add as new
-            _altMetaDataSetArray.Add(altMetaDataSet);
-        }
-
-        internal _SqlMetaDataSet GetAltMetaData(int id)
-        {
-            foreach (_SqlMetaDataSet altMetaDataSet in _altMetaDataSetArray)
-            {
-                if (altMetaDataSet.id == id)
-                {
-                    return altMetaDataSet;
-                }
-            }
-            Debug.Fail("Can't match up altMetaDataSet with given id");
-            return null;
-        }
-
-        public object Clone()
-        {
-            _SqlMetaDataSetCollection result = new _SqlMetaDataSetCollection();
-            result.metaDataSet = metaDataSet == null ? null : (_SqlMetaDataSet)metaDataSet.Clone();
-            foreach (_SqlMetaDataSet set in _altMetaDataSetArray)
-            {
-                result._altMetaDataSetArray.Add((_SqlMetaDataSet)set.Clone());
-            }
-            return result;
-        }
-    }
-
-    internal class SqlMetaDataPriv
-    {
-        [Flags]
-        private enum SqlMetaDataPrivFlags : byte
-        {
-            None = 0,
-            IsNullable = 1 << 1,
-            IsMultiValued = 1 << 2
-        }
-
-        internal SqlDbType type;    // SqlDbType enum value
-        internal byte tdsType; // underlying tds type
-        internal byte precision = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
-        internal byte scale = TdsEnums.UNKNOWN_PRECISION_SCALE; // give default of unknown (-1)
-        private SqlMetaDataPrivFlags flags;
-        internal int length;
-        internal SqlCollation collation;
-        internal int codePage;
-        internal Encoding encoding;
-        internal MetaType metaType; // cached metaType
-        public SqlMetaDataUdt udt;
-        public SqlMetaDataXmlSchemaCollection xmlSchemaCollection;
-
-        internal SqlMetaDataPriv()
-        {
-        }
-
-        public bool IsNullable
-        {
-            get => flags.HasFlag(SqlMetaDataPrivFlags.IsNullable);
-            set => Set(SqlMetaDataPrivFlags.IsNullable, value);
-        }
-
-        public bool IsMultiValued
-        {
-            get => flags.HasFlag(SqlMetaDataPrivFlags.IsMultiValued);
-            set => Set(SqlMetaDataPrivFlags.IsMultiValued, value);
-        }
-
-        private void Set(SqlMetaDataPrivFlags flag, bool value)
-        {
-            flags = value ? flags | flag : flags & ~flag;
-        }
-
-        internal virtual void CopyFrom(SqlMetaDataPriv original)
-        {
-            this.type = original.type;
-            this.tdsType = original.tdsType;
-            this.precision = original.precision;
-            this.scale = original.scale;
-            this.length = original.length;
-            this.collation = original.collation;
-            this.codePage = original.codePage;
-            this.encoding = original.encoding;
-            this.metaType = original.metaType;
-            this.flags = original.flags;
-
-            if (original.udt != null)
-            {
-                udt = new SqlMetaDataUdt();
-                udt.CopyFrom(original.udt);
-            }
-
-            if (original.xmlSchemaCollection != null)
-            {
-                xmlSchemaCollection = new SqlMetaDataXmlSchemaCollection();
-                xmlSchemaCollection.CopyFrom(original.xmlSchemaCollection);
-            }
-        }
-    }
-
-    internal sealed class SqlMetaDataXmlSchemaCollection
-    {
-        internal string Database;
-        internal string OwningSchema;
-        internal string Name;
-
-        public void CopyFrom(SqlMetaDataXmlSchemaCollection original)
-        {
-            if (original != null)
-            {
-                Database = original.Database;
-                OwningSchema = original.OwningSchema;
-                Name = original.Name;
-            }
-        }
-    }
-
-    internal sealed class SqlMetaDataUdt
-    {
-        internal Type Type;
-        internal string DatabaseName;
-        internal string SchemaName;
-        internal string TypeName;
-        internal string AssemblyQualifiedName;
-
-        public void CopyFrom(SqlMetaDataUdt original)
-        {
-            if (original != null)
-            {
-                Type = original.Type;
-                DatabaseName = original.DatabaseName;
-                SchemaName = original.SchemaName;
-                TypeName = original.TypeName;
-                AssemblyQualifiedName = original.AssemblyQualifiedName;
-            }
-        }
-    }
-
-    internal sealed class _SqlRPC
-    {
-        internal string rpcName;
-        internal ushort ProcID;       // Used instead of name
-        internal ushort options;
-
-        internal SqlParameter[] systemParams;
-        internal byte[] systemParamOptions;
-        internal int systemParamCount;
-
-        internal SqlParameterCollection userParams;
-        internal long[] userParamMap;
-        internal int userParamCount;
-
-        internal int? recordsAffected;
-        internal int cumulativeRecordsAffected;
-
-        internal int errorsIndexStart;
-        internal int errorsIndexEnd;
-        internal SqlErrorCollection errors;
-
-        internal int warningsIndexStart;
-        internal int warningsIndexEnd;
-        internal SqlErrorCollection warnings;
-
-        internal SqlParameter GetParameterByIndex(int index, out byte options)
-        {
-            options = 0;
-            SqlParameter retval = null;
-            if (index < systemParamCount)
-            {
-                retval = systemParams[index];
-                options = systemParamOptions[index];
-            }
-            else
-            {
-                long data = userParamMap[index - systemParamCount];
-                int paramIndex = (int)(data & int.MaxValue);
-                options = (byte)((data >> 32) & 0xFF);
-                retval = userParams[paramIndex];
-            }
-            return retval;
-        }
-    }
-
-    internal sealed class SqlReturnValue : SqlMetaDataPriv
-    {
-        internal string parameter;
-        internal readonly SqlBuffer value;
-
-        internal SqlReturnValue() : base()
-        {
-            value = new SqlBuffer();
-        }
-    }
-
-    internal struct MultiPartTableName
-    {
-        private string _multipartName;
-        private string _serverName;
-        private string _catalogName;
-        private string _schemaName;
-        private string _tableName;
-
-        internal MultiPartTableName(string[] parts)
-        {
-            _multipartName = null;
-            _serverName = parts[0];
-            _catalogName = parts[1];
-            _schemaName = parts[2];
-            _tableName = parts[3];
-        }
-
-        internal MultiPartTableName(string multipartName)
-        {
-            _multipartName = multipartName;
-            _serverName = null;
-            _catalogName = null;
-            _schemaName = null;
-            _tableName = null;
-        }
-
-        internal string ServerName
-        {
-            get
-            {
-                ParseMultipartName();
-                return _serverName;
-            }
-            set { _serverName = value; }
-        }
-        internal string CatalogName
-        {
-            get
-            {
-                ParseMultipartName();
-                return _catalogName;
-            }
-            set { _catalogName = value; }
-        }
-        internal string SchemaName
-        {
-            get
-            {
-                ParseMultipartName();
-                return _schemaName;
-            }
-            set { _schemaName = value; }
-        }
-        internal string TableName
-        {
-            get
-            {
-                ParseMultipartName();
-                return _tableName;
-            }
-            set { _tableName = value; }
-        }
-
-        private void ParseMultipartName()
-        {
-            if (null != _multipartName)
-            {
-                string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", SR.SQL_TDSParserTableName, false);
-                _serverName = parts[0];
-                _catalogName = parts[1];
-                _schemaName = parts[2];
-                _tableName = parts[3];
-                _multipartName = null;
-            }
-        }
-
-        internal static readonly MultiPartTableName Null = new MultiPartTableName(new string[] { null, null, null, null });
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserSafeHandles.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserSafeHandles.cs
deleted file mode 100644 (file)
index e39ec70..0000000
+++ /dev/null
@@ -1,299 +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.Generic;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-
-namespace System.Data.SqlClient
-{
-    internal sealed partial class SNILoadHandle : SafeHandle
-    {
-        internal static readonly SNILoadHandle SingletonInstance = new SNILoadHandle();
-
-        internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate ReadAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(ReadDispatcher);
-        internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate WriteAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(WriteDispatcher);
-
-        private readonly uint _sniStatus = TdsEnums.SNI_UNINITIALIZED;
-        private readonly EncryptionOptions _encryptionOption;
-
-        private SNILoadHandle() : base(IntPtr.Zero, true)
-        {
-            // From security review - SafeHandle guarantees this is only called once.
-            // The reason for the safehandle is guaranteed initialization and termination of SNI to
-            // ensure SNI terminates and cleans up properly.
-            try { }
-            finally
-            {
-                _sniStatus = SNINativeMethodWrapper.SNIInitialize();
-
-                uint value = 0;
-
-                // VSDevDiv 479597: If initialize fails, don't call QueryInfo.
-                if (TdsEnums.SNI_SUCCESS == _sniStatus)
-                {
-                    // Query OS to find out whether encryption is supported.
-                    SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value);
-                }
-
-                _encryptionOption = (value == 0) ? EncryptionOptions.NOT_SUP : EncryptionOptions.OFF;
-
-                base.handle = (IntPtr)1; // Initialize to non-zero dummy variable.
-            }
-        }
-
-        public override bool IsInvalid
-        {
-            get
-            {
-                return (IntPtr.Zero == base.handle);
-            }
-        }
-
-        protected override bool ReleaseHandle()
-        {
-            if (base.handle != IntPtr.Zero)
-            {
-                if (TdsEnums.SNI_SUCCESS == _sniStatus)
-                {
-                    LocalDBAPI.ReleaseDLLHandles();
-                    SNINativeMethodWrapper.SNITerminate();
-                }
-                base.handle = IntPtr.Zero;
-            }
-
-            return true;
-        }
-
-        public uint Status
-        {
-            get
-            {
-                return _sniStatus;
-            }
-        }
-
-        public EncryptionOptions Options
-        {
-            get
-            {
-                return _encryptionOption;
-            }
-        }
-
-        private static void ReadDispatcher(IntPtr key, IntPtr packet, uint error)
-        {
-            // This is the app-domain dispatcher for all async read callbacks, It
-            // simply gets the state object from the key that it is passed, and
-            // calls the state object's read callback.
-            Debug.Assert(IntPtr.Zero != key, "no key passed to read callback dispatcher?");
-            if (IntPtr.Zero != key)
-            {
-                // NOTE: we will get a null ref here if we don't get a key that
-                //       contains a GCHandle to TDSParserStateObject; that is
-                //       very bad, and we want that to occur so we can catch it.
-                GCHandle gcHandle = (GCHandle)key;
-                TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
-
-                if (null != stateObj)
-                {
-                    stateObj.ReadAsyncCallback(IntPtr.Zero, PacketHandle.FromNativePointer(packet), error);
-                }
-            }
-        }
-
-        private static void WriteDispatcher(IntPtr key, IntPtr packet, uint error)
-        {
-            // This is the app-domain dispatcher for all async write callbacks, It
-            // simply gets the state object from the key that it is passed, and
-            // calls the state object's write callback.
-            Debug.Assert(IntPtr.Zero != key, "no key passed to write callback dispatcher?");
-            if (IntPtr.Zero != key)
-            {
-                // NOTE: we will get a null ref here if we don't get a key that
-                //       contains a GCHandle to TDSParserStateObject; that is
-                //       very bad, and we want that to occur so we can catch it.
-                GCHandle gcHandle = (GCHandle)key;
-                TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
-
-                if (null != stateObj)
-                {
-                    stateObj.WriteAsyncCallback(IntPtr.Zero, PacketHandle.FromNativePointer(packet), error);
-                }
-            }
-        }
-    }
-
-    internal sealed class SNIHandle : SafeHandle
-    {
-        private readonly uint _status = TdsEnums.SNI_UNINITIALIZED;
-        private readonly bool _fSync = false;
-
-        // creates a physical connection
-        internal SNIHandle(
-            SNINativeMethodWrapper.ConsumerInfo myInfo,
-            string serverName,
-            byte[] spnBuffer,
-            bool ignoreSniOpenTimeout,
-            int timeout,
-            out byte[] instanceName,
-            bool flushCache,
-            bool fSync,
-            bool fParallel)
-            : base(IntPtr.Zero, true)
-        {
-            try { }
-            finally
-            {
-                _fSync = fSync;
-                instanceName = new byte[256]; // Size as specified by netlibs.
-                if (ignoreSniOpenTimeout)
-                {
-                    timeout = Timeout.Infinite; // -1 == native SNIOPEN_TIMEOUT_VALUE / INFINITE
-                }
-
-                _status = SNINativeMethodWrapper.SNIOpenSyncEx(myInfo, serverName, ref base.handle,
-                            spnBuffer, instanceName, flushCache, fSync, timeout, fParallel);
-            }
-        }
-
-        // constructs SNI Handle for MARS session
-        internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true)
-        {
-            try { }
-            finally
-            {
-                _status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync);
-            }
-        }
-
-        public override bool IsInvalid
-        {
-            get
-            {
-                return (IntPtr.Zero == base.handle);
-            }
-        }
-
-        protected override bool ReleaseHandle()
-        {
-            // NOTE: The SafeHandle class guarantees this will be called exactly once.
-            IntPtr ptr = base.handle;
-            base.handle = IntPtr.Zero;
-            if (IntPtr.Zero != ptr)
-            {
-                if (0 != SNINativeMethodWrapper.SNIClose(ptr))
-                {
-                    return false;   // SNIClose should never fail.
-                }
-            }
-            return true;
-        }
-
-        internal uint Status
-        {
-            get
-            {
-                return _status;
-            }
-        }
-    }
-
-    internal sealed class SNIPacket : SafeHandle
-    {
-        internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true)
-        {
-            SNINativeMethodWrapper.SNIPacketAllocate(sniHandle, SNINativeMethodWrapper.IOType.WRITE, ref base.handle);
-            if (IntPtr.Zero == base.handle)
-            {
-                throw SQL.SNIPacketAllocationFailure();
-            }
-        }
-
-        public override bool IsInvalid
-        {
-            get
-            {
-                return (IntPtr.Zero == base.handle);
-            }
-        }
-
-        protected override bool ReleaseHandle()
-        {
-            // NOTE: The SafeHandle class guarantees this will be called exactly once.
-            IntPtr ptr = base.handle;
-            base.handle = IntPtr.Zero;
-            if (IntPtr.Zero != ptr)
-            {
-                SNINativeMethodWrapper.SNIPacketRelease(ptr);
-            }
-            return true;
-        }
-    }
-
-    internal sealed class WritePacketCache : IDisposable
-    {
-        private bool _disposed;
-        private readonly Stack<SNIPacket> _packets;
-
-        public WritePacketCache()
-        {
-            _disposed = false;
-            _packets = new Stack<SNIPacket>();
-        }
-
-        public SNIPacket Take(SNIHandle sniHandle)
-        {
-            SNIPacket packet;
-            if (_packets.Count > 0)
-            {
-                // Success - reset the packet
-                packet = _packets.Pop();
-                SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
-            }
-            else
-            {
-                // Failed to take a packet - create a new one
-                packet = new SNIPacket(sniHandle);
-            }
-            return packet;
-        }
-
-        public void Add(SNIPacket packet)
-        {
-            if (!_disposed)
-            {
-                _packets.Push(packet);
-            }
-            else
-            {
-                // If we're disposed, then get rid of any packets added to us
-                packet.Dispose();
-            }
-        }
-
-        public void Clear()
-        {
-            while (_packets.Count > 0)
-            {
-                _packets.Pop().Dispose();
-            }
-        }
-
-        public void Dispose()
-        {
-            if (!_disposed)
-            {
-                _disposed = true;
-                Clear();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserSessionPool.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserSessionPool.cs
deleted file mode 100644 (file)
index a022677..0000000
+++ /dev/null
@@ -1,198 +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.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient
-{
-    internal class TdsParserSessionPool
-    {
-        // NOTE: This is a very simplistic, lightweight pooler.  It wasn't
-        //       intended to handle huge number of items, just to keep track
-        //       of the session objects to ensure that they're cleaned up in
-        //       a timely manner, to avoid holding on to an unacceptable
-        //       amount of server-side resources in the event that consumers
-        //       let their data readers be GC'd, instead of explicitly
-        //       closing or disposing of them
-
-        private const int MaxInactiveCount = 10; // pick something, preferably small...
-
-
-        private readonly TdsParser _parser;       // parser that owns us
-        private readonly List<TdsParserStateObject> _cache;        // collection of all known sessions
-        private int _cachedCount;  // lock-free _cache.Count
-        private TdsParserStateObject[] _freeStateObjects; // collection of all sessions available for reuse
-        private int _freeStateObjectCount; // Number of available free sessions
-
-        internal TdsParserSessionPool(TdsParser parser)
-        {
-            _parser = parser;
-            _cache = new List<TdsParserStateObject>();
-            _freeStateObjects = new TdsParserStateObject[MaxInactiveCount];
-            _freeStateObjectCount = 0;
-        }
-
-        private bool IsDisposed
-        {
-            get
-            {
-                return (null == _freeStateObjects);
-            }
-        }
-
-
-        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.
-
-            lock (_cache)
-            {
-                // NOTE: The PutSession call below may choose to remove the
-                //       session from the cache, which will throw off our
-                //       enumerator.  We avoid that by simply indexing backward
-                //       through the array.
-
-                for (int i = _cache.Count - 1; i >= 0; i--)
-                {
-                    TdsParserStateObject session = _cache[i];
-
-                    if (null != session)
-                    {
-                        if (session.IsOrphaned)
-                        {
-                            // TODO: consider adding a performance counter for the number of sessions we reclaim
-
-
-                            PutSession(session);
-                        }
-                    }
-                }
-                // TODO: re-enable this assert when the connection isn't doomed.
-                //Debug.Assert (_cachedCount < MaxInactiveCount, "non-orphaned connection past initial allocation?");
-            }
-        }
-
-        internal void Dispose()
-        {
-            lock (_cache)
-            {
-                // Dispose free sessions
-                for (int i = 0; i < _freeStateObjectCount; i++)
-                {
-                    if (_freeStateObjects[i] != null)
-                    {
-                        _freeStateObjects[i].Dispose();
-                    }
-                }
-                _freeStateObjects = null;
-                _freeStateObjectCount = 0;
-
-                // Dispose orphaned sessions
-                for (int i = 0; i < _cache.Count; i++)
-                {
-                    if (_cache[i] != null)
-                    {
-                        if (_cache[i].IsOrphaned)
-                        {
-                            _cache[i].Dispose();
-                        }
-                        else
-                        {
-                            // Remove the "initial" callback (this will allow the stateObj to be GC collected if need be)
-                            _cache[i].DecrementPendingCallbacks(false);
-                        }
-                    }
-                }
-                _cache.Clear();
-                _cachedCount = 0;
-                // Any active sessions will take care of themselves
-                // (It's too dangerous to dispose them, as this can cause AVs)
-            }
-        }
-
-        internal TdsParserStateObject GetSession(object owner)
-        {
-            TdsParserStateObject session;
-            lock (_cache)
-            {
-                if (IsDisposed)
-                {
-                    throw ADP.ClosedConnectionError();
-                }
-                else if (_freeStateObjectCount > 0)
-                {
-                    // Free state object - grab it
-                    _freeStateObjectCount--;
-                    session = _freeStateObjects[_freeStateObjectCount];
-                    _freeStateObjects[_freeStateObjectCount] = null;
-                    Debug.Assert(session != null, "There was a null session in the free session list?");
-                }
-                else
-                {
-                    // No free objects, create a new one
-                    session = _parser.CreateSession();
-
-
-                    _cache.Add(session);
-                    _cachedCount = _cache.Count;
-                }
-
-                session.Activate(owner);
-            }
-
-
-            return session;
-        }
-
-        internal void PutSession(TdsParserStateObject session)
-        {
-            Debug.Assert(null != session, "null session?");
-            //Debug.Assert(null != session.Owner, "session without owner?");
-
-            bool okToReuse = session.Deactivate();
-
-            lock (_cache)
-            {
-                if (IsDisposed)
-                {
-                    // We're diposed - just clean out the session
-                    Debug.Assert(_cachedCount == 0, "SessionPool is disposed, but there are still sessions in the cache?");
-                    session.Dispose();
-                }
-                else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount))
-                {
-                    // Session is good to re-use and our cache has space
-                    Debug.Assert(!session._pendingData, "pending data on a pooled session?");
-
-                    _freeStateObjects[_freeStateObjectCount] = session;
-                    _freeStateObjectCount++;
-                }
-                else
-                {
-                    // Either the session is bad, or we have no cache space - so dispose the session and remove it
-
-                    bool removed = _cache.Remove(session);
-                    Debug.Assert(removed, "session not in pool?");
-                    _cachedCount = _cache.Count;
-                    session.Dispose();
-                }
-
-                session.RemoveOwner();
-            }
-        }
-
-
-        internal int ActiveSessionsCount
-        {
-            get
-            {
-                return _cachedCount - _freeStateObjectCount;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObject.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObject.cs
deleted file mode 100644 (file)
index 284a404..0000000
+++ /dev/null
@@ -1,4046 +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.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Text;
-using System.Security;
-using System.Runtime.InteropServices;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class LastIOTimer
-    {
-        internal long _value;
-    }
-
-    internal abstract class TdsParserStateObject
-    {
-        private const int AttentionTimeoutSeconds = 5;
-
-        // Ticks to consider a connection "good" after a successful I/O (10,000 ticks = 1 ms)
-        // The resolution of the timer is typically in the range 10 to 16 milliseconds according to msdn.
-        // We choose a value that is smaller than the likely timer resolution, but
-        // large enough to ensure that check connection execution will be 0.1% or less
-        // of very small open, query, close loops.
-        private const long CheckConnectionWindow = 50000;
-
-
-        protected readonly TdsParser _parser;                            // TdsParser pointer
-        private readonly WeakReference _owner = new WeakReference(null);   // the owner of this session, used to track when it's been orphaned
-        internal SqlDataReader.SharedState _readerState;                    // susbset of SqlDataReader state (if it is the owner) necessary for parsing abandoned results in TDS
-        private int _activateCount;                     // 0 when we're in the pool, 1 when we're not, all others are an error
-
-        // Two buffers exist in tdsparser, an in buffer and an out buffer.  For the out buffer, only
-        // one bookkeeping variable is needed, the number of bytes used in the buffer.  For the in buffer,
-        // three variables are actually needed.  First, we need to record from the netlib how many bytes it
-        // read from the netlib, this variable is _inBytesRead.  Then, we need to also keep track of how many
-        // bytes we have used as we consume the bytes from the buffer, that variable is _inBytesUsed.  Third,
-        // we need to keep track of how many bytes are left in the packet, so that we know when we have reached
-        // the end of the packet and so we need to consume the next header.  That variable is _inBytesPacket.
-
-        // Header length constants
-        internal readonly int _inputHeaderLen = TdsEnums.HEADER_LEN;
-        internal readonly int _outputHeaderLen = TdsEnums.HEADER_LEN;
-
-        // Out buffer variables
-        internal byte[] _outBuff;                                     // internal write buffer - initialize on login
-        internal int _outBytesUsed = TdsEnums.HEADER_LEN; // number of bytes used in internal write buffer -
-                                                          // - initialize past header
-                                                          // In buffer variables
-        protected byte[] _inBuff;                         // internal read buffer - initialize on login
-        internal int _inBytesUsed = 0;                   // number of bytes used in internal read buffer
-        internal int _inBytesRead = 0;                   // number of bytes read into internal read buffer
-
-        internal int _inBytesPacket = 0;                   // number of bytes left in packet
-
-        // Packet state variables
-        internal byte _outputMessageType = 0;                   // tds header type
-        internal byte _messageStatus;                               // tds header status
-        internal byte _outputPacketNumber = 1;                   // number of packets sent to server in message - start at 1 per ramas
-        internal uint _outputPacketCount;
-        internal bool _pendingData = false;
-        internal volatile bool _fResetEventOwned = false;               // ResetEvent serializing call to sp_reset_connection
-        internal volatile bool _fResetConnectionSent = false;               // For multiple packet execute
-
-        internal bool _errorTokenReceived = false;               // Keep track of whether an error was received for the result.
-                                                                 // This is reset upon each done token - there can be
-
-        internal bool _bulkCopyOpperationInProgress = false;        // Set to true during bulk copy and used to turn toggle write timeouts.
-        internal bool _bulkCopyWriteTimeout = false;                // Set to trun when _bulkCopyOpeperationInProgress is trun and write timeout happens
-
-        // SNI variables                                                     // multiple resultsets in one batch.
-
-        protected readonly object _writePacketLockObject = new object();        // Used to synchronize access to _writePacketCache and _pendingWritePackets
-
-        // Async variables
-        private int _pendingCallbacks;                            // we increment this before each async read/write call and decrement it in the callback.  We use this to determine when to release the GcHandle...
-
-        // Timeout variables
-        private long _timeoutMilliseconds;
-        private long _timeoutTime;                                 // variable used for timeout computations, holds the value of the hi-res performance counter at which this request should expire
-        internal volatile bool _attentionSent = false;               // true if we sent an Attention to the server
-        internal bool _attentionReceived = false;               // NOTE: Received is not volatile as it is only ever accessed\modified by TryRun its callees (i.e. single threaded access)
-        internal volatile bool _attentionSending = false;
-        internal bool _internalTimeout = false;               // an internal timeout occurred
-
-        private readonly LastIOTimer _lastSuccessfulIOTimer;
-
-        // secure password information to be stored
-        //  At maximum number of secure string that need to be stored is two; one for login password and the other for new change password
-        private readonly SecureString[] _securePasswords = new SecureString[2] { null, null };
-        private readonly int[] _securePasswordOffsetsInBuffer = new int[2];
-
-        // This variable is used to track whether another thread has requested a cancel.  The
-        // synchronization points are
-        //   On the user's execute thread:
-        //     1) the first packet write
-        //     2) session close - return this stateObj to the session pool
-        //   On cancel thread we only have the cancel call.
-        // Currently all access to this variable is inside a lock, The state diagram is:
-        // 1) pre first packet write, if cancel is requested, set variable so exception is triggered
-        //    on user thread when first packet write is attempted
-        // 2) post first packet write, but before session return - a call to cancel will send an
-        //    attention to the server
-        // 3) post session close - no attention is allowed
-        private bool _cancelled;
-        private const int _waitForCancellationLockPollTimeout = 100;
-        private readonly WeakReference _cancellationOwner = new WeakReference(null);
-
-        internal bool _hasOpenResult = false;
-        // Cache the transaction for which this command was executed so upon completion we can
-        // decrement the appropriate result count.
-        internal SqlInternalTransaction _executedUnderTransaction = null;
-
-        // TDS stream processing variables
-        internal ulong _longlen;                                     // plp data length indicator
-        internal ulong _longlenleft;                                 // Length of data left to read (64 bit lengths)
-        internal int[] _decimalBits = null;                // scratch buffer for decimal/numeric data
-        internal byte[] _bTmp = new byte[TdsEnums.YUKON_HEADER_LEN];  // Scratch buffer for misc use
-        internal int _bTmpRead = 0;                   // Counter for number of temporary bytes read
-        internal Decoder _plpdecoder = null;             // Decoder object to process plp character data
-        internal bool _accumulateInfoEvents = false;               // TRUE - accumulate info messages during TdsParser.Run, FALSE - fire them
-        internal List<SqlError> _pendingInfoEvents = null;
-
-        //
-        // DO NOT USE THIS BUFFER FOR OTHER THINGS.
-        // ProcessHeader can be called ANYTIME while doing network reads.
-        private readonly byte[] _partialHeaderBuffer = new byte[TdsEnums.HEADER_LEN];   // Scratch buffer for ProcessHeader
-        internal int _partialHeaderBytesRead = 0;
-
-        internal _SqlMetaDataSet _cleanupMetaData = null;
-        internal _SqlMetaDataSetCollection _cleanupAltMetaDataSetArray = null;
-
-
-        internal bool _receivedColMetaData;      // Used to keep track of when to fire StatementCompleted  event.
-
-        private SniContext _sniContext = SniContext.Undefined;
-#if DEBUG
-        private SniContext _debugOnlyCopyOfSniContext = SniContext.Undefined;
-#endif
-
-        private bool _bcpLock = false;
-
-        // Null bitmap compression (NBC) information for the current row
-        private NullBitmap _nullBitmapInfo;
-
-        // Async
-        internal TaskCompletionSource<object> _networkPacketTaskSource;
-        private Timer _networkPacketTimeout;
-        internal bool _syncOverAsync = true;
-        private bool _snapshotReplay = false;
-        private StateSnapshot _snapshot;
-        internal ExecutionContext _executionContext;
-        internal bool _asyncReadWithoutSnapshot = false;
-#if DEBUG
-        // Used to override the assert than ensures that the stacktraces on subsequent replays are the same
-        // This is useful is you are purposefully running the replay from a different thread (e.g. during SqlDataReader.Close)
-        internal bool _permitReplayStackTraceToDiffer = false;
-
-        // Used to indicate that the higher level object believes that this stateObj has enough data to complete an operation
-        // If this stateObj has to read, then it will raise an assert
-        internal bool _shouldHaveEnoughData = false;
-#endif
-
-        // local exceptions to cache warnings and errors
-        internal SqlErrorCollection _errors;
-        internal SqlErrorCollection _warnings;
-        internal object _errorAndWarningsLock = new object();
-        private bool _hasErrorOrWarning = false;
-
-        // local exceptions to cache warnings and errors that occurred prior to sending attention
-        internal SqlErrorCollection _preAttentionErrors;
-        internal SqlErrorCollection _preAttentionWarnings;
-
-        private volatile TaskCompletionSource<object> _writeCompletionSource = null;
-        protected volatile int _asyncWriteCount = 0;
-        private volatile Exception _delayedWriteAsyncCallbackException = null; // set by write async callback if completion source is not yet created
-
-        // _readingcount is incremented when we are about to read.
-        // We check the parser state afterwards.
-        // When the read is completed, we decrement it before handling errors
-        // as the error handling may end up calling Dispose.
-        private int _readingCount;
-
-        // Test hooks
-#if DEBUG
-        // This is a test hook to enable testing of the retry paths.
-        // When set to true, almost every possible retry point will be attempted.
-        // This will drastically impact performance.
-        //
-        // Sample code to enable:
-        //
-        //    Type type = typeof(SqlDataReader).Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
-        //    System.Reflection.FieldInfo field = type.GetField("_forceAllPends", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
-        //    if (field != null) {
-        //        field.SetValue(null, true);
-        //    }
-        //
-        internal static bool _forceAllPends = false;
-
-        // set this while making a call that should not block.
-        // instead of blocking it will fail.
-        internal static bool _failAsyncPends = false;
-
-        // If this is set and an async read is made, then
-        // we will switch to syncOverAsync mode for the
-        // remainder of the async operation.
-        internal static bool _forceSyncOverAsyncAfterFirstPend = false;
-
-        // Requests to send attention will be ignored when _skipSendAttention is true.
-        // This is useful to simulate circumstances where timeouts do not recover.
-        internal static bool _skipSendAttention = false;
-
-        // Prevents any pending read from completing until the user signals it using
-        // CompletePendingReadWithSuccess() or CompletePendingReadWithFailure(int errorCode) in SqlCommand\SqlDataReader
-        internal static bool _forcePendingReadsToWaitForUser;
-        internal TaskCompletionSource<object> _realNetworkPacketTaskSource = null;
-
-        // Field is never assigned to, and will always have its default value
-#pragma warning disable 0649
-        // Set to true to enable checking the call stacks match when packet retry occurs.
-        internal static bool _checkNetworkPacketRetryStacks;
-#pragma warning restore 0649
-#endif
-
-        //////////////////
-        // Constructors //
-        //////////////////
-
-        internal TdsParserStateObject(TdsParser parser)
-        {
-            // Construct a physical connection
-            Debug.Assert(null != parser, "no parser?");
-            _parser = parser;
-
-            // For physical connection, initialize to default login packet size.
-            SetPacketSize(TdsEnums.DEFAULT_LOGIN_PACKET_SIZE);
-
-            // we post a callback that represents the call to dispose; once the
-            // object is disposed, the next callback will cause the GC Handle to
-            // be released.
-            IncrementPendingCallbacks();
-            _lastSuccessfulIOTimer = new LastIOTimer();
-        }
-
-        internal TdsParserStateObject(TdsParser parser, TdsParserStateObject physicalConnection, bool async)
-        {
-            // Construct a MARS session
-            Debug.Assert(null != parser, "no parser?");
-            _parser = parser;
-            SniContext = SniContext.Snix_GetMarsSession;
-
-            Debug.Assert(null != _parser._physicalStateObj, "no physical session?");
-            Debug.Assert(null != _parser._physicalStateObj._inBuff, "no in buffer?");
-            Debug.Assert(null != _parser._physicalStateObj._outBuff, "no out buffer?");
-            Debug.Assert(_parser._physicalStateObj._outBuff.Length ==
-                         _parser._physicalStateObj._inBuff.Length, "Unexpected unequal buffers.");
-
-            // Determine packet size based on physical connection buffer lengths.
-            SetPacketSize(_parser._physicalStateObj._outBuff.Length);
-
-            CreateSessionHandle(physicalConnection, async);
-
-            if (IsFailedHandle())
-            {
-                AddError(parser.ProcessSNIError(this));
-                ThrowExceptionAndWarning();
-            }
-
-            // we post a callback that represents the call to dispose; once the
-            // object is disposed, the next callback will cause the GC Handle to
-            // be released.
-            IncrementPendingCallbacks();
-            _lastSuccessfulIOTimer = parser._physicalStateObj._lastSuccessfulIOTimer;
-        }
-
-        ////////////////
-        // Properties //
-        ////////////////
-
-        // BcpLock - use to lock this object if there is a potential risk of using this object
-        // between tds packets
-        internal bool BcpLock
-        {
-            get
-            {
-                return _bcpLock;
-            }
-            set
-            {
-                _bcpLock = value;
-            }
-        }
-
-#if DEBUG
-        internal SniContext DebugOnlyCopyOfSniContext
-        {
-            get
-            {
-                return _debugOnlyCopyOfSniContext;
-            }
-        }
-#endif
-
-        internal bool HasOpenResult
-        {
-            get
-            {
-                return _hasOpenResult;
-            }
-        }
-
-#if DEBUG
-        internal void InvalidateDebugOnlyCopyOfSniContext()
-        {
-            _debugOnlyCopyOfSniContext = SniContext.Undefined;
-        }
-#endif
-
-        internal bool IsOrphaned
-        {
-            get
-            {
-                Debug.Assert((0 == _activateCount && !_owner.IsAlive) // in pool
-                             || (1 == _activateCount && _owner.IsAlive && _owner.Target != null)
-                             || (1 == _activateCount && !_owner.IsAlive), "Unknown state on TdsParserStateObject.IsOrphaned!");
-                return (0 != _activateCount && !_owner.IsAlive);
-            }
-        }
-
-        internal object Owner
-        {
-            set
-            {
-                Debug.Assert(value == null || !_owner.IsAlive || ((value is SqlDataReader) && (((SqlDataReader)value).Command == _owner.Target)), "Should not be changing the owner of an owned stateObj");
-                SqlDataReader reader = value as SqlDataReader;
-                if (reader == null)
-                {
-                    _readerState = null;
-                }
-                else
-                {
-                    _readerState = reader._sharedState;
-                }
-                _owner.Target = value;
-            }
-        }
-
-        internal abstract uint DisabeSsl();
-
-        internal bool HasOwner
-        {
-            get
-            {
-                return _owner.IsAlive;
-            }
-        }
-
-        internal TdsParser Parser
-        {
-            get
-            {
-                return _parser;
-            }
-        }
-
-        internal abstract uint EnableMars(ref uint info);
-
-        internal SniContext SniContext
-        {
-            get
-            {
-                return _sniContext;
-            }
-            set
-            {
-                _sniContext = value;
-#if DEBUG
-                _debugOnlyCopyOfSniContext = value;
-#endif
-            }
-        }
-
-        internal abstract uint Status
-        {
-            get;
-        }
-
-        internal abstract SessionHandle SessionHandle
-        {
-            get;
-        }
-
-        internal bool TimeoutHasExpired
-        {
-            get
-            {
-                Debug.Assert(0 == _timeoutMilliseconds || 0 == _timeoutTime, "_timeoutTime hasn't been reset");
-                return TdsParserStaticMethods.TimeoutHasExpired(_timeoutTime);
-            }
-        }
-
-        internal long TimeoutTime
-        {
-            get
-            {
-                if (0 != _timeoutMilliseconds)
-                {
-                    _timeoutTime = TdsParserStaticMethods.GetTimeout(_timeoutMilliseconds);
-                    _timeoutMilliseconds = 0;
-                }
-                return _timeoutTime;
-            }
-            set
-            {
-                _timeoutMilliseconds = 0;
-                _timeoutTime = value;
-            }
-        }
-
-        internal int GetTimeoutRemaining()
-        {
-            int remaining;
-            if (0 != _timeoutMilliseconds)
-            {
-                remaining = (int)Math.Min((long)int.MaxValue, _timeoutMilliseconds);
-                _timeoutTime = TdsParserStaticMethods.GetTimeout(_timeoutMilliseconds);
-                _timeoutMilliseconds = 0;
-            }
-            else
-            {
-                remaining = TdsParserStaticMethods.GetTimeoutMilliseconds(_timeoutTime);
-            }
-            return remaining;
-        }
-
-        internal bool TryStartNewRow(bool isNullCompressed, int nullBitmapColumnsCount = 0)
-        {
-            Debug.Assert(!isNullCompressed || nullBitmapColumnsCount > 0, "Null-Compressed row requires columns count");
-
-            if (_snapshot != null)
-            {
-                _snapshot.CloneNullBitmapInfo();
-            }
-
-            // initialize or unset null bitmap information for the current row
-            if (isNullCompressed)
-            {
-                // assert that NBCROW is not in use by Yukon or before
-                Debug.Assert(_parser.IsKatmaiOrNewer, "NBCROW is sent by pre-Katmai server");
-
-                if (!_nullBitmapInfo.TryInitialize(this, nullBitmapColumnsCount))
-                {
-                    return false;
-                }
-            }
-            else
-            {
-                _nullBitmapInfo.Clean();
-            }
-
-            return true;
-        }
-
-        internal bool IsRowTokenReady()
-        {
-            // Removing one byte since TryReadByteArray\TryReadByte will aggressively read the next packet if there is no data left - so we need to ensure there is a spare byte
-            int bytesRemaining = Math.Min(_inBytesPacket, _inBytesRead - _inBytesUsed) - 1;
-
-            if (bytesRemaining > 0)
-            {
-                if (_inBuff[_inBytesUsed] == TdsEnums.SQLROW)
-                {
-                    // At a row token, so we're ready
-                    return true;
-                }
-                else if (_inBuff[_inBytesUsed] == TdsEnums.SQLNBCROW)
-                {
-                    // NBC row token, ensure that we have enough data for the bitmap
-                    // SQLNBCROW + Null Bitmap (copied from NullBitmap.TryInitialize)
-                    int bytesToRead = 1 + (_cleanupMetaData.Length + 7) / 8;
-                    return (bytesToRead <= bytesRemaining);
-                }
-            }
-
-            // No data left, or not at a row token
-            return false;
-        }
-
-        internal bool IsNullCompressionBitSet(int columnOrdinal)
-        {
-            return _nullBitmapInfo.IsGuaranteedNull(columnOrdinal);
-        }
-
-        private struct NullBitmap
-        {
-            private byte[] _nullBitmap;
-            private int _columnsCount; // set to 0 if not used or > 0 for NBC rows
-
-            internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount)
-            {
-                _columnsCount = columnsCount;
-                // 1-8 columns need 1 byte
-                // 9-16: 2 bytes, and so on
-                int bitmapArrayLength = (columnsCount + 7) / 8;
-
-                // allow reuse of previously allocated bitmap
-                if (_nullBitmap == null || _nullBitmap.Length != bitmapArrayLength)
-                {
-                    _nullBitmap = new byte[bitmapArrayLength];
-                }
-
-                // read the null bitmap compression information from TDS
-                if (!stateObj.TryReadByteArray(_nullBitmap, _nullBitmap.Length))
-                {
-                    return false;
-                }
-
-
-                return true;
-            }
-
-            internal bool ReferenceEquals(NullBitmap obj)
-            {
-                return object.ReferenceEquals(_nullBitmap, obj._nullBitmap);
-            }
-
-            internal NullBitmap Clone()
-            {
-                NullBitmap newBitmap = default;
-                newBitmap._nullBitmap = _nullBitmap == null ? null : (byte[])_nullBitmap.Clone();
-                newBitmap._columnsCount = _columnsCount;
-                return newBitmap;
-            }
-
-            internal void Clean()
-            {
-                _columnsCount = 0;
-                // no need to free _nullBitmap array - it is cached for the next row
-            }
-
-            /// <summary>
-            /// If this method returns true, the value is guaranteed to be null. This is not true vice versa:
-            /// if the bitmap value is false (if this method returns false), the value can be either null or non-null - no guarantee in this case.
-            /// To determine whether it is null or not, read it from the TDS (per NBCROW design spec, for IMAGE/TEXT/NTEXT columns server might send
-            /// bitmap = 0, when the actual value is null).
-            /// </summary>
-            internal bool IsGuaranteedNull(int columnOrdinal)
-            {
-                if (_columnsCount == 0)
-                {
-                    // not an NBC row
-                    return false;
-                }
-
-                Debug.Assert(columnOrdinal >= 0 && columnOrdinal < _columnsCount, "Invalid column ordinal");
-
-                byte testBit = (byte)(1 << (columnOrdinal & 0x7)); // columnOrdinal & 0x7 == columnOrdinal MOD 0x7
-                byte testByte = _nullBitmap[columnOrdinal >> 3];
-                return (testBit & testByte) != 0;
-            }
-        }
-
-        /////////////////////
-        // General methods //
-        /////////////////////
-
-        // If this object is part of a TdsParserSessionPool, then this *must* be called inside the pool's lock
-        internal void Activate(object owner)
-        {
-            Debug.Assert(_parser.MARSOn, "Can not activate a non-MARS connection");
-            Owner = owner; // must assign an owner for reclamation to work
-            int result = Interlocked.Increment(ref _activateCount);   // must have non-zero activation count for reclamation to work too.
-            Debug.Assert(result == 1, "invalid deactivate count");
-        }
-
-        // This method is only called by the command or datareader as a result of a user initiated
-        // cancel request.
-        internal void Cancel(object caller)
-        {
-            Debug.Assert(caller != null, "Null caller for Cancel!");
-            Debug.Assert(caller is SqlCommand || caller is SqlDataReader, "Calling API with invalid caller type: " + caller.GetType());
-
-            bool hasLock = false;
-            try
-            {
-                // Keep looping until we either grabbed the lock (and therefore sent attention) or the connection closes\breaks
-                while ((!hasLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
-                {
-                    Monitor.TryEnter(this, _waitForCancellationLockPollTimeout, ref hasLock);
-                    if (hasLock)
-                    { // Lock for the time being - since we need to synchronize the attention send.
-                      // This lock is also protecting against concurrent close and async continuations
-
-                        // Ensure that, once we have the lock, that we are still the owner
-                        if ((!_cancelled) && (_cancellationOwner.Target == caller))
-                        {
-                            _cancelled = true;
-
-                            if (_pendingData && !_attentionSent)
-                            {
-                                bool hasParserLock = false;
-                                // Keep looping until we have the parser lock (and so are allowed to write), or the connection closes\breaks
-                                while ((!hasParserLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
-                                {
-                                    try
-                                    {
-                                        _parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false, timeout: _waitForCancellationLockPollTimeout, lockTaken: ref hasParserLock);
-                                        if (hasParserLock)
-                                        {
-                                            _parser.Connection.ThreadHasParserLockForClose = true;
-                                            SendAttention();
-                                        }
-                                    }
-                                    finally
-                                    {
-                                        if (hasParserLock)
-                                        {
-                                            if (_parser.Connection.ThreadHasParserLockForClose)
-                                            {
-                                                _parser.Connection.ThreadHasParserLockForClose = false;
-                                            }
-                                            _parser.Connection._parserLock.Release();
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                if (hasLock)
-                {
-                    Monitor.Exit(this);
-                }
-            }
-        }
-
-        // CancelRequest - use to cancel while writing a request to the server
-        //
-        // o none of the request might have been sent to the server, simply reset the buffer,
-        //   sending attention does not hurt
-        // o the request was partially written. Send an ignore header to the server. attention is
-        //   required if the server was waiting for data (e.g. insert bulk rows)
-        // o the request was completely written out and the server started to process the request.
-        //   attention is required to have the server stop processing.
-        //
-        internal void CancelRequest()
-        {
-            ResetBuffer();    // clear out unsent buffer
-            // If the first sqlbulkcopy timeout, _outputPacketNumber may not be 1,
-            // the next sqlbulkcopy (same connection string) requires this to be 1, hence reset
-            // it here when exception happens in the first sqlbulkcopy
-            ResetPacketCounters();
-
-            // VSDD#907507, if bulkcopy write timeout happens, it already sent the attention,
-            // so no need to send it again
-            if (!_bulkCopyWriteTimeout)
-            {
-                SendAttention();
-                Parser.ProcessPendingAck(this);
-            }
-        }
-
-        public void CheckSetResetConnectionState(uint error, CallbackType callbackType)
-        {
-            // Should only be called for MARS - that is the only time we need to take
-            // the ResetConnection lock!
-
-            // It was raised in a security review by Microsoft questioning whether
-            // we need to actually process the resulting packet (sp_reset ack or error) to know if the
-            // reset actually succeeded.  There was a concern that if the reset failed and we proceeded
-            // there might be a security issue present.  We have been assured by the server that if
-            // sp_reset fails, they guarantee they will kill the resulting connection.  So - it is
-            // safe for us to simply receive the packet and then consume the pre-login later.
-
-            Debug.Assert(_parser.MARSOn, "Should not be calling CheckSetResetConnectionState on non MARS connection");
-
-            if (_fResetEventOwned)
-            {
-                if (callbackType == CallbackType.Read && TdsEnums.SNI_SUCCESS == error)
-                {
-                    // RESET SUCCEEDED!
-                    // If we are on read callback and no error occurred (and we own reset event) -
-                    // then we sent the sp_reset_connection and so we need to reset sp_reset_connection
-                    // flag to false, and then release the ResetEvent.
-                    _parser._fResetConnection = false;
-                    _fResetConnectionSent = false;
-                    _fResetEventOwned = !_parser._resetConnectionEvent.Set();
-                    Debug.Assert(!_fResetEventOwned, "Invalid AutoResetEvent state!");
-                }
-
-                if (TdsEnums.SNI_SUCCESS != error)
-                {
-                    // RESET FAILED!
-
-                    // If write or read failed with reset, we need to clear event but not mark connection
-                    // as reset.
-                    _fResetConnectionSent = false;
-                    _fResetEventOwned = !_parser._resetConnectionEvent.Set();
-                    Debug.Assert(!_fResetEventOwned, "Invalid AutoResetEvent state!");
-                }
-            }
-        }
-
-        internal void CloseSession()
-        {
-            ResetCancelAndProcessAttention();
-#if DEBUG
-            InvalidateDebugOnlyCopyOfSniContext();
-#endif
-            Parser.PutSession(this);
-        }
-
-        private void ResetCancelAndProcessAttention()
-        {
-            // This method is shared by CloseSession initiated by DataReader.Close or completed
-            // command execution, as well as the session reclamation code for cases where the
-            // DataReader is opened and then GC'ed.
-            lock (this)
-            {
-                // Reset cancel state.
-                _cancelled = false;
-                _cancellationOwner.Target = null;
-
-                if (_attentionSent)
-                {
-                    // Make sure we're cleaning up the AttentionAck if Cancel happened before taking the lock.
-                    // We serialize Cancel/CloseSession to prevent a race condition between these two states.
-                    // The problem is that both sending and receiving attentions are time taking
-                    // operations.
-                    Parser.ProcessPendingAck(this);
-                }
-                _internalTimeout = false;
-            }
-        }
-
-        internal abstract void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool fParallel, bool isIntegratedSecurity = false);
-
-        internal abstract uint SniGetConnectionId(ref Guid clientConnectionId);
-
-        internal abstract bool IsFailedHandle();
-
-        protected abstract void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async);
-
-        protected abstract void FreeGcHandle(int remaining, bool release);
-
-        internal abstract uint EnableSsl(ref uint info);
-
-        internal abstract uint WaitForSSLHandShakeToComplete();
-
-        internal abstract void Dispose();
-
-        internal abstract void DisposePacketCache();
-
-        internal abstract bool IsPacketEmpty(PacketHandle readPacket);
-
-        internal abstract PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error);
-
-        internal abstract PacketHandle ReadAsync(SessionHandle handle, out uint error);
-
-        internal abstract uint CheckConnection();
-
-        internal abstract uint SetConnectionBufferSize(ref uint unsignedPacketSize);
-
-        internal abstract void ReleasePacket(PacketHandle syncReadPacket);
-
-        protected abstract uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize);
-
-        internal abstract PacketHandle GetResetWritePacket(int dataSize);
-
-        internal abstract void ClearAllWritePackets();
-
-        internal abstract PacketHandle AddPacketToPendingList(PacketHandle packet);
-
-        protected abstract void RemovePacketFromPendingList(PacketHandle pointer);
-
-        internal abstract uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer);
-
-        internal bool Deactivate()
-        {
-            bool goodForReuse = false;
-
-            try
-            {
-                TdsParserState state = Parser.State;
-                if (state != TdsParserState.Broken && state != TdsParserState.Closed)
-                {
-                    if (_pendingData)
-                    {
-                        Parser.DrainData(this); // This may throw - taking us to catch block.c
-                    }
-
-                    if (HasOpenResult)
-                    {
-                        DecrementOpenResultCount();
-                    }
-
-                    ResetCancelAndProcessAttention();
-                    goodForReuse = true;
-                }
-            }
-            catch (Exception e)
-            {
-                if (!ADP.IsCatchableExceptionType(e))
-                {
-                    throw;
-                }
-            }
-            return goodForReuse;
-        }
-
-        // If this object is part of a TdsParserSessionPool, then this *must* be called inside the pool's lock
-        internal void RemoveOwner()
-        {
-            if (_parser.MARSOn)
-            {
-                // We only care about the activation count for MARS connections
-                int result = Interlocked.Decrement(ref _activateCount);   // must have non-zero activation count for reclamation to work too.
-                Debug.Assert(result == 0, "invalid deactivate count");
-            }
-            Owner = null;
-        }
-
-        internal void DecrementOpenResultCount()
-        {
-            if (_executedUnderTransaction == null)
-            {
-                // If we were not executed under a transaction - decrement the global count
-                // on the parser.
-                _parser.DecrementNonTransactedOpenResultCount();
-            }
-            else
-            {
-                // If we were executed under a transaction - decrement the count on the transaction.
-                _executedUnderTransaction.DecrementAndObtainOpenResultCount();
-                _executedUnderTransaction = null;
-            }
-            _hasOpenResult = false;
-        }
-
-        internal int DecrementPendingCallbacks(bool release)
-        {
-            int remaining = Interlocked.Decrement(ref _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
-            Debug.Assert((remaining == -1 && SessionHandle.IsNull) || (0 <= remaining && remaining < 3), $"_pendingCallbacks values is invalid after decrementing: {remaining}");
-            return remaining;
-        }
-
-        internal void DisposeCounters()
-        {
-            Timer networkPacketTimeout = _networkPacketTimeout;
-            if (networkPacketTimeout != null)
-            {
-                _networkPacketTimeout = null;
-                networkPacketTimeout.Dispose();
-            }
-
-            Debug.Assert(Volatile.Read(ref _readingCount) >= 0, "_readingCount is negative");
-            if (Volatile.Read(ref _readingCount) > 0)
-            {
-                // if _reading is true, we need to wait for it to complete
-                // if _reading is false, then future read attempts will
-                // already see the null _sessionHandle and abort.
-
-                // We block after nulling _sessionHandle but before disposing it
-                // to give a chance for a read that has already grabbed the
-                // handle to complete.
-                SpinWait.SpinUntil(() => Volatile.Read(ref _readingCount) == 0);
-            }
-        }
-
-        internal int IncrementAndObtainOpenResultCount(SqlInternalTransaction transaction)
-        {
-            _hasOpenResult = true;
-
-            if (transaction == null)
-            {
-                // If we are not passed a transaction, we are not executing under a transaction
-                // and thus we should increment the global connection result count.
-                return _parser.IncrementNonTransactedOpenResultCount();
-            }
-            else
-            {
-                // If we are passed a transaction, we are executing under a transaction
-                // and thus we should increment the transaction's result count.
-                _executedUnderTransaction = transaction;
-                return transaction.IncrementAndObtainOpenResultCount();
-            }
-        }
-
-        internal int IncrementPendingCallbacks()
-        {
-            int remaining = Interlocked.Increment(ref _pendingCallbacks);
-            Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}");
-            return remaining;
-        }
-
-        internal void SetTimeoutSeconds(int timeout)
-        {
-            SetTimeoutMilliseconds((long)timeout * 1000L);
-        }
-
-        internal void SetTimeoutMilliseconds(long timeout)
-        {
-            if (timeout <= 0)
-            {
-                // 0 or less (i.e. Timespan.Infinite) == infinite (which is represented by Int64.MaxValue)
-                _timeoutMilliseconds = 0;
-                _timeoutTime = long.MaxValue;
-            }
-            else
-            {
-                _timeoutMilliseconds = timeout;
-                _timeoutTime = 0;
-            }
-        }
-
-        internal void StartSession(object cancellationOwner)
-        {
-            _cancellationOwner.Target = cancellationOwner;
-        }
-
-        internal void ThrowExceptionAndWarning(bool callerHasConnectionLock = false, bool asyncClose = false)
-        {
-            _parser.ThrowExceptionAndWarning(this, callerHasConnectionLock, asyncClose);
-        }
-
-        ////////////////////////////////////////////
-        // TDS Packet/buffer manipulation methods //
-        ////////////////////////////////////////////
-
-        internal Task ExecuteFlush()
-        {
-            lock (this)
-            {
-                if (_cancelled && 1 == _outputPacketNumber)
-                {
-                    ResetBuffer();
-                    _cancelled = false;
-                    throw SQL.OperationCancelled();
-                }
-                else
-                {
-                    Task writePacketTask = WritePacket(TdsEnums.HARDFLUSH);
-                    if (writePacketTask == null)
-                    {
-                        _pendingData = true;
-                        _messageStatus = 0;
-                        return null;
-                    }
-                    else
-                    {
-                        return AsyncHelper.CreateContinuationTask(writePacketTask, () => { _pendingData = true; _messageStatus = 0; });
-                    }
-                }
-            }
-        }
-
-        // Processes the tds header that is present in the buffer
-        internal bool TryProcessHeader()
-        {
-            Debug.Assert(_inBytesPacket == 0, "there should not be any bytes left in packet when ReadHeader is called");
-
-            // if the header splits buffer reads - special case!
-            if ((_partialHeaderBytesRead > 0) || (_inBytesUsed + _inputHeaderLen > _inBytesRead))
-            {
-                // VSTS 219884: when some kind of MITM (man-in-the-middle) tool splits the network packets, the message header can be split over
-                // several network packets.
-                // Note: cannot use ReadByteArray here since it uses _inBytesPacket which is not set yet.
-                do
-                {
-                    int copy = Math.Min(_inBytesRead - _inBytesUsed, _inputHeaderLen - _partialHeaderBytesRead);
-                    Debug.Assert(copy > 0, "ReadNetworkPacket read empty buffer");
-
-                    Buffer.BlockCopy(_inBuff, _inBytesUsed, _partialHeaderBuffer, _partialHeaderBytesRead, copy);
-                    _partialHeaderBytesRead += copy;
-                    _inBytesUsed += copy;
-
-                    Debug.Assert(_partialHeaderBytesRead <= _inputHeaderLen, "Read more bytes for header than required");
-                    if (_partialHeaderBytesRead == _inputHeaderLen)
-                    {
-                        // All read
-                        _partialHeaderBytesRead = 0;
-                        _inBytesPacket = ((int)_partialHeaderBuffer[TdsEnums.HEADER_LEN_FIELD_OFFSET] << 8 |
-                                  (int)_partialHeaderBuffer[TdsEnums.HEADER_LEN_FIELD_OFFSET + 1]) - _inputHeaderLen;
-
-                        _messageStatus = _partialHeaderBuffer[1];
-                    }
-                    else
-                    {
-                        Debug.Assert(_inBytesUsed == _inBytesRead, "Did not use all data while reading partial header");
-
-                        // Require more data
-                        if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
-                        {
-                            // NOTE: ReadNetworkPacket does nothing if the parser state is closed or broken
-                            // to avoid infinite loop, we raise an exception
-                            ThrowExceptionAndWarning();
-                            return true;
-                        }
-
-                        if (!TryReadNetworkPacket())
-                        {
-                            return false;
-                        }
-
-                        if (_internalTimeout)
-                        {
-                            ThrowExceptionAndWarning();
-                            return true;
-                        }
-                    }
-                } while (_partialHeaderBytesRead != 0); // This is reset to 0 once we have read everything that we need
-
-                AssertValidState();
-            }
-            else
-            {
-                // normal header processing...
-                _messageStatus = _inBuff[_inBytesUsed + 1];
-                _inBytesPacket = ((int)_inBuff[_inBytesUsed + TdsEnums.HEADER_LEN_FIELD_OFFSET] << 8 |
-                                              (int)_inBuff[_inBytesUsed + TdsEnums.HEADER_LEN_FIELD_OFFSET + 1]) - _inputHeaderLen;
-                _inBytesUsed += _inputHeaderLen;
-
-                AssertValidState();
-            }
-
-            if (_inBytesPacket < 0)
-            {
-                // either TDS stream is corrupted or there is multithreaded misuse of connection
-                throw SQL.ParsingError();
-            }
-
-            return true;
-        }
-
-        // This ensure that there is data available to be read in the buffer and that the header has been processed
-        // NOTE: This method (and all it calls) should be retryable without replaying a snapshot
-        internal bool TryPrepareBuffer()
-        {
-            Debug.Assert(_inBuff != null, "packet buffer should not be null!");
-
-            // Header spans packets, or we haven't read the header yet - process header
-            if ((_inBytesPacket == 0) && (_inBytesUsed < _inBytesRead))
-            {
-                if (!TryProcessHeader())
-                {
-                    return false;
-                }
-                Debug.Assert(_inBytesPacket != 0, "_inBytesPacket cannot be 0 after processing header!");
-                AssertValidState();
-            }
-
-            // If we're out of data, need to read more
-            if (_inBytesUsed == _inBytesRead)
-            {
-                // If the _inBytesPacket is not zero, then we have data left in the packet, but the data in the packet
-                // spans the buffer, so we can read any amount of data possible, and we do not need to call ProcessHeader
-                // because there isn't a header at the beginning of the data that we are reading.
-                if (_inBytesPacket > 0)
-                {
-                    if (!TryReadNetworkPacket())
-                    {
-                        return false;
-                    }
-                }
-                else if (_inBytesPacket == 0)
-                {
-                    // Else we have finished the packet and so we must read as much data as possible
-                    if (!TryReadNetworkPacket())
-                    {
-                        return false;
-                    }
-
-                    if (!TryProcessHeader())
-                    {
-                        return false;
-                    }
-
-                    Debug.Assert(_inBytesPacket != 0, "_inBytesPacket cannot be 0 after processing header!");
-                    if (_inBytesUsed == _inBytesRead)
-                    {
-                        // we read a header but didn't get anything else except it
-                        // VSTS 219884: it can happen that the TDS packet header and its data are split across two network packets.
-                        // Read at least one more byte to get/cache the first data portion of this TDS packet
-                        if (!TryReadNetworkPacket())
-                        {
-                            return false;
-                        }
-                    }
-                }
-                else
-                {
-                    Debug.Fail("entered negative _inBytesPacket loop");
-                }
-                AssertValidState();
-            }
-
-            return true;
-        }
-
-        internal void ResetBuffer()
-        {
-            _outBytesUsed = _outputHeaderLen;
-        }
-
-        internal void ResetPacketCounters()
-        {
-            _outputPacketNumber = 1;
-            _outputPacketCount = 0;
-        }
-
-        internal bool SetPacketSize(int size)
-        {
-            if (size > TdsEnums.MAX_PACKET_SIZE)
-            {
-                throw SQL.InvalidPacketSize();
-            }
-            Debug.Assert(size >= 1, "Cannot set packet size to less than 1.");
-            Debug.Assert((_outBuff == null && _inBuff == null) ||
-                          (_outBuff.Length == _inBuff.Length),
-                          "Buffers are not in consistent state");
-            Debug.Assert((_outBuff == null && _inBuff == null) ||
-                          this == _parser._physicalStateObj,
-                          "SetPacketSize should only be called on a stateObj with null buffers on the physicalStateObj!");
-            Debug.Assert(_inBuff == null
-                          || (
-                          _outBytesUsed == (_outputHeaderLen + BitConverter.ToInt32(_outBuff, _outputHeaderLen)) &&
-                          _outputPacketNumber == 1)
-                          ||
-                          (_outBytesUsed == _outputHeaderLen && _outputPacketNumber == 1),
-                          "SetPacketSize called with data in the buffer!");
-
-            if (_inBuff == null || _inBuff.Length != size)
-            { // We only check _inBuff, since two buffers should be consistent.
-                // Allocate or re-allocate _inBuff.
-                if (_inBuff == null)
-                {
-                    _inBuff = new byte[size];
-                    _inBytesRead = 0;
-                    _inBytesUsed = 0;
-                }
-                else if (size != _inBuff.Length)
-                {
-                    // If new size is other than existing...
-                    if (_inBytesRead > _inBytesUsed)
-                    {
-                        // if we still have data left in the buffer we must keep that array reference and then copy into new one
-                        byte[] temp = _inBuff;
-
-                        _inBuff = new byte[size];
-
-                        // copy remainder of unused data
-                        int remainingData = _inBytesRead - _inBytesUsed;
-                        if ((temp.Length < _inBytesUsed + remainingData) || (_inBuff.Length < remainingData))
-                        {
-                            string errormessage = SR.GetString(SR.SQL_InvalidInternalPacketSize) + ' ' + temp.Length + ", " + _inBytesUsed + ", " + remainingData + ", " + _inBuff.Length;
-                            throw SQL.InvalidInternalPacketSize(errormessage);
-                        }
-                        Buffer.BlockCopy(temp, _inBytesUsed, _inBuff, 0, remainingData);
-
-                        _inBytesRead = _inBytesRead - _inBytesUsed;
-                        _inBytesUsed = 0;
-
-                        AssertValidState();
-                    }
-                    else
-                    {
-                        // buffer is empty - just create the new one that is double the size of the old one
-                        _inBuff = new byte[size];
-                        _inBytesRead = 0;
-                        _inBytesUsed = 0;
-                    }
-                }
-
-                // Always re-allocate _outBuff - assert is above to verify state.
-                _outBuff = new byte[size];
-                _outBytesUsed = _outputHeaderLen;
-
-                AssertValidState();
-                return true;
-            }
-
-            return false;
-        }
-
-        ///////////////////////////////////////
-        // Buffer read methods - data values //
-        ///////////////////////////////////////
-
-        // look at the next byte without pulling it off the wire, don't just return _inBytesUsed since we may
-        // have to go to the network to get the next byte.
-        internal bool TryPeekByte(out byte value)
-        {
-            if (!TryReadByte(out value))
-            {
-                return false;
-            }
-
-            // now do fixup
-            _inBytesPacket++;
-            _inBytesUsed--;
-
-            AssertValidState();
-            return true;
-        }
-
-        // Takes a byte array, an offset, and a len and fills the array from the offset to len number of
-        // bytes from the in buffer.
-        public bool TryReadByteArray(Span<byte> buff, int len)
-        {
-            return TryReadByteArray(buff, len, out _);
-        }
-
-        // NOTE: This method must be retriable WITHOUT replaying a snapshot
-        // Every time you call this method increment the offset and decrease len by the value of totalRead
-        public bool TryReadByteArray(Span<byte> buff, int len, out int totalRead)
-        {
-            totalRead = 0;
-
-#if DEBUG
-            if (_snapshot != null && _snapshot.DoPend())
-            {
-                _networkPacketTaskSource = new TaskCompletionSource<object>();
-                Interlocked.MemoryBarrier();
-
-                if (_forcePendingReadsToWaitForUser)
-                {
-                    _realNetworkPacketTaskSource = new TaskCompletionSource<object>();
-                    _realNetworkPacketTaskSource.SetResult(null);
-                }
-                else
-                {
-                    _networkPacketTaskSource.TrySetResult(null);
-                }
-                return false;
-            }
-#endif
-
-            Debug.Assert(buff.IsEmpty || buff.Length >= len, "Invalid length sent to ReadByteArray()!");
-
-            // loop through and read up to array length
-            while (len > 0)
-            {
-                if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
-                {
-                    if (!TryPrepareBuffer())
-                    {
-                        return false;
-                    }
-                }
-
-                int bytesToRead = Math.Min(len, Math.Min(_inBytesPacket, _inBytesRead - _inBytesUsed));
-                Debug.Assert(bytesToRead > 0, "0 byte read in TryReadByteArray");
-                if (!buff.IsEmpty)
-                {
-                    var copyFrom = new ReadOnlySpan<byte>(_inBuff, _inBytesUsed, bytesToRead);
-                    Span<byte> copyTo = buff.Slice(totalRead, bytesToRead);
-                    copyFrom.CopyTo(copyTo);
-                }
-
-                totalRead += bytesToRead;
-                _inBytesUsed += bytesToRead;
-                _inBytesPacket -= bytesToRead;
-                len -= bytesToRead;
-
-                AssertValidState();
-            }
-
-            return true;
-        }
-
-        // Takes no arguments and returns a byte from the buffer.  If the buffer is empty, it is filled
-        // before the byte is returned.
-        internal bool TryReadByte(out byte value)
-        {
-            Debug.Assert(_inBytesUsed >= 0 && _inBytesUsed <= _inBytesRead, "ERROR - TDSParser: _inBytesUsed < 0 or _inBytesUsed > _inBytesRead");
-            value = 0;
-
-#if DEBUG
-            if (_snapshot != null && _snapshot.DoPend())
-            {
-                _networkPacketTaskSource = new TaskCompletionSource<object>();
-                Interlocked.MemoryBarrier();
-
-                if (_forcePendingReadsToWaitForUser)
-                {
-                    _realNetworkPacketTaskSource = new TaskCompletionSource<object>();
-                    _realNetworkPacketTaskSource.SetResult(null);
-                }
-                else
-                {
-                    _networkPacketTaskSource.TrySetResult(null);
-                }
-                return false;
-            }
-#endif
-
-            if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
-            {
-                if (!TryPrepareBuffer())
-                {
-                    return false;
-                }
-            }
-
-            // decrement the number of bytes left in the packet
-            _inBytesPacket--;
-
-            Debug.Assert(_inBytesPacket >= 0, "ERROR - TDSParser: _inBytesPacket < 0");
-
-            // return the byte from the buffer and increment the counter for number of bytes used in the in buffer
-            value = (_inBuff[_inBytesUsed++]);
-
-            AssertValidState();
-            return true;
-        }
-
-        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;
-            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))
-                {
-                    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;
-
-                _inBytesUsed += 2;
-                _inBytesPacket -= 2;
-            }
-
-            AssertValidState();
-            value = (char)((buffer[offset + 1] << 8) + buffer[offset]);
-            return true;
-        }
-
-        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;
-            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))
-                {
-                    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;
-
-                _inBytesUsed += 2;
-                _inBytesPacket -= 2;
-            }
-
-            AssertValidState();
-            value = (short)((buffer[offset + 1] << 8) + buffer[offset]);
-            return true;
-        }
-
-        internal bool TryReadInt32(out int value)
-        {
-            Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
-            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))
-                {
-                    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);
-
-                _inBytesUsed += 4;
-                _inBytesPacket -= 4;
-
-                AssertValidState();
-                return true;
-            }
-        }
-
-        // This method is safe to call when doing async without snapshot
-        internal bool TryReadInt64(out long value)
-        {
-            if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
-            {
-                if (!TryPrepareBuffer())
-                {
-                    value = 0;
-                    return false;
-                }
-            }
-
-            if ((_bTmpRead > 0) || (((_inBytesUsed + 8) > _inBytesRead) || (_inBytesPacket < 8)))
-            {
-                // If the long 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.
-
-                int bytesRead = 0;
-                if (!TryReadByteArray(_bTmp.AsSpan(_bTmpRead), 8 - _bTmpRead, out bytesRead))
-                {
-                    Debug.Assert(_bTmpRead + bytesRead <= 8, "Read more data than required");
-                    _bTmpRead += bytesRead;
-                    value = 0;
-                    return false;
-                }
-                else
-                {
-                    Debug.Assert(_bTmpRead + bytesRead == 8, "TryReadByteArray returned true without reading all data required");
-                    _bTmpRead = 0;
-                    AssertValidState();
-                    value = BitConverter.ToInt64(_bTmp, 0);
-                    return true;
-                }
-            }
-            else
-            {
-                // The entire long is in the packet and in the buffer, so just return it
-                // and take care of the counters.
-
-                value = BitConverter.ToInt64(_inBuff, _inBytesUsed);
-
-                _inBytesUsed += 8;
-                _inBytesPacket -= 8;
-
-                AssertValidState();
-                return true;
-            }
-        }
-
-        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;
-            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))
-                {
-                    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;
-
-                _inBytesUsed += 2;
-                _inBytesPacket -= 2;
-            }
-
-            AssertValidState();
-            value = (ushort)((buffer[offset + 1] << 8) + buffer[offset]);
-            return true;
-        }
-
-        // This method is safe to call when doing async without replay
-        internal bool TryReadUInt32(out uint value)
-        {
-            if ((_inBytesPacket == 0) || (_inBytesUsed == _inBytesRead))
-            {
-                if (!TryPrepareBuffer())
-                {
-                    value = 0;
-                    return false;
-                }
-            }
-
-            if ((_bTmpRead > 0) || (((_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.
-
-                int bytesRead = 0;
-                if (!TryReadByteArray(_bTmp.AsSpan(_bTmpRead), 4 - _bTmpRead, out bytesRead))
-                {
-                    Debug.Assert(_bTmpRead + bytesRead <= 4, "Read more data than required");
-                    _bTmpRead += bytesRead;
-                    value = 0;
-                    return false;
-                }
-                else
-                {
-                    Debug.Assert(_bTmpRead + bytesRead == 4, "TryReadByteArray returned true without reading all data required");
-                    _bTmpRead = 0;
-                    AssertValidState();
-                    value = BitConverter.ToUInt32(_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.ToUInt32(_inBuff, _inBytesUsed);
-
-                _inBytesUsed += 4;
-                _inBytesPacket -= 4;
-
-                AssertValidState();
-                return true;
-            }
-        }
-
-        internal bool TryReadSingle(out float value)
-        {
-            Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
-            if (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4))
-            {
-                // If the float 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))
-                {
-                    value = default;
-                    return false;
-                }
-
-                AssertValidState();
-                value = BitConverter.ToSingle(_bTmp, 0);
-                return true;
-            }
-            else
-            {
-                // The entire float is in the packet and in the buffer, so just return it
-                // and take care of the counters.
-
-                value = BitConverter.ToSingle(_inBuff, _inBytesUsed);
-
-                _inBytesUsed += 4;
-                _inBytesPacket -= 4;
-
-                AssertValidState();
-                return true;
-            }
-        }
-
-        internal bool TryReadDouble(out double value)
-        {
-            Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
-            if (((_inBytesUsed + 8) > _inBytesRead) || (_inBytesPacket < 8))
-            {
-                // If the double 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, 8))
-                {
-                    value = default;
-                    return false;
-                }
-
-                AssertValidState();
-                value = BitConverter.ToDouble(_bTmp, 0);
-                return true;
-            }
-            else
-            {
-                // The entire double is in the packet and in the buffer, so just return it
-                // and take care of the counters.
-
-                value = BitConverter.ToDouble(_inBuff, _inBytesUsed);
-
-                _inBytesUsed += 8;
-                _inBytesPacket -= 8;
-
-                AssertValidState();
-                return true;
-            }
-        }
-
-        internal bool TryReadString(int length, out string value)
-        {
-            Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
-            int cBytes = length << 1;
-            byte[] buf;
-            int offset = 0;
-
-            if (((_inBytesUsed + cBytes) > _inBytesRead) || (_inBytesPacket < cBytes))
-            {
-                if (_bTmp == null || _bTmp.Length < cBytes)
-                {
-                    _bTmp = new byte[cBytes];
-                }
-
-                if (!TryReadByteArray(_bTmp, cBytes))
-                {
-                    value = null;
-                    return false;
-                }
-
-                // assign local to point to parser scratch buffer
-                buf = _bTmp;
-
-                AssertValidState();
-            }
-            else
-            {
-                // assign local to point to _inBuff
-                buf = _inBuff;
-                offset = _inBytesUsed;
-                _inBytesUsed += cBytes;
-                _inBytesPacket -= cBytes;
-
-                AssertValidState();
-            }
-
-            value = System.Text.Encoding.Unicode.GetString(buf, offset, cBytes);
-            return true;
-        }
-
-        internal bool TryReadStringWithEncoding(int length, System.Text.Encoding encoding, bool isPlp, out string value)
-        {
-            Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
-
-            if (null == encoding)
-            {
-                // Need to skip the current column before throwing the error - this ensures that the state shared between this and the data reader is consistent when calling DrainData
-                if (isPlp)
-                {
-                    ulong ignored;
-                    if (!_parser.TrySkipPlpValue((ulong)length, this, out ignored))
-                    {
-                        value = null;
-                        return false;
-                    }
-                }
-                else
-                {
-                    if (!TrySkipBytes(length))
-                    {
-                        value = null;
-                        return false;
-                    }
-                }
-
-                _parser.ThrowUnsupportedCollationEncountered(this);
-            }
-            byte[] buf = null;
-            int offset = 0;
-
-            if (isPlp)
-            {
-                if (!TryReadPlpBytes(ref buf, 0, int.MaxValue, out length))
-                {
-                    value = null;
-                    return false;
-                }
-
-                AssertValidState();
-            }
-            else
-            {
-                if (((_inBytesUsed + length) > _inBytesRead) || (_inBytesPacket < length))
-                {
-                    if (_bTmp == null || _bTmp.Length < length)
-                    {
-                        _bTmp = new byte[length];
-                    }
-
-                    if (!TryReadByteArray(_bTmp, length))
-                    {
-                        value = null;
-                        return false;
-                    }
-
-                    // assign local to point to parser scratch buffer
-                    buf = _bTmp;
-
-                    AssertValidState();
-                }
-                else
-                {
-                    // assign local to point to _inBuff
-                    buf = _inBuff;
-                    offset = _inBytesUsed;
-                    _inBytesUsed += length;
-                    _inBytesPacket -= length;
-
-                    AssertValidState();
-                }
-            }
-
-            // BCL optimizes to not use char[] underneath
-            value = encoding.GetString(buf, offset, length);
-            return true;
-        }
-
-        internal ulong ReadPlpLength(bool returnPlpNullIfNull)
-        {
-            ulong value;
-            Debug.Assert(_syncOverAsync, "Should not attempt pends in a synchronous call");
-            bool result = TryReadPlpLength(returnPlpNullIfNull, out value);
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-            return value;
-        }
-
-        // Reads the length of either the entire data or the length of the next chunk in a
-        //   partially length prefixed data
-        // After this call, call  ReadPlpBytes/ReadPlpUnicodeChars until the specified length of data
-        // is consumed. Repeat this until ReadPlpLength returns 0 in order to read the
-        // entire stream.
-        // When this function returns 0, it means the data stream is read completely and the
-        // plp state in the tdsparser is cleaned.
-        internal bool TryReadPlpLength(bool returnPlpNullIfNull, out ulong lengthLeft)
-        {
-            uint chunklen;
-            // bool firstchunk = false;
-            bool isNull = false;
-
-            Debug.Assert(_longlenleft == 0, "Out of synch length read request");
-            if (_longlen == 0)
-            {
-                // First chunk is being read. Find out what type of chunk it is
-                long value;
-                if (!TryReadInt64(out value))
-                {
-                    lengthLeft = 0;
-                    return false;
-                }
-                _longlen = (ulong)value;
-                // firstchunk = true;
-            }
-
-            if (_longlen == TdsEnums.SQL_PLP_NULL)
-            {
-                _longlen = 0;
-                _longlenleft = 0;
-                isNull = true;
-            }
-            else
-            {
-                // Data is coming in uint chunks, read length of next chunk
-                if (!TryReadUInt32(out chunklen))
-                {
-                    lengthLeft = 0;
-                    return false;
-                }
-                if (chunklen == TdsEnums.SQL_PLP_CHUNK_TERMINATOR)
-                {
-                    _longlenleft = 0;
-                    _longlen = 0;
-                }
-                else
-                {
-                    _longlenleft = (ulong)chunklen;
-                }
-            }
-
-            AssertValidState();
-
-            if (isNull && returnPlpNullIfNull)
-            {
-                lengthLeft = TdsEnums.SQL_PLP_NULL;
-                return true;
-            }
-
-            lengthLeft = _longlenleft;
-            return true;
-        }
-
-        internal int ReadPlpBytesChunk(byte[] buff, int offset, int len)
-        {
-            Debug.Assert(_syncOverAsync, "Should not attempt pends in a synchronous call");
-            Debug.Assert(_longlenleft > 0, "Read when no data available");
-
-            int value;
-            int bytesToRead = (int)Math.Min(_longlenleft, (ulong)len);
-            bool result = TryReadByteArray(buff.AsSpan(offset), bytesToRead, out value);
-            _longlenleft -= (ulong)bytesToRead;
-            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
-            return value;
-        }
-
-        // Reads the requested number of bytes from a plp data stream, or the entire data if
-        // requested length is -1 or larger than the actual length of data. First call to this method
-        //  should be preceded by a call to ReadPlpLength or ReadDataLength.
-        // Returns the actual bytes read.
-        // NOTE: This method must be retriable WITHOUT replaying a snapshot
-        // Every time you call this method increment the offset and decrease len by the value of totalBytesRead
-        internal bool TryReadPlpBytes(ref byte[] buff, int offset, int len, out int totalBytesRead)
-        {
-            int bytesRead = 0;
-            int bytesLeft;
-            byte[] newbuf;
-            ulong ignored;
-
-            if (_longlen == 0)
-            {
-                Debug.Assert(_longlenleft == 0);
-                if (buff == null)
-                {
-                    buff = Array.Empty<byte>();
-                }
-
-                AssertValidState();
-                totalBytesRead = 0;
-                return true;       // No data
-            }
-
-            Debug.Assert((_longlen != TdsEnums.SQL_PLP_NULL),
-                    "Out of sync plp read request");
-
-            Debug.Assert((buff == null && offset == 0) || (buff.Length >= offset + len), "Invalid length sent to ReadPlpBytes()!");
-            bytesLeft = len;
-
-            // If total length is known up front, allocate the whole buffer in one shot instead of realloc'ing and copying over each time
-            if (buff == null && _longlen != TdsEnums.SQL_PLP_UNKNOWNLEN)
-            {
-                buff = new byte[(int)Math.Min((int)_longlen, len)];
-            }
-
-            if (_longlenleft == 0)
-            {
-                if (!TryReadPlpLength(false, out ignored))
-                {
-                    totalBytesRead = 0;
-                    return false;
-                }
-                if (_longlenleft == 0)
-                { // Data read complete
-                    totalBytesRead = 0;
-                    return true;
-                }
-            }
-
-            if (buff == null)
-            {
-                buff = new byte[_longlenleft];
-            }
-
-            totalBytesRead = 0;
-
-            while (bytesLeft > 0)
-            {
-                int bytesToRead = (int)Math.Min(_longlenleft, (ulong)bytesLeft);
-                if (buff.Length < (offset + bytesToRead))
-                {
-                    // Grow the array
-                    newbuf = new byte[offset + bytesToRead];
-                    Buffer.BlockCopy(buff, 0, newbuf, 0, offset);
-                    buff = newbuf;
-                }
-
-                bool result = TryReadByteArray(buff.AsSpan(offset), bytesToRead, out bytesRead);
-                Debug.Assert(bytesRead <= bytesLeft, "Read more bytes than we needed");
-                Debug.Assert((ulong)bytesRead <= _longlenleft, "Read more bytes than is available");
-
-                bytesLeft -= bytesRead;
-                offset += bytesRead;
-                totalBytesRead += bytesRead;
-                _longlenleft -= (ulong)bytesRead;
-                if (!result)
-                {
-                    return false;
-                }
-
-                if (_longlenleft == 0)
-                { // Read the next chunk or cleanup state if hit the end
-                    if (!TryReadPlpLength(false, out ignored))
-                    {
-                        return false;
-                    }
-                }
-
-                AssertValidState();
-
-                // Catch the point where we read the entire plp data stream and clean up state
-                if (_longlenleft == 0)   // Data read complete
-                    break;
-            }
-            return true;
-        }
-
-
-        /////////////////////////////////////////
-        // Value Skip Logic                    //
-        /////////////////////////////////////////
-
-
-        // Reads bytes from the buffer but doesn't return them, in effect simply deleting them.
-        // Does not handle plp fields, need to use SkipPlpBytesValue for those.
-        // Does not handle null values or NBC bitmask, ensure the value is not null before calling this method
-        internal bool TrySkipLongBytes(long num)
-        {
-            Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
-            int cbSkip = 0;
-
-            while (num > 0)
-            {
-                cbSkip = (int)Math.Min((long)int.MaxValue, num);
-                if (!TryReadByteArray(Span<byte>.Empty, cbSkip))
-                {
-                    return false;
-                }
-                num -= (long)cbSkip;
-            }
-
-            return true;
-        }
-
-        // Reads bytes from the buffer but doesn't return them, in effect simply deleting them.
-        internal bool TrySkipBytes(int num)
-        {
-            Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async");
-            return TryReadByteArray(Span<byte>.Empty, num);
-        }
-
-        /////////////////////////////////////////
-        // Network/Packet Reading & Processing //
-        /////////////////////////////////////////
-
-        internal void SetSnapshot()
-        {
-            _snapshot = new StateSnapshot(this);
-            _snapshot.Snap();
-            _snapshotReplay = false;
-        }
-
-        internal void ResetSnapshot()
-        {
-            _snapshot = null;
-            _snapshotReplay = false;
-        }
-
-#if DEBUG
-        private string _lastStack;
-#endif
-
-        internal bool TryReadNetworkPacket()
-        {
-#if DEBUG
-            Debug.Assert(!_shouldHaveEnoughData || _attentionSent, "Caller said there should be enough data, but we are currently reading a packet");
-#endif
-
-            if (_snapshot != null)
-            {
-                if (_snapshotReplay)
-                {
-                    if (_snapshot.Replay())
-                    {
-#if DEBUG
-                        if (_checkNetworkPacketRetryStacks)
-                        {
-                            _snapshot.CheckStack(Environment.StackTrace);
-                        }
-#endif
-                        return true;
-                    }
-#if DEBUG
-                    else
-                    {
-                        if (_checkNetworkPacketRetryStacks)
-                        {
-                            _lastStack = Environment.StackTrace;
-                        }
-                    }
-#endif
-                }
-
-                // previous buffer is in snapshot
-                _inBuff = new byte[_inBuff.Length];
-            }
-
-            if (_syncOverAsync)
-            {
-                ReadSniSyncOverAsync();
-                return true;
-            }
-
-            ReadSni(new TaskCompletionSource<object>());
-
-#if DEBUG
-            if (_failAsyncPends)
-            {
-                throw new InvalidOperationException("Attempted to pend a read when _failAsyncPends test hook was enabled");
-            }
-            if (_forceSyncOverAsyncAfterFirstPend)
-            {
-                _syncOverAsync = true;
-            }
-#endif
-            Debug.Assert((_snapshot != null) ^ _asyncReadWithoutSnapshot, "Must have either _snapshot set up or _asyncReadWithoutSnapshot enabled (but not both) to pend a read");
-
-            return false;
-        }
-
-        internal void PrepareReplaySnapshot()
-        {
-            _networkPacketTaskSource = null;
-            _snapshot.PrepareReplay();
-        }
-
-        internal void ReadSniSyncOverAsync()
-        {
-            if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
-            {
-                throw ADP.ClosedConnectionError();
-            }
-
-            PacketHandle readPacket = default;
-
-            uint error;
-
-            bool shouldDecrement = false;
-            try
-            {
-                Interlocked.Increment(ref _readingCount);
-                shouldDecrement = true;
-
-                readPacket = ReadSyncOverAsync(GetTimeoutRemaining(), out error);
-
-                Interlocked.Decrement(ref _readingCount);
-                shouldDecrement = false;
-
-                if (_parser.MARSOn)
-                { // Only take reset lock on MARS and Async.
-                    CheckSetResetConnectionState(error, CallbackType.Read);
-                }
-
-                if (TdsEnums.SNI_SUCCESS == error)
-                { // Success - process results!
-
-                    Debug.Assert(!IsPacketEmpty(readPacket), "ReadNetworkPacket cannot be null in synchronous operation!");
-
-                    ProcessSniPacket(readPacket, 0);
-#if DEBUG
-                    if (_forcePendingReadsToWaitForUser)
-                    {
-                        _networkPacketTaskSource = new TaskCompletionSource<object>();
-                        Interlocked.MemoryBarrier();
-                        _networkPacketTaskSource.Task.Wait();
-                        _networkPacketTaskSource = null;
-                    }
-#endif
-                }
-                else
-                { // Failure!
-
-                    Debug.Assert(!IsValidPacket(readPacket), "unexpected readPacket without corresponding SNIPacketRelease");
-
-                    ReadSniError(this, error);
-                }
-            }
-            finally
-            {
-                if (shouldDecrement)
-                {
-                    Interlocked.Decrement(ref _readingCount);
-                }
-
-                if (!IsPacketEmpty(readPacket))
-                {
-                    ReleasePacket(readPacket);
-                }
-
-                AssertValidState();
-            }
-        }
-
-        internal void OnConnectionClosed()
-        {
-            // the stateObj is not null, so the async invocation that registered this callback
-            // via the SqlReferenceCollection has not yet completed.  We will look for a
-            // _networkPacketTaskSource and mark it faulted.  If we don't find it, then
-            // TdsParserStateObject.ReadSni will abort when it does look to see if the parser
-            // is open.  If we do, then when the call that created it completes and a continuation
-            // is registered, we will ensure the completion is called.
-
-            // Note, this effort is necessary because when the app domain is being unloaded,
-            // we don't get callback from SNI.
-
-            // first mark parser broken.  This is to ensure that ReadSni will abort if it has
-            // not yet executed.
-            Parser.State = TdsParserState.Broken;
-            Parser.Connection.BreakConnection();
-
-            // Ensure that changing state occurs before checking _networkPacketTaskSource
-            Interlocked.MemoryBarrier();
-
-            // then check for networkPacketTaskSource
-            var taskSource = _networkPacketTaskSource;
-            if (taskSource != null)
-            {
-                taskSource.TrySetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
-            }
-
-            taskSource = _writeCompletionSource;
-            if (taskSource != null)
-            {
-                taskSource.TrySetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
-            }
-        }
-
-        private void OnTimeout(object state)
-        {
-            if (!_internalTimeout)
-            {
-                _internalTimeout = true;
-                // lock protects against Close and Cancel
-                lock (this)
-                {
-                    if (!_attentionSent)
-                    {
-                        AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _parser.Server, _parser.Connection.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
-
-                        // Grab a reference to the _networkPacketTaskSource in case it becomes null while we are trying to use it
-                        TaskCompletionSource<object> source = _networkPacketTaskSource;
-
-                        if (_parser.Connection.IsInPool)
-                        {
-                            // We should never timeout if the connection is currently in the pool: the safest thing to do here is to doom the connection to avoid corruption
-                            Debug.Assert(_parser.Connection.IsConnectionDoomed, "Timeout occurred while the connection is in the pool");
-                            _parser.State = TdsParserState.Broken;
-                            _parser.Connection.BreakConnection();
-                            if (source != null)
-                            {
-                                source.TrySetCanceled();
-                            }
-                        }
-                        else if (_parser.State == TdsParserState.OpenLoggedIn)
-                        {
-                            try
-                            {
-                                SendAttention(mustTakeWriteLock: true);
-                            }
-                            catch (Exception e)
-                            {
-                                if (!ADP.IsCatchableExceptionType(e))
-                                {
-                                    throw;
-                                }
-                                // if unable to send attention, cancel the _networkPacketTaskSource to
-                                // request the parser be broken.  SNIWritePacket errors will already
-                                // be in the _errors collection.
-                                if (source != null)
-                                {
-                                    source.TrySetCanceled();
-                                }
-                            }
-                        }
-
-                        // If we still haven't received a packet then we don't want to actually close the connection
-                        // from another thread, so complete the pending operation as cancelled, informing them to break it
-                        if (source != null)
-                        {
-                            Task.Delay(AttentionTimeoutSeconds * 1000).ContinueWith(_ =>
-                            {
-                                // Only break the connection if the read didn't finish
-                                if (!source.Task.IsCompleted)
-                                {
-                                    int pendingCallback = IncrementPendingCallbacks();
-                                    try
-                                    {
-                                        // If pendingCallback is at 3, then ReadAsyncCallback hasn't been called yet
-                                        // So it is safe for us to break the connection and cancel the Task (since we are not sure that ReadAsyncCallback will ever be called)
-                                        if ((pendingCallback == 3) && (!source.Task.IsCompleted))
-                                        {
-                                            Debug.Assert(source == _networkPacketTaskSource, "_networkPacketTaskSource which is being timed is not the current task source");
-
-                                            // Try to throw the timeout exception and store it in the task
-                                            bool exceptionStored = false;
-                                            try
-                                            {
-                                                CheckThrowSNIException();
-                                            }
-                                            catch (Exception ex)
-                                            {
-                                                if (source.TrySetException(ex))
-                                                {
-                                                    exceptionStored = true;
-                                                }
-                                            }
-
-                                            // Ensure that the connection is no longer usable
-                                            // This is needed since the timeout error added above is non-fatal (and so throwing it won't break the connection)
-                                            _parser.State = TdsParserState.Broken;
-                                            _parser.Connection.BreakConnection();
-
-                                            // If we didn't get an exception (something else observed it?) then ensure that the task is cancelled
-                                            if (!exceptionStored)
-                                            {
-                                                source.TrySetCanceled();
-                                            }
-                                        }
-                                    }
-                                    finally
-                                    {
-                                        DecrementPendingCallbacks(release: false);
-                                    }
-                                }
-                            }, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
-                        }
-                    }
-                }
-            }
-        }
-
-        internal void ReadSni(TaskCompletionSource<object> completion)
-        {
-
-            Debug.Assert(_networkPacketTaskSource == null || ((_asyncReadWithoutSnapshot) && (_networkPacketTaskSource.Task.IsCompleted)), "Pending async call or failed to replay snapshot when calling ReadSni");
-            _networkPacketTaskSource = completion;
-
-            // Ensure that setting the completion source is completed before checking the state
-            Interlocked.MemoryBarrier();
-
-            // We must check after assigning _networkPacketTaskSource to avoid races with
-            // SqlCommand.OnConnectionClosed
-            if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed)
-            {
-                throw ADP.ClosedConnectionError();
-            }
-
-#if DEBUG
-            if (_forcePendingReadsToWaitForUser)
-            {
-                _realNetworkPacketTaskSource = new TaskCompletionSource<object>();
-            }
-#endif
-
-
-            PacketHandle readPacket = default;
-
-            uint error = 0;
-
-            try
-            {
-                Debug.Assert(completion != null, "Async on but null asyncResult passed");
-
-                if (_networkPacketTimeout == null)
-                {
-                    _networkPacketTimeout = ADP.UnsafeCreateTimer(
-                        new TimerCallback(OnTimeout),
-                        null,
-                        Timeout.Infinite,
-                        Timeout.Infinite);
-                }
-
-                // -1 == Infinite
-                //  0 == Already timed out (NOTE: To simulate the same behavior as sync we will only timeout on 0 if we receive an IO Pending from SNI)
-                // >0 == Actual timeout remaining
-                int msecsRemaining = GetTimeoutRemaining();
-                if (msecsRemaining > 0)
-                {
-                    ChangeNetworkPacketTimeout(msecsRemaining, Timeout.Infinite);
-                }
-
-                Interlocked.Increment(ref _readingCount);
-
-                SessionHandle handle = SessionHandle;
-                if (!handle.IsNull)
-                {
-                    IncrementPendingCallbacks();
-
-                    readPacket = ReadAsync(handle, out error);
-
-                    if (!(TdsEnums.SNI_SUCCESS == error || TdsEnums.SNI_SUCCESS_IO_PENDING == error))
-                    {
-                        DecrementPendingCallbacks(false); // Failure - we won't receive callback!
-                    }
-                }
-
-                Interlocked.Decrement(ref _readingCount);
-
-                if (handle.IsNull)
-                {
-                    throw ADP.ClosedConnectionError();
-                }
-
-                if (TdsEnums.SNI_SUCCESS == error)
-                { // Success - process results!
-                    Debug.Assert(IsValidPacket(readPacket), "ReadNetworkPacket should not have been null on this async operation!");
-                    // Evaluate this condition for MANAGED_SNI. This may not be needed because the network call is happening Async and only the callback can receive a success.
-                    ReadAsyncCallback(IntPtr.Zero, readPacket, 0);
-                }
-                else if (TdsEnums.SNI_SUCCESS_IO_PENDING != error)
-                { // FAILURE!
-                    Debug.Assert(IsPacketEmpty(readPacket), "unexpected readPacket without corresponding SNIPacketRelease");
-
-                    ReadSniError(this, error);
-#if DEBUG
-                    if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null))
-                    {
-                        _realNetworkPacketTaskSource.TrySetResult(null);
-                    }
-                    else
-#endif
-                    {
-                        _networkPacketTaskSource.TrySetResult(null);
-                    }
-                    // Disable timeout timer on error
-                    ChangeNetworkPacketTimeout(Timeout.Infinite, Timeout.Infinite);
-                }
-                else if (msecsRemaining == 0)
-                { // Got IO Pending, but we have no time left to wait
-                    // Immediately schedule the timeout timer to fire
-                    ChangeNetworkPacketTimeout(0, Timeout.Infinite);
-                }
-                // DO NOT HANDLE PENDING READ HERE - which is TdsEnums.SNI_SUCCESS_IO_PENDING state.
-                // That is handled by user who initiated async read, or by ReadNetworkPacket which is sync over async.
-            }
-            finally
-            {
-                if (!TdsParserStateObjectFactory.UseManagedSNI)
-                {
-                    if (!IsPacketEmpty(readPacket))
-                    {
-                        // Be sure to release packet, otherwise it will be leaked by native.
-                        ReleasePacket(readPacket);
-                    }
-                }
-                AssertValidState();
-            }
-        }
-
-        /// <summary>
-        /// Checks to see if the underlying connection is still alive (used by connection pool resiliency)
-        /// NOTE: This is not safe to do on a connection that is currently in use
-        /// NOTE: This will mark the connection as broken if it is found to be dead
-        /// </summary>
-        /// <param name="throwOnException">If true then an exception will be thrown if the connection is found to be dead, otherwise no exception will be thrown</param>
-        /// <returns>True if the connection is still alive, otherwise false</returns>
-        internal bool IsConnectionAlive(bool throwOnException)
-        {
-            Debug.Assert(_parser.Connection == null || _parser.Connection.Pool != null, "Shouldn't be calling IsConnectionAlive on non-pooled connections");
-            bool isAlive = true;
-
-            if (DateTime.UtcNow.Ticks - _lastSuccessfulIOTimer._value > CheckConnectionWindow)
-            {
-                if ((_parser == null) || ((_parser.State == TdsParserState.Broken) || (_parser.State == TdsParserState.Closed)))
-                {
-                    isAlive = false;
-                    if (throwOnException)
-                    {
-                        throw SQL.ConnectionDoomed();
-                    }
-                }
-                else if ((_pendingCallbacks > 1) || ((_parser.Connection != null) && (!_parser.Connection.IsInPool)))
-                {
-                    // This connection is currently in use, assume that the connection is 'alive'
-                    // NOTE: SNICheckConnection is not currently supported for connections that are in use
-                    Debug.Assert(true, "Call to IsConnectionAlive while connection is in use");
-                }
-                else
-                {
-                    uint error;
-                    SniContext = SniContext.Snix_Connect;
-                    error = CheckConnection();
-
-                    if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT))
-                    {
-                        // Connection is dead
-                        isAlive = false;
-                        if (throwOnException)
-                        {
-                            // Get the error from SNI so that we can throw the correct exception
-                            AddError(_parser.ProcessSNIError(this));
-                            ThrowExceptionAndWarning();
-                        }
-                    }
-                    else
-                    {
-                        _lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
-                    }
-                }
-            }
-
-            return isAlive;
-        }
-
-        /// <summary>
-        /// Checks to see if the underlying connection is still valid (used by idle connection resiliency - for active connections)
-        /// NOTE: This is not safe to do on a connection that is currently in use
-        /// NOTE: This will mark the connection as broken if it is found to be dead
-        /// </summary>
-        /// <returns>True if the connection is still alive, otherwise false</returns>
-        internal bool ValidateSNIConnection()
-        {
-            if ((_parser == null) || ((_parser.State == TdsParserState.Broken) || (_parser.State == TdsParserState.Closed)))
-            {
-                return false;
-            }
-
-            if (DateTime.UtcNow.Ticks - _lastSuccessfulIOTimer._value <= CheckConnectionWindow)
-            {
-                return true;
-            }
-
-            uint error = TdsEnums.SNI_SUCCESS;
-            SniContext = SniContext.Snix_Connect;
-            try
-            {
-                Interlocked.Increment(ref _readingCount);
-                error = CheckConnection();
-            }
-            finally
-            {
-                Interlocked.Decrement(ref _readingCount);
-            }
-            return (error == TdsEnums.SNI_SUCCESS) || (error == TdsEnums.SNI_WAIT_TIMEOUT);
-        }
-
-        // This method should only be called by ReadSni!  If not - it may have problems with timeouts!
-        private void ReadSniError(TdsParserStateObject stateObj, uint error)
-        {
-            if (TdsEnums.SNI_WAIT_TIMEOUT == error)
-            {
-                Debug.Assert(_syncOverAsync, "Should never reach here with async on!");
-                bool fail = false;
-
-                if (_internalTimeout)
-                { // This is now our second timeout - time to give up.
-                    fail = true;
-                }
-                else
-                {
-                    stateObj._internalTimeout = true;
-                    Debug.Assert(_parser.Connection != null, "SqlConnectionInternalTds handler can not be null at this point.");
-                    AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _parser.Server, _parser.Connection.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
-
-                    if (!stateObj._attentionSent)
-                    {
-                        if (stateObj.Parser.State == TdsParserState.OpenLoggedIn)
-                        {
-                            stateObj.SendAttention(mustTakeWriteLock: true);
-
-                            PacketHandle syncReadPacket = default;
-
-                            bool shouldDecrement = false;
-                            try
-                            {
-                                Interlocked.Increment(ref _readingCount);
-                                shouldDecrement = true;
-
-                                syncReadPacket = ReadSyncOverAsync(stateObj.GetTimeoutRemaining(), out error);
-
-                                Interlocked.Decrement(ref _readingCount);
-                                shouldDecrement = false;
-
-                                if (TdsEnums.SNI_SUCCESS == error)
-                                {
-                                    // We will end up letting the run method deal with the expected done:done_attn token stream.
-                                    stateObj.ProcessSniPacket(syncReadPacket, 0);
-                                    return;
-                                }
-                                else
-                                {
-                                    Debug.Assert(!IsValidPacket(syncReadPacket), "unexpected syncReadPacket without corresponding SNIPacketRelease");
-                                    fail = true; // Subsequent read failed, time to give up.
-                                }
-                            }
-                            finally
-                            {
-                                if (shouldDecrement)
-                                {
-                                    Interlocked.Decrement(ref _readingCount);
-                                }
-
-                                if (!IsPacketEmpty(syncReadPacket))
-                                {
-                                    ReleasePacket(syncReadPacket);
-                                }
-                            }
-                        }
-                        else
-                        {
-                            if (_parser._loginWithFailover)
-                            {
-                                // For DbMirroring Failover during login, never break the connection, just close the TdsParser
-                                _parser.Disconnect();
-                            }
-                            else if ((_parser.State == TdsParserState.OpenNotLoggedIn) && (_parser.Connection.ConnectionOptions.MultiSubnetFailover))
-                            {
-                                // For MultiSubnet Failover during login, never break the connection, just close the TdsParser
-                                _parser.Disconnect();
-                            }
-                            else
-                                fail = true; // We aren't yet logged in - just fail.
-                        }
-                    }
-                }
-
-                if (fail)
-                {
-                    _parser.State = TdsParserState.Broken; // We failed subsequent read, we have to quit!
-                    _parser.Connection.BreakConnection();
-                }
-            }
-            else
-            {
-                // Caution: ProcessSNIError  always  returns a fatal error!
-                AddError(_parser.ProcessSNIError(stateObj));
-            }
-            ThrowExceptionAndWarning();
-
-            AssertValidState();
-        }
-
-        public void ProcessSniPacket(PacketHandle packet, uint error)
-        {
-            if (error != 0)
-            {
-                if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
-                {
-                    // Do nothing with callback if closed or broken and error not 0 - callback can occur
-                    // after connection has been closed.  PROBLEM IN NETLIB - DESIGN FLAW.
-                    return;
-                }
-
-                AddError(_parser.ProcessSNIError(this));
-                AssertValidState();
-            }
-            else
-            {
-                uint dataSize = 0;
-
-                uint getDataError = SNIPacketGetData(packet, _inBuff, ref dataSize);
-
-                if (getDataError == TdsEnums.SNI_SUCCESS)
-                {
-                    if (_inBuff.Length < dataSize)
-                    {
-                        Debug.Assert(true, "Unexpected dataSize on Read");
-                        throw SQL.InvalidInternalPacketSize(SR.GetString(SR.SqlMisc_InvalidArraySizeMessage));
-                    }
-
-                    _lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
-                    _inBytesRead = (int)dataSize;
-                    _inBytesUsed = 0;
-
-                    if (_snapshot != null)
-                    {
-                        _snapshot.PushBuffer(_inBuff, _inBytesRead);
-                        if (_snapshotReplay)
-                        {
-                            _snapshot.Replay();
-#if DEBUG
-                            _snapshot.AssertCurrent();
-#endif
-                        }
-                    }
-
-                    SniReadStatisticsAndTracing();
-
-
-                    AssertValidState();
-                }
-                else
-                {
-                    throw SQL.ParsingError();
-                }
-            }
-        }
-
-        private void ChangeNetworkPacketTimeout(int dueTime, int period)
-        {
-            Timer networkPacketTimeout = _networkPacketTimeout;
-            if (networkPacketTimeout != null)
-            {
-                try
-                {
-                    networkPacketTimeout.Change(dueTime, period);
-                }
-                catch (ObjectDisposedException)
-                {
-                    // _networkPacketTimeout is set to null before Disposing, but there is still a slight chance
-                    // that object was disposed after we took a copy
-                }
-            }
-        }
-
-        private void SetBufferSecureStrings()
-        {
-            if (_securePasswords != null)
-            {
-                for (int i = 0; i < _securePasswords.Length; i++)
-                {
-                    if (_securePasswords[i] != null)
-                    {
-                        IntPtr str = IntPtr.Zero;
-                        try
-                        {
-                            str = Marshal.SecureStringToBSTR(_securePasswords[i]);
-                            byte[] data = new byte[_securePasswords[i].Length * 2];
-                            Marshal.Copy(str, data, 0, _securePasswords[i].Length * 2);
-                            TdsParserStaticMethods.ObfuscatePassword(data);
-                            data.CopyTo(_outBuff, _securePasswordOffsetsInBuffer[i]);
-                        }
-                        finally
-                        {
-                            Marshal.ZeroFreeBSTR(str);
-                        }
-                    }
-                }
-            }
-        }
-
-        public void ReadAsyncCallback(PacketHandle packet, uint error)
-        {
-            ReadAsyncCallback(IntPtr.Zero, packet, error);
-        }
-
-        public void ReadAsyncCallback(IntPtr key, PacketHandle packet, uint error)
-        {
-            // Key never used.
-            // Note - it's possible that when native calls managed that an asynchronous exception
-            // could occur in the native->managed transition, which would
-            // have two impacts:
-            // 1) user event not called
-            // 2) DecrementPendingCallbacks not called, which would mean this object would be leaked due
-            //    to the outstanding GCRoot until AppDomain.Unload.
-            // We live with the above for the time being due to the constraints of the current
-            // reliability infrastructure provided by the CLR.
-
-            TaskCompletionSource<object> source = _networkPacketTaskSource;
-#if DEBUG
-            if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null))
-            {
-                source = _realNetworkPacketTaskSource;
-            }
-#endif
-
-            // The mars physical connection can get a callback
-            // with a packet but no result after the connection is closed.
-            if (source == null && _parser._pMarsPhysicalConObj == this)
-            {
-                return;
-            }
-
-            bool processFinallyBlock = true;
-            try
-            {
-                Debug.Assert(CheckPacket(packet, source) && source != null, "AsyncResult null on callback");
-
-                if (_parser.MARSOn)
-                { // Only take reset lock on MARS and Async.
-                    CheckSetResetConnectionState(error, CallbackType.Read);
-                }
-
-                ChangeNetworkPacketTimeout(Timeout.Infinite, Timeout.Infinite);
-
-                ProcessSniPacket(packet, error);
-            }
-            catch (Exception e)
-            {
-                processFinallyBlock = ADP.IsCatchableExceptionType(e);
-                throw;
-            }
-            finally
-            {
-                // pendingCallbacks may be 2 after decrementing, this indicates that a fatal timeout is occurring, and therefore we shouldn't complete the task
-                int pendingCallbacks = DecrementPendingCallbacks(false); // may dispose of GC handle.
-                if ((processFinallyBlock) && (source != null) && (pendingCallbacks < 2))
-                {
-                    if (error == 0)
-                    {
-                        if (_executionContext != null)
-                        {
-                            ExecutionContext.Run(_executionContext, (state) => source.TrySetResult(null), null);
-                        }
-                        else
-                        {
-                            source.TrySetResult(null);
-                        }
-                    }
-                    else
-                    {
-                        if (_executionContext != null)
-                        {
-                            ExecutionContext.Run(_executionContext, (state) => ReadAsyncCallbackCaptureException(source), null);
-                        }
-                        else
-                        {
-                            ReadAsyncCallbackCaptureException(source);
-                        }
-                    }
-                }
-
-                AssertValidState();
-            }
-        }
-
-        protected abstract bool CheckPacket(PacketHandle packet, TaskCompletionSource<object> source);
-
-        private void ReadAsyncCallbackCaptureException(TaskCompletionSource<object> source)
-        {
-            bool captureSuccess = false;
-            try
-            {
-                if (_hasErrorOrWarning)
-                {
-                    // Do the close on another thread, since we don't want to block the callback thread
-                    ThrowExceptionAndWarning(asyncClose: true);
-                }
-                else if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
-                {
-                    // Connection was closed by another thread before we parsed the packet, so no error was added to the collection
-                    throw ADP.ClosedConnectionError();
-                }
-            }
-            catch (Exception ex)
-            {
-                if (source.TrySetException(ex))
-                {
-                    // There was an exception, and it was successfully stored in the task
-                    captureSuccess = true;
-                }
-            }
-
-            if (!captureSuccess)
-            {
-                // Either there was no exception, or the task was already completed
-                // This is unusual, but possible if a fatal timeout occurred on another thread (which should mean that the connection is now broken)
-                Debug.Assert(_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed || _parser.Connection.IsConnectionDoomed, "Failed to capture exception while the connection was still healthy");
-
-                // The safest thing to do is to ensure that the connection is broken and attempt to cancel the task
-                // This must be done from another thread to not block the callback thread
-                Task.Run(() =>
-                {
-                    _parser.State = TdsParserState.Broken;
-                    _parser.Connection.BreakConnection();
-                    source.TrySetCanceled();
-                });
-            }
-        }
-
-        public void WriteAsyncCallback(PacketHandle packet, uint sniError)
-        {
-            WriteAsyncCallback(IntPtr.Zero, packet, sniError);
-        }
-
-        public void WriteAsyncCallback(IntPtr key, PacketHandle packet, uint sniError)
-        { // Key never used.
-            RemovePacketFromPendingList(packet);
-            try
-            {
-                if (sniError != TdsEnums.SNI_SUCCESS)
-                {
-                    try
-                    {
-                        AddError(_parser.ProcessSNIError(this));
-                        ThrowExceptionAndWarning(asyncClose: true);
-                    }
-                    catch (Exception e)
-                    {
-                        var writeCompletionSource = _writeCompletionSource;
-                        if (writeCompletionSource != null)
-                        {
-                            writeCompletionSource.TrySetException(e);
-                        }
-                        else
-                        {
-                            _delayedWriteAsyncCallbackException = e;
-
-                            // Ensure that _delayedWriteAsyncCallbackException is set before checking _writeCompletionSource
-                            Interlocked.MemoryBarrier();
-
-                            // Double check that _writeCompletionSource hasn't been created in the meantime
-                            writeCompletionSource = _writeCompletionSource;
-                            if (writeCompletionSource != null)
-                            {
-                                var delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
-                                if (delayedException != null)
-                                {
-                                    writeCompletionSource.TrySetException(delayedException);
-                                }
-                            }
-                        }
-
-                        return;
-                    }
-                }
-                else
-                {
-                    _lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
-                }
-            }
-            finally
-            {
-#if DEBUG
-                if (SqlCommand.DebugForceAsyncWriteDelay > 0)
-                {
-                    new Timer(obj =>
-                    {
-                        Interlocked.Decrement(ref _asyncWriteCount);
-                        var writeCompletionSource = _writeCompletionSource;
-                        if (_asyncWriteCount == 0 && writeCompletionSource != null)
-                        {
-                            writeCompletionSource.TrySetResult(null);
-                        }
-                    }, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite);
-                }
-                else
-                {
-#else
-                {
-#endif
-                    Interlocked.Decrement(ref _asyncWriteCount);
-                }
-            }
-#if DEBUG
-            if (SqlCommand.DebugForceAsyncWriteDelay > 0)
-            {
-                return;
-            }
-#endif
-            var completionSource = _writeCompletionSource;
-            if (_asyncWriteCount == 0 && completionSource != null)
-            {
-                completionSource.TrySetResult(null);
-            }
-        }
-
-        /////////////////////////////////////////
-        // Network/Packet Writing & Processing //
-        /////////////////////////////////////////
-
-        internal void WriteSecureString(SecureString secureString)
-        {
-            Debug.Assert(_securePasswords[0] == null || _securePasswords[1] == null, "There are more than two secure passwords");
-
-            int index = _securePasswords[0] != null ? 1 : 0;
-
-            _securePasswords[index] = secureString;
-            _securePasswordOffsetsInBuffer[index] = _outBytesUsed;
-
-            // loop through and write the entire array
-            int lengthInBytes = secureString.Length * 2;
-
-            // It is guaranteed both secure password and secure change password should fit into the first packet
-            // Given current TDS format and implementation it is not possible that one of secure string is the last item and exactly fill up the output buffer
-            //  if this ever happens and it is correct situation, the packet needs to be written out after _outBytesUsed is update
-            Debug.Assert((_outBytesUsed + lengthInBytes) < _outBuff.Length, "Passwords cannot be splited into two different packet or the last item which fully fill up _outBuff!!!");
-
-            _outBytesUsed += lengthInBytes;
-        }
-
-        internal void ResetSecurePasswordsInformation()
-        {
-            for (int i = 0; i < _securePasswords.Length; ++i)
-            {
-                _securePasswords[i] = null;
-                _securePasswordOffsetsInBuffer[i] = 0;
-            }
-        }
-
-        internal Task WaitForAccumulatedWrites()
-        {
-            // Checked for stored exceptions
-            var delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
-            if (delayedException != null)
-            {
-                throw delayedException;
-            }
-
-            if (_asyncWriteCount == 0)
-            {
-                return null;
-            }
-
-            _writeCompletionSource = new TaskCompletionSource<object>();
-            Task task = _writeCompletionSource.Task;
-
-            // Ensure that _writeCompletionSource is set before checking state
-            Interlocked.MemoryBarrier();
-
-            // Now that we have set _writeCompletionSource, check if parser is closed or broken
-            if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
-            {
-                throw ADP.ClosedConnectionError();
-            }
-
-            // Check for stored exceptions
-            delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
-            if (delayedException != null)
-            {
-                throw delayedException;
-            }
-
-            // If there are no outstanding writes, see if we can shortcut and return null
-            if ((_asyncWriteCount == 0) && ((!task.IsCompleted) || (task.Exception == null)))
-            {
-                task = null;
-            }
-
-            return task;
-        }
-
-        // Takes in a single byte and writes it to the buffer.  If the buffer is full, it is flushed
-        // and then the buffer is re-initialized in flush() and then the byte is put in the buffer.
-        internal void WriteByte(byte b)
-        {
-            Debug.Assert(_outBytesUsed <= _outBuff.Length, "ERROR - TDSParser: _outBytesUsed > _outBuff.Length");
-
-            // check to make sure we haven't used the full amount of space available in the buffer, if so, flush it
-            if (_outBytesUsed == _outBuff.Length)
-            {
-                WritePacket(TdsEnums.SOFTFLUSH, canAccumulate: true);
-            }
-            // set byte in buffer and increment the counter for number of bytes used in the out buffer
-            _outBuff[_outBytesUsed++] = b;
-        }
-
-
-        internal Task WriteByteSpan(ReadOnlySpan<byte> span, bool canAccumulate = true, TaskCompletionSource<object> completion = null)
-        {
-            return WriteBytes(span, span.Length, 0, canAccumulate, completion);
-        }
-
-        internal Task WriteByteArray(byte[] b, int len, int offsetBuffer, bool canAccumulate = true, TaskCompletionSource<object> completion = null)
-        {
-            return WriteBytes(ReadOnlySpan<byte>.Empty, len, offsetBuffer, canAccumulate, completion, b);
-        }
-
-        //
-        // Takes a span or a byte array and writes it to the buffer
-        // If you pass in a span and a null array then the span wil be used.
-        // If you pass in a non-null array then the array will be used and the span is ignored.
-        // if the span cannot be written into the current packet then the remaining contents of the span are copied to a
-        //  new heap allocated array that will used to callback into the method to continue the write operation.
-        private Task WriteBytes(ReadOnlySpan<byte> b, int len, int offsetBuffer, bool canAccumulate = true, TaskCompletionSource<object> completion = null, byte[] array = null)
-        {
-            if (array != null)
-            {
-                b = new ReadOnlySpan<byte>(array, offsetBuffer, len);
-            }
-            try
-            {
-                bool async = _parser._asyncWrite;  // NOTE: We are capturing this now for the assert after the Task is returned, since WritePacket will turn off async if there is an exception
-                Debug.Assert(async || _asyncWriteCount == 0);
-                // Do we have to send out in packet size chunks, or can we rely on netlib layer to break it up?
-                // would prefer to do something like:
-                //
-                // if (len > what we have room for || len > out buf)
-                //   flush buffer
-                //   UnsafeNativeMethods.Write(b)
-                //
-
-                int offset = offsetBuffer;
-
-                Debug.Assert(b.Length >= len, "Invalid length sent to WriteBytes()!");
-
-                // loop through and write the entire array
-                do
-                {
-                    if ((_outBytesUsed + len) > _outBuff.Length)
-                    {
-                        // If the remainder of the data won't fit into the buffer, then we have to put
-                        // whatever we can into the buffer, and flush that so we can then put more into
-                        // the buffer on the next loop of the while.
-
-                        int remainder = _outBuff.Length - _outBytesUsed;
-
-                        // write the remainder
-                        Span<byte> copyTo = _outBuff.AsSpan(_outBytesUsed, remainder);
-                        ReadOnlySpan<byte> copyFrom = b.Slice(0, remainder);
-
-                        Debug.Assert(copyTo.Length == copyFrom.Length, $"copyTo.Length:{copyTo.Length} and copyFrom.Length{copyFrom.Length:D} should be the same");
-
-                        copyFrom.CopyTo(copyTo);
-
-                        offset += remainder;
-                        _outBytesUsed += remainder;
-                        len -= remainder;
-                        b = b.Slice(remainder, len);
-
-                        Task packetTask = WritePacket(TdsEnums.SOFTFLUSH, canAccumulate);
-
-                        if (packetTask != null)
-                        {
-                            Task task = null;
-                            Debug.Assert(async, "Returned task in sync mode");
-                            if (completion == null)
-                            {
-                                completion = new TaskCompletionSource<object>();
-                                task = completion.Task; // we only care about return from topmost call, so do not access Task property in other cases
-                            }
-
-                            if (array == null)
-                            {
-                                byte[] tempArray = new byte[len];
-                                Span<byte> copyTempTo = tempArray.AsSpan();
-
-                                Debug.Assert(copyTempTo.Length == b.Length, $"copyTempTo.Length:{copyTempTo.Length} and copyTempFrom.Length:{b.Length:D} should be the same");
-
-                                b.CopyTo(copyTempTo);
-                                array = tempArray;
-                                offset = 0;
-                            }
-
-                            WriteBytesSetupContinuation(array, len, completion, offset, packetTask);
-                            return task;
-                        }
-                    }
-                    else
-                    {
-                        //((stateObj._outBytesUsed + len) <= stateObj._outBuff.Length )
-                        // Else the remainder of the string will fit into the buffer, so copy it into the
-                        // buffer and then break out of the loop.
-
-                        Span<byte> copyTo = _outBuff.AsSpan(_outBytesUsed, len);
-                        ReadOnlySpan<byte> copyFrom = b.Slice(0, len);
-
-                        Debug.Assert(copyTo.Length == copyFrom.Length, $"copyTo.Length:{copyTo.Length} and copyFrom.Length:{copyFrom.Length:D} should be the same");
-
-                        copyFrom.CopyTo(copyTo);
-
-                        // handle out buffer bytes used counter
-                        _outBytesUsed += len;
-                        break;
-                    }
-                } while (len > 0);
-
-                if (completion != null)
-                {
-                    completion.SetResult(null);
-                }
-                return null;
-            }
-            catch (Exception e)
-            {
-                if (completion != null)
-                {
-                    completion.SetException(e);
-                    return null;
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        // This is in its own method to avoid always allocating the lambda in WriteBytes
-        private void WriteBytesSetupContinuation(byte[] array, int len, TaskCompletionSource<object> completion, int offset, Task packetTask)
-        {
-            AsyncHelper.ContinueTask(packetTask, completion,
-                onSuccess: () => WriteBytes(ReadOnlySpan<byte>.Empty, len: len, offsetBuffer: offset, canAccumulate: false, completion: completion, array)
-            );
-        }
-
-        // Dumps contents of buffer to SNI for network write.
-        internal Task WritePacket(byte flushMode, bool canAccumulate = false)
-        {
-            TdsParserState state = _parser.State;
-            if ((state == TdsParserState.Closed) || (state == TdsParserState.Broken))
-            {
-                throw ADP.ClosedConnectionError();
-            }
-
-            if (
-                // This appears to be an optimization to avoid writing empty packets in Yukon
-                // However, since we don't know the version prior to login IsYukonOrNewer was always false prior to login
-                // So removing the IsYukonOrNewer check causes issues since the login packet happens to meet the rest of the conditions below
-                // So we need to avoid this check prior to login completing
-                state == TdsParserState.OpenLoggedIn &&
-                !_bulkCopyOpperationInProgress && // ignore the condition checking for bulk copy
-                    _outBytesUsed == (_outputHeaderLen + BitConverter.ToInt32(_outBuff, _outputHeaderLen))
-                    && _outputPacketCount == 0
-                || _outBytesUsed == _outputHeaderLen
-                    && _outputPacketCount == 0)
-            {
-                return null;
-            }
-
-            byte status;
-            byte packetNumber = _outputPacketNumber;
-
-            // Set Status byte based whether this is end of message or not
-            bool willCancel = (_cancelled) && (_parser._asyncWrite);
-            if (willCancel)
-            {
-                status = TdsEnums.ST_EOM | TdsEnums.ST_IGNORE;
-                ResetPacketCounters();
-            }
-            else if (TdsEnums.HARDFLUSH == flushMode)
-            {
-                status = TdsEnums.ST_EOM;
-                ResetPacketCounters();
-            }
-            else if (TdsEnums.SOFTFLUSH == flushMode)
-            {
-                status = TdsEnums.ST_BATCH;
-                _outputPacketNumber++;
-                _outputPacketCount++;
-            }
-            else
-            {
-                status = TdsEnums.ST_EOM;
-                Debug.Fail($"Unexpected argument {flushMode,-2:x2} to WritePacket");
-            }
-
-            _outBuff[0] = _outputMessageType;         // Message Type
-            _outBuff[1] = status;
-            _outBuff[2] = (byte)(_outBytesUsed >> 8); // length - upper byte
-            _outBuff[3] = (byte)(_outBytesUsed & 0xff); // length - lower byte
-            _outBuff[4] = 0;                          // channel
-            _outBuff[5] = 0;
-            _outBuff[6] = packetNumber;               // packet
-            _outBuff[7] = 0;                          // window
-
-            Task task = null;
-            _parser.CheckResetConnection(this);       // HAS SIDE EFFECTS - re-org at a later time if possible
-
-            task = WriteSni(canAccumulate);
-            AssertValidState();
-
-            if (willCancel)
-            {
-                // If we have been cancelled, then ensure that we write the ATTN packet as well
-                task = AsyncHelper.CreateContinuationTask(task, CancelWritePacket);
-            }
-
-            return task;
-        }
-
-        private void CancelWritePacket()
-        {
-            Debug.Assert(_cancelled, "Should not call CancelWritePacket if _cancelled is not set");
-
-            _parser.Connection.ThreadHasParserLockForClose = true;      // In case of error, let the connection know that we are holding the lock
-            try
-            {
-                // Send the attention and wait for the ATTN_ACK
-                SendAttention();
-                ResetCancelAndProcessAttention();
-
-                // Let the caller know that we've given up
-                throw SQL.OperationCancelled();
-            }
-            finally
-            {
-                _parser.Connection.ThreadHasParserLockForClose = false;
-            }
-        }
-
-        private Task SNIWritePacket(PacketHandle packet, out uint sniError, bool canAccumulate, bool callerHasConnectionLock)
-        {
-            // Check for a stored exception
-            var delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
-            if (delayedException != null)
-            {
-                throw delayedException;
-            }
-
-            Task task = null;
-            _writeCompletionSource = null;
-
-            PacketHandle packetPointer = EmptyReadPacket;
-
-            bool sync = !_parser._asyncWrite;
-            if (sync && _asyncWriteCount > 0)
-            { // for example, SendAttention while there are writes pending
-                Task waitForWrites = WaitForAccumulatedWrites();
-                if (waitForWrites != null)
-                {
-                    try
-                    {
-                        waitForWrites.Wait();
-                    }
-                    catch (AggregateException ae)
-                    {
-                        throw ae.InnerException;
-                    }
-                }
-                Debug.Assert(_asyncWriteCount == 0, "All async write should be finished");
-            }
-            if (!sync)
-            {
-                // Add packet to the pending list (since the callback can happen any time after we call SNIWritePacket)
-                packetPointer = AddPacketToPendingList(packet);
-            }
-
-            // Async operation completion may be delayed (success pending).
-            try
-            {
-            }
-            finally
-            {
-                sniError = WritePacket(packet, sync);
-            }
-
-            if (sniError == TdsEnums.SNI_SUCCESS_IO_PENDING)
-            {
-                Debug.Assert(!sync, "Completion should be handled in SniManagedWwrapper");
-                Interlocked.Increment(ref _asyncWriteCount);
-                Debug.Assert(_asyncWriteCount >= 0);
-                if (!canAccumulate)
-                {
-                    // Create completion source (for callback to complete)
-                    _writeCompletionSource = new TaskCompletionSource<object>();
-                    task = _writeCompletionSource.Task;
-
-                    // Ensure that setting _writeCompletionSource completes before checking _delayedWriteAsyncCallbackException
-                    Interlocked.MemoryBarrier();
-
-                    // Check for a stored exception
-                    delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
-                    if (delayedException != null)
-                    {
-                        throw delayedException;
-                    }
-
-                    // If there are no outstanding writes, see if we can shortcut and return null
-                    if ((_asyncWriteCount == 0) && ((!task.IsCompleted) || (task.Exception == null)))
-                    {
-                        task = null;
-                    }
-                }
-            }
-#if DEBUG
-            else if (!sync && !canAccumulate && SqlCommand.DebugForceAsyncWriteDelay > 0)
-            {
-                // Executed synchronously - callback will not be called
-                TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
-                uint error = sniError;
-                new Timer(obj =>
-                {
-                    try
-                    {
-                        if (_parser.MARSOn)
-                        { // Only take reset lock on MARS.
-                            CheckSetResetConnectionState(error, CallbackType.Write);
-                        }
-
-                        if (error != TdsEnums.SNI_SUCCESS)
-                        {
-                            AddError(_parser.ProcessSNIError(this));
-                            ThrowExceptionAndWarning();
-                        }
-                        AssertValidState();
-                        completion.SetResult(null);
-                    }
-                    catch (Exception e)
-                    {
-                        completion.SetException(e);
-                    }
-                }, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite);
-                task = completion.Task;
-            }
-#endif
-            else
-            {
-                if (_parser.MARSOn)
-                { // Only take reset lock on MARS.
-                    CheckSetResetConnectionState(sniError, CallbackType.Write);
-                }
-
-                if (sniError == TdsEnums.SNI_SUCCESS)
-                {
-                    _lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
-
-                    if (!sync)
-                    {
-                        // Since there will be no callback, remove the packet from the pending list
-                        Debug.Assert(IsValidPacket(packetPointer), "Packet added to list has an invalid pointer, can not remove from pending list");
-                        RemovePacketFromPendingList(packetPointer);
-                    }
-                }
-                else
-                {
-                    AddError(_parser.ProcessSNIError(this));
-                    ThrowExceptionAndWarning(callerHasConnectionLock);
-                }
-                AssertValidState();
-            }
-            return task;
-        }
-
-        internal abstract bool IsValidPacket(PacketHandle packetPointer);
-
-        internal abstract uint WritePacket(PacketHandle packet, bool sync);
-
-        // Sends an attention signal - executing thread will consume attn.
-        internal void SendAttention(bool mustTakeWriteLock = false)
-        {
-            if (!_attentionSent)
-            {
-                // Dumps contents of buffer to OOB write (currently only used for
-                // attentions.  There is no body for this message
-                // Doesn't touch this._outBytesUsed
-                if (_parser.State == TdsParserState.Closed || _parser.State == TdsParserState.Broken)
-                {
-                    return;
-                }
-
-                PacketHandle attnPacket = CreateAndSetAttentionPacket();
-
-                try
-                {
-                    // Dev11 #344723: SqlClient stress hang System_Data!Tcp::ReadSync via a call to SqlDataReader::Close
-                    // Set _attentionSending to true before sending attention and reset after setting _attentionSent
-                    // This prevents a race condition between receiving the attention ACK and setting _attentionSent
-                    _attentionSending = true;
-
-#if DEBUG
-                    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)
-                            {
-                                return;
-                            }
-
-                            uint sniError;
-                            _parser._asyncWrite = false; // stop async write
-                            SNIWritePacket(attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false);
-                        }
-                        finally
-                        {
-                            if (releaseLock)
-                            {
-                                _parser.Connection.ThreadHasParserLockForClose = false;
-                                _parser.Connection._parserLock.Release();
-                            }
-                        }
-#if DEBUG
-                    }
-#endif
-
-                    SetTimeoutSeconds(AttentionTimeoutSeconds); // Initialize new attention timeout of 5 seconds.
-                    _attentionSent = true;
-                }
-                finally
-                {
-                    _attentionSending = false;
-                }
-
-
-                AssertValidState();
-            }
-        }
-
-        internal abstract PacketHandle CreateAndSetAttentionPacket();
-
-        internal abstract void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed);
-
-        private Task WriteSni(bool canAccumulate)
-        {
-            // Prepare packet, and write to packet.
-            PacketHandle packet = GetResetWritePacket(_outBytesUsed);
-
-            SetBufferSecureStrings();
-            SetPacketData(packet, _outBuff, _outBytesUsed);
-
-            uint sniError;
-            Debug.Assert(Parser.Connection._parserLock.ThreadMayHaveLock(), "Thread is writing without taking the connection lock");
-            Task task = SNIWritePacket(packet, out sniError, canAccumulate, callerHasConnectionLock: true);
-
-            // Check to see if the timeout has occurred.  This time out code is special case code to allow BCP writes to timeout. Eventually we should make all writes timeout.
-            if (_bulkCopyOpperationInProgress && 0 == GetTimeoutRemaining())
-            {
-                _parser.Connection.ThreadHasParserLockForClose = true;
-                try
-                {
-                    Debug.Assert(_parser.Connection != null, "SqlConnectionInternalTds handler can not be null at this point.");
-                    AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, _parser.Server, _parser.Connection.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
-                    _bulkCopyWriteTimeout = true;
-                    SendAttention();
-                    _parser.ProcessPendingAck(this);
-                    ThrowExceptionAndWarning();
-                }
-                finally
-                {
-                    _parser.Connection.ThreadHasParserLockForClose = false;
-                }
-            }
-
-            // Special case logic for encryption removal.
-            if (_parser.State == TdsParserState.OpenNotLoggedIn &&
-                _parser.EncryptionOptions == EncryptionOptions.LOGIN)
-            {
-                // If no error occurred, and we are Open but not logged in, and
-                // our encryptionOption state is login, remove the SSL Provider.
-                // We only need encrypt the very first packet of the login message to the server.
-
-                // We wanted to encrypt entire login channel, but there is
-                // currently no mechanism to communicate this.  Removing encryption post 1st packet
-                // is a hard-coded agreement between client and server.  We need some mechanism or
-                // common change to be able to make this change in a non-breaking fashion.
-                _parser.RemoveEncryption();                        // Remove the SSL Provider.
-                _parser.EncryptionOptions = EncryptionOptions.OFF; // Turn encryption off.
-
-                // Since this packet was associated with encryption, dispose and re-create.
-                ClearAllWritePackets();
-            }
-
-            SniWriteStatisticsAndTracing();
-
-            ResetBuffer();
-
-            AssertValidState();
-            return task;
-        }
-
-        //////////////////////////////////////////////
-        // Statistics, Tracing, and related methods //
-        //////////////////////////////////////////////
-
-        private void SniReadStatisticsAndTracing()
-        {
-            SqlStatistics statistics = Parser.Statistics;
-            if (null != statistics)
-            {
-                if (statistics.WaitForReply)
-                {
-                    statistics.SafeIncrement(ref statistics._serverRoundtrips);
-                    statistics.ReleaseAndUpdateNetworkServerTimer();
-                }
-
-                statistics.SafeAdd(ref statistics._bytesReceived, _inBytesRead);
-                statistics.SafeIncrement(ref statistics._buffersReceived);
-            }
-        }
-
-        private void SniWriteStatisticsAndTracing()
-        {
-            SqlStatistics statistics = _parser.Statistics;
-            if (null != statistics)
-            {
-                statistics.SafeIncrement(ref statistics._buffersSent);
-                statistics.SafeAdd(ref statistics._bytesSent, _outBytesUsed);
-                statistics.RequestNetworkServerTimer();
-            }
-        }
-        [Conditional("DEBUG")]
-
-        private void AssertValidState()
-        {
-            if (_inBytesUsed < 0 || _inBytesRead < 0)
-            {
-                Debug.Fail($"Invalid TDS Parser State: either _inBytesUsed or _inBytesRead is negative: {_inBytesUsed}, {_inBytesRead}");
-            }
-            else if (_inBytesUsed > _inBytesRead)
-            {
-                Debug.Fail($"Invalid TDS Parser State: _inBytesUsed > _inBytesRead: {_inBytesUsed} > {_inBytesRead}");
-            }
-
-            Debug.Assert(_inBytesPacket >= 0, "Packet must not be negative");
-        }
-
-
-        //////////////////////////////////////////////
-        // Errors and Warnings                      //
-        //////////////////////////////////////////////
-
-        /// <summary>
-        /// True if there is at least one error or warning (not counting the pre-attention errors\warnings)
-        /// </summary>
-        internal bool HasErrorOrWarning
-        {
-            get
-            {
-                return _hasErrorOrWarning;
-            }
-        }
-
-        /// <summary>
-        /// Adds an error to the error collection
-        /// </summary>
-        /// <param name="error"></param>
-        internal void AddError(SqlError error)
-        {
-            Debug.Assert(error != null, "Trying to add a null error");
-
-            // Switch to sync once we see an error
-            _syncOverAsync = true;
-
-            lock (_errorAndWarningsLock)
-            {
-                _hasErrorOrWarning = true;
-                if (_errors == null)
-                {
-                    _errors = new SqlErrorCollection();
-                }
-                _errors.Add(error);
-            }
-        }
-
-        /// <summary>
-        /// Gets the number of errors currently in the error collection
-        /// </summary>
-        internal int ErrorCount
-        {
-            get
-            {
-                int count = 0;
-                lock (_errorAndWarningsLock)
-                {
-                    if (_errors != null)
-                    {
-                        count = _errors.Count;
-                    }
-                }
-                return count;
-            }
-        }
-
-        /// <summary>
-        /// Adds an warning to the warning collection
-        /// </summary>
-        /// <param name="error"></param>
-        internal void AddWarning(SqlError error)
-        {
-            Debug.Assert(error != null, "Trying to add a null error");
-
-            // Switch to sync once we see a warning
-            _syncOverAsync = true;
-
-            lock (_errorAndWarningsLock)
-            {
-                _hasErrorOrWarning = true;
-                if (_warnings == null)
-                {
-                    _warnings = new SqlErrorCollection();
-                }
-                _warnings.Add(error);
-            }
-        }
-
-        /// <summary>
-        /// Gets the number of warnings currently in the warning collection
-        /// </summary>
-        internal int WarningCount
-        {
-            get
-            {
-                int count = 0;
-                lock (_errorAndWarningsLock)
-                {
-                    if (_warnings != null)
-                    {
-                        count = _warnings.Count;
-                    }
-                }
-                return count;
-            }
-        }
-
-        protected abstract PacketHandle EmptyReadPacket { get; }
-
-        /// <summary>
-        /// Gets the full list of errors and warnings (including the pre-attention ones), then wipes all error and warning lists
-        /// </summary>
-        /// <param name="broken">If true, the connection should be broken</param>
-        /// <returns>An array containing all of the errors and warnings</returns>
-        internal SqlErrorCollection GetFullErrorAndWarningCollection(out bool broken)
-        {
-            SqlErrorCollection allErrors = new SqlErrorCollection();
-            broken = false;
-
-            lock (_errorAndWarningsLock)
-            {
-                _hasErrorOrWarning = false;
-
-                // Merge all error lists, then reset them
-                AddErrorsToCollection(_errors, ref allErrors, ref broken);
-                AddErrorsToCollection(_warnings, ref allErrors, ref broken);
-                _errors = null;
-                _warnings = null;
-
-                // We also process the pre-attention error lists here since, if we are here and they are populated, then an error occurred while sending attention so we should show the errors now (otherwise they'd be lost)
-                AddErrorsToCollection(_preAttentionErrors, ref allErrors, ref broken);
-                AddErrorsToCollection(_preAttentionWarnings, ref allErrors, ref broken);
-                _preAttentionErrors = null;
-                _preAttentionWarnings = null;
-            }
-
-            return allErrors;
-        }
-
-        private void AddErrorsToCollection(SqlErrorCollection inCollection, ref SqlErrorCollection collectionToAddTo, ref bool broken)
-        {
-            if (inCollection != null)
-            {
-                foreach (SqlError error in inCollection)
-                {
-                    collectionToAddTo.Add(error);
-                    broken |= (error.Class >= TdsEnums.FATAL_ERROR_CLASS);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Stores away current errors and warnings so that an attention can be processed
-        /// </summary>
-        internal void StoreErrorAndWarningForAttention()
-        {
-            lock (_errorAndWarningsLock)
-            {
-                Debug.Assert(_preAttentionErrors == null && _preAttentionWarnings == null, "Can't store errors for attention because there are already errors stored");
-
-                _hasErrorOrWarning = false;
-
-                _preAttentionErrors = _errors;
-                _preAttentionWarnings = _warnings;
-
-                _errors = null;
-                _warnings = null;
-            }
-        }
-
-        /// <summary>
-        /// Restores errors and warnings that were stored in order to process an attention
-        /// </summary>
-        internal void RestoreErrorAndWarningAfterAttention()
-        {
-            lock (_errorAndWarningsLock)
-            {
-                Debug.Assert(_errors == null && _warnings == null, "Can't restore errors after attention because there are already other errors");
-
-                _hasErrorOrWarning = (((_preAttentionErrors != null) && (_preAttentionErrors.Count > 0)) || ((_preAttentionWarnings != null) && (_preAttentionWarnings.Count > 0)));
-
-                _errors = _preAttentionErrors;
-                _warnings = _preAttentionWarnings;
-
-                _preAttentionErrors = null;
-                _preAttentionWarnings = null;
-            }
-        }
-
-        /// <summary>
-        /// Checks if an error is stored in _error and, if so, throws an error
-        /// </summary>
-        internal void CheckThrowSNIException()
-        {
-            if (HasErrorOrWarning)
-            {
-                ThrowExceptionAndWarning();
-            }
-        }
-
-        /// <summary>
-        /// Debug Only: Ensures that the TdsParserStateObject has no lingering state and can safely be re-used
-        /// </summary>
-        [Conditional("DEBUG")]
-        internal void AssertStateIsClean()
-        {
-            // If our TdsParser is closed or broken, then we don't really care about our state
-            var parser = _parser;
-            if ((parser != null) && (parser.State != TdsParserState.Closed) && (parser.State != TdsParserState.Broken))
-            {
-                // Async reads
-                Debug.Assert(_snapshot == null && !_snapshotReplay, "StateObj has leftover snapshot state");
-                Debug.Assert(!_asyncReadWithoutSnapshot, "StateObj has AsyncReadWithoutSnapshot still enabled");
-                Debug.Assert(_executionContext == null, "StateObj has a stored execution context from an async read");
-                // Async writes
-                Debug.Assert(_asyncWriteCount == 0, "StateObj still has outstanding async writes");
-                Debug.Assert(_delayedWriteAsyncCallbackException == null, "StateObj has an unobserved exceptions from an async write");
-                // Attention\Cancellation\Timeouts
-                Debug.Assert(!_attentionReceived && !_attentionSent && !_attentionSending, $"StateObj is still dealing with attention: Sent: {_attentionSent}, Received: {_attentionReceived}, Sending: {_attentionSending}");
-                Debug.Assert(!_cancelled, "StateObj still has cancellation set");
-                Debug.Assert(!_internalTimeout, "StateObj still has internal timeout set");
-                // Errors and Warnings
-                Debug.Assert(!_hasErrorOrWarning, "StateObj still has stored errors or warnings");
-            }
-        }
-
-#if DEBUG
-        internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait)
-        {
-            var realNetworkPacketTaskSource = _realNetworkPacketTaskSource;
-            var networkPacketTaskSource = _networkPacketTaskSource;
-
-            Debug.Assert(_forcePendingReadsToWaitForUser, "Not forcing pends to wait for user - can't force complete");
-            Debug.Assert(networkPacketTaskSource != null, "No pending read to complete");
-
-            try
-            {
-                if (realNetworkPacketTaskSource != null)
-                {
-                    // Wait for the real read to complete
-                    realNetworkPacketTaskSource.Task.Wait();
-                }
-            }
-            finally
-            {
-                if (networkPacketTaskSource != null)
-                {
-                    if (resetForcePendingReadsToWait)
-                    {
-                        _forcePendingReadsToWaitForUser = false;
-                    }
-
-                    networkPacketTaskSource.TrySetResult(null);
-                }
-            }
-        }
-
-        internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait)
-        {
-            var realNetworkPacketTaskSource = _realNetworkPacketTaskSource;
-            var networkPacketTaskSource = _networkPacketTaskSource;
-
-            Debug.Assert(_forcePendingReadsToWaitForUser, "Not forcing pends to wait for user - can't force complete");
-            Debug.Assert(networkPacketTaskSource != null, "No pending read to complete");
-
-            try
-            {
-                if (realNetworkPacketTaskSource != null)
-                {
-                    // Wait for the real read to complete
-                    realNetworkPacketTaskSource.Task.Wait();
-                }
-            }
-            finally
-            {
-                if (networkPacketTaskSource != null)
-                {
-                    if (resetForcePendingReadsToWait)
-                    {
-                        _forcePendingReadsToWaitForUser = false;
-                    }
-
-                    AddError(new SqlError(errorCode, 0x00, TdsEnums.FATAL_ERROR_CLASS, _parser.Server, string.Empty, string.Empty, 0));
-                    try
-                    {
-                        ThrowExceptionAndWarning();
-                    }
-                    catch (Exception ex)
-                    {
-                        networkPacketTaskSource.TrySetException(ex);
-                    }
-                }
-            }
-        }
-#endif
-
-        internal void CloneCleanupAltMetaDataSetArray()
-        {
-            if (_snapshot != null)
-            {
-                _snapshot.CloneCleanupAltMetaDataSetArray();
-            }
-        }
-
-        private class PacketData
-        {
-            public byte[] Buffer;
-            public int Read;
-#if DEBUG
-            public string Stack;
-#endif
-        }
-
-        private class StateSnapshot
-        {
-            private readonly List<PacketData> _snapshotInBuffs;
-            private int _snapshotInBuffCurrent = 0;
-            private int _snapshotInBytesUsed = 0;
-            private int _snapshotInBytesPacket = 0;
-            private bool _snapshotPendingData = false;
-            private bool _snapshotErrorTokenReceived = false;
-            private bool _snapshotHasOpenResult = false;
-            private bool _snapshotReceivedColumnMetadata = false;
-            private bool _snapshotAttentionReceived;
-            private byte _snapshotMessageStatus;
-
-            private NullBitmap _snapshotNullBitmapInfo;
-            private ulong _snapshotLongLen;
-            private ulong _snapshotLongLenLeft;
-            private _SqlMetaDataSet _snapshotCleanupMetaData;
-            private _SqlMetaDataSetCollection _snapshotCleanupAltMetaDataSetArray;
-
-            private readonly TdsParserStateObject _stateObj;
-
-            public StateSnapshot(TdsParserStateObject state)
-            {
-                _snapshotInBuffs = new List<PacketData>();
-                _stateObj = state;
-            }
-
-#if DEBUG
-            private int _rollingPend = 0;
-            private int _rollingPendCount = 0;
-
-            internal bool DoPend()
-            {
-                if (_failAsyncPends || !_forceAllPends)
-                {
-                    return false;
-                }
-
-                if (_rollingPendCount == _rollingPend)
-                {
-                    _rollingPend++;
-                    _rollingPendCount = 0;
-                    return true;
-                }
-
-                _rollingPendCount++;
-                return false;
-            }
-#endif
-
-            internal void CloneNullBitmapInfo()
-            {
-                if (_stateObj._nullBitmapInfo.ReferenceEquals(_snapshotNullBitmapInfo))
-                {
-                    _stateObj._nullBitmapInfo = _stateObj._nullBitmapInfo.Clone();
-                }
-            }
-
-            internal void CloneCleanupAltMetaDataSetArray()
-            {
-                if (_stateObj._cleanupAltMetaDataSetArray != null && object.ReferenceEquals(_snapshotCleanupAltMetaDataSetArray, _stateObj._cleanupAltMetaDataSetArray))
-                {
-                    _stateObj._cleanupAltMetaDataSetArray = (_SqlMetaDataSetCollection)_stateObj._cleanupAltMetaDataSetArray.Clone();
-                }
-            }
-
-            internal void PushBuffer(byte[] buffer, int read)
-            {
-                Debug.Assert(!_snapshotInBuffs.Any(b => object.ReferenceEquals(b.Buffer, buffer)));
-
-                PacketData packetData = new PacketData();
-                packetData.Buffer = buffer;
-                packetData.Read = read;
-#if DEBUG
-                packetData.Stack = _stateObj._lastStack;
-#endif
-
-                _snapshotInBuffs.Add(packetData);
-            }
-
-#if DEBUG
-            internal void AssertCurrent()
-            {
-                Debug.Assert(_snapshotInBuffCurrent == _snapshotInBuffs.Count, "Should not be reading new packets when not replaying last packet");
-            }
-            internal void CheckStack(string trace)
-            {
-                PacketData prev = _snapshotInBuffs[_snapshotInBuffCurrent - 1];
-                if (prev.Stack == null)
-                {
-                    prev.Stack = trace;
-                }
-                else
-                {
-                    Debug.Assert(_stateObj._permitReplayStackTraceToDiffer || prev.Stack.ToString() == trace.ToString(), "The stack trace on subsequent replays should be the same");
-                }
-            }
-#endif
-
-            internal bool Replay()
-            {
-                if (_snapshotInBuffCurrent < _snapshotInBuffs.Count)
-                {
-                    PacketData next = _snapshotInBuffs[_snapshotInBuffCurrent];
-                    _stateObj._inBuff = next.Buffer;
-                    _stateObj._inBytesUsed = 0;
-                    _stateObj._inBytesRead = next.Read;
-                    _snapshotInBuffCurrent++;
-                    return true;
-                }
-
-                return false;
-            }
-
-            internal void Snap()
-            {
-                _snapshotInBuffs.Clear();
-                _snapshotInBuffCurrent = 0;
-                _snapshotInBytesUsed = _stateObj._inBytesUsed;
-                _snapshotInBytesPacket = _stateObj._inBytesPacket;
-                _snapshotPendingData = _stateObj._pendingData;
-                _snapshotErrorTokenReceived = _stateObj._errorTokenReceived;
-                _snapshotMessageStatus = _stateObj._messageStatus;
-                // _nullBitmapInfo must be cloned before it is updated
-                _snapshotNullBitmapInfo = _stateObj._nullBitmapInfo;
-                _snapshotLongLen = _stateObj._longlen;
-                _snapshotLongLenLeft = _stateObj._longlenleft;
-                _snapshotCleanupMetaData = _stateObj._cleanupMetaData;
-                // _cleanupAltMetaDataSetArray must be cloned before it is updated
-                _snapshotCleanupAltMetaDataSetArray = _stateObj._cleanupAltMetaDataSetArray;
-                _snapshotHasOpenResult = _stateObj._hasOpenResult;
-                _snapshotReceivedColumnMetadata = _stateObj._receivedColMetaData;
-                _snapshotAttentionReceived = _stateObj._attentionReceived;
-#if DEBUG
-                _rollingPend = 0;
-                _rollingPendCount = 0;
-                _stateObj._lastStack = null;
-                Debug.Assert(_stateObj._bTmpRead == 0, "Has partially read data when snapshot taken");
-                Debug.Assert(_stateObj._partialHeaderBytesRead == 0, "Has partially read header when snapshot taken");
-#endif
-
-                PushBuffer(_stateObj._inBuff, _stateObj._inBytesRead);
-            }
-
-            internal void ResetSnapshotState()
-            {
-                // go back to the beginning
-                _snapshotInBuffCurrent = 0;
-
-                Replay();
-
-                _stateObj._inBytesUsed = _snapshotInBytesUsed;
-                _stateObj._inBytesPacket = _snapshotInBytesPacket;
-                _stateObj._pendingData = _snapshotPendingData;
-                _stateObj._errorTokenReceived = _snapshotErrorTokenReceived;
-                _stateObj._messageStatus = _snapshotMessageStatus;
-                _stateObj._nullBitmapInfo = _snapshotNullBitmapInfo;
-                _stateObj._cleanupMetaData = _snapshotCleanupMetaData;
-                _stateObj._cleanupAltMetaDataSetArray = _snapshotCleanupAltMetaDataSetArray;
-                _stateObj._hasOpenResult = _snapshotHasOpenResult;
-                _stateObj._receivedColMetaData = _snapshotReceivedColumnMetadata;
-                _stateObj._attentionReceived = _snapshotAttentionReceived;
-
-                // Reset partially read state (these only need to be maintained if doing async without snapshot)
-                _stateObj._bTmpRead = 0;
-                _stateObj._partialHeaderBytesRead = 0;
-
-                // reset plp state
-                _stateObj._longlen = _snapshotLongLen;
-                _stateObj._longlenleft = _snapshotLongLenLeft;
-
-                _stateObj._snapshotReplay = true;
-
-                _stateObj.AssertValidState();
-            }
-
-            internal void PrepareReplay()
-            {
-                ResetSnapshotState();
-            }
-        }
-
-        /*
-
-        // leave this in. comes handy if you have to do Console.WriteLine style debugging ;)
-                private void DumpBuffer() {
-                    Console.WriteLine("dumping buffer");
-                    Console.WriteLine("_inBytesRead = {0}", _inBytesRead);
-                    Console.WriteLine("_inBytesUsed = {0}", _inBytesUsed);
-                    int cc = 0; // character counter
-                    int i;
-                    Console.WriteLine("used buffer:");
-                    for (i=0; i< _inBytesUsed; i++) {
-                        if (cc==16) {
-                            Console.WriteLine();
-                            cc = 0;
-                        }
-                        Console.Write("{0,-2:X2} ", _inBuff[i]);
-                        cc++;
-                    }
-                    if (cc>0) {
-                        Console.WriteLine();
-                    }
-
-                    cc = 0;
-                    Console.WriteLine("unused buffer:");
-                    for (i=_inBytesUsed; i<_inBytesRead; i++) {
-                        if (cc==16) {
-                            Console.WriteLine();
-                            cc = 0;
-                        }
-                        Console.Write("{0,-2:X2} ", _inBuff[i]);
-                        cc++;
-                    }
-                    if (cc>0) {
-                        Console.WriteLine();
-                    }
-                }
-        */
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectFactory.Managed.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectFactory.Managed.cs
deleted file mode 100644 (file)
index a6b9a70..0000000
+++ /dev/null
@@ -1,42 +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.Data.SqlClient.SNI;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class TdsParserStateObjectFactory
-    {
-
-        public static bool UseManagedSNI => true;
-
-        public static readonly TdsParserStateObjectFactory Singleton = new TdsParserStateObjectFactory();
-
-        public EncryptionOptions EncryptionOptions
-        {
-            get
-            {
-                return SNI.SNILoadHandle.SingletonInstance.Options;
-            }
-        }
-
-        public uint SNIStatus
-        {
-            get
-            {
-                return SNI.SNILoadHandle.SingletonInstance.Status;
-            }
-        }
-
-        public TdsParserStateObject CreateTdsParserStateObject(TdsParser parser)
-        {
-            return new TdsParserStateObjectManaged(parser);
-        }
-
-        internal TdsParserStateObject CreateSessionObject(TdsParser tdsParser, TdsParserStateObject _pMarsPhysicalConObj, bool v)
-        {
-            return new TdsParserStateObjectManaged(tdsParser, _pMarsPhysicalConObj, true);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs
deleted file mode 100644 (file)
index 2c5f4ca..0000000
+++ /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 System.Data.SqlClient.SNI;
-
-namespace System.Data.SqlClient
-{
-    internal sealed class TdsParserStateObjectFactory
-    {
-        public static readonly TdsParserStateObjectFactory Singleton = new TdsParserStateObjectFactory();
-
-        // Temporary disabling App Context switching for managed SNI.
-        // If the appcontext switch is set then Use Managed SNI based on the value. Otherwise Managed SNI should always be used.
-        //private const string UseLegacyNetworkingOnWindows = "System.Data.SqlClient.UseLegacyNetworkingOnWindows";
-        //private static bool shouldUseLegacyNetorking;
-        //public static bool UseManagedSNI { get; } = AppContext.TryGetSwitch(UseLegacyNetworkingOnWindows, out shouldUseLegacyNetorking) ? !shouldUseLegacyNetorking : true;
-
-#if DEBUG
-        private static readonly Lazy<bool> useManagedSNIOnWindows = new Lazy<bool>(
-            () => bool.TrueString.Equals(Environment.GetEnvironmentVariable("System.Data.SqlClient.UseManagedSNIOnWindows"), StringComparison.InvariantCultureIgnoreCase)
-        );
-        public static bool UseManagedSNI => useManagedSNIOnWindows.Value;
-#else
-        public static bool UseManagedSNI { get; } = false;
-#endif
-
-        public EncryptionOptions EncryptionOptions
-        {
-            get
-            {
-                return UseManagedSNI ? SNI.SNILoadHandle.SingletonInstance.Options : SNILoadHandle.SingletonInstance.Options;
-            }
-        }
-
-        public uint SNIStatus
-        {
-            get
-            {
-                return UseManagedSNI ? SNI.SNILoadHandle.SingletonInstance.Status : SNILoadHandle.SingletonInstance.Status;
-            }
-        }
-
-        public TdsParserStateObject CreateTdsParserStateObject(TdsParser parser)
-        {
-            if (UseManagedSNI)
-            {
-                return new TdsParserStateObjectManaged(parser);
-            }
-            else
-            {
-                return new TdsParserStateObjectNative(parser);
-            }
-        }
-
-        internal TdsParserStateObject CreateSessionObject(TdsParser tdsParser, TdsParserStateObject _pMarsPhysicalConObj, bool v)
-        {
-            if (TdsParserStateObjectFactory.UseManagedSNI)
-            {
-                return new TdsParserStateObjectManaged(tdsParser, _pMarsPhysicalConObj, true);
-            }
-            else
-            {
-                return new TdsParserStateObjectNative(tdsParser, _pMarsPhysicalConObj, true);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectManaged.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectManaged.cs
deleted file mode 100644 (file)
index 8ebe124..0000000
+++ /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.Collections.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.SNI
-{
-    internal class TdsParserStateObjectManaged : TdsParserStateObject
-    {
-        private SNIMarsConnection _marsConnection;
-        private SNIHandle _sessionHandle;
-        private SspiClientContextStatus _sspiClientContextStatus;
-
-        public TdsParserStateObjectManaged(TdsParser parser) : base(parser) { }
-
-        internal TdsParserStateObjectManaged(TdsParser parser, TdsParserStateObject physicalConnection, bool async) :
-            base(parser, physicalConnection, async)
-        { }
-
-        internal SNIHandle Handle => _sessionHandle;
-
-        internal override uint Status => _sessionHandle != null ? _sessionHandle.Status : TdsEnums.SNI_UNINITIALIZED;
-
-        internal override SessionHandle SessionHandle => SessionHandle.FromManagedSession(_sessionHandle);
-
-        protected override bool CheckPacket(PacketHandle packet, TaskCompletionSource<object> source)
-        {
-            SNIPacket p = packet.ManagedPacket;
-            return p.IsInvalid || source != null;
-        }
-
-        protected override void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async)
-        {
-            Debug.Assert(physicalConnection is TdsParserStateObjectManaged, "Expected a stateObject of type " + this.GetType());
-            TdsParserStateObjectManaged managedSNIObject = physicalConnection as TdsParserStateObjectManaged;
-
-            _sessionHandle = managedSNIObject.CreateMarsSession(this, async);
-        }
-
-        internal SNIMarsHandle CreateMarsSession(object callbackObject, bool async)
-        {
-            return _marsConnection.CreateMarsSession(callbackObject, async);
-        }
-
-        protected override uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize) => SNIProxy.Singleton.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, bool isIntegratedSecurity)
-        {
-            _sessionHandle = SNIProxy.Singleton.CreateConnectionHandle(this, serverName, ignoreSniOpenTimeout, timerExpire, out instanceName, ref spnBuffer, flushCache, async, parallel, isIntegratedSecurity);
-            if (_sessionHandle == null)
-            {
-                _parser.ProcessSNIError(this);
-            }
-            else if (async)
-            {
-                // Create call backs and allocate to the session handle
-                SNIAsyncCallback ReceiveAsyncCallbackDispatcher = new SNIAsyncCallback(ReadAsyncCallback);
-                SNIAsyncCallback SendAsyncCallbackDispatcher = new SNIAsyncCallback(WriteAsyncCallback);
-                _sessionHandle.SetAsyncCallbacks(ReceiveAsyncCallbackDispatcher, SendAsyncCallbackDispatcher);
-            }
-        }
-
-        internal void ReadAsyncCallback(SNIPacket packet, uint error) => ReadAsyncCallback(IntPtr.Zero, PacketHandle.FromManagedPacket(packet), error);
-
-        internal void WriteAsyncCallback(SNIPacket packet, uint sniError) => WriteAsyncCallback(IntPtr.Zero, PacketHandle.FromManagedPacket(packet), sniError);
-
-        protected override void RemovePacketFromPendingList(PacketHandle packet)
-        {
-            // No-Op
-        }
-
-        internal override void Dispose()
-        {
-            SNIHandle sessionHandle = _sessionHandle;
-
-            _sessionHandle = null;
-            _marsConnection = null;
-
-            DisposeCounters();
-
-            if (sessionHandle != null)
-            {
-                sessionHandle.Dispose();
-                DecrementPendingCallbacks(true); // Will dispose of GC handle.
-            }
-
-            DisposePacketCache();
-        }
-
-        internal override void DisposePacketCache()
-        {
-
-        }
-
-        protected override void FreeGcHandle(int remaining, bool release)
-        {
-            // No - op
-        }
-
-        internal override bool IsFailedHandle() => _sessionHandle.Status != TdsEnums.SNI_SUCCESS;
-
-        internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error)
-        {
-            SNIHandle handle = Handle;
-            if (handle == null)
-            {
-                throw ADP.ClosedConnectionError();
-            }
-            SNIPacket packet = null;
-            error = SNIProxy.Singleton.ReadSyncOverAsync(handle, out packet, timeoutRemaining);
-            return PacketHandle.FromManagedPacket(packet);
-        }
-
-        protected override PacketHandle EmptyReadPacket => PacketHandle.FromManagedPacket(null);
-
-        internal override bool IsPacketEmpty(PacketHandle packet)
-        {
-            return packet.ManagedPacket == null;
-        }
-
-        internal override void ReleasePacket(PacketHandle syncReadPacket)
-        {
-            syncReadPacket.ManagedPacket?.Release();
-        }
-
-        internal override uint CheckConnection()
-        {
-            SNIHandle handle = Handle;
-            return handle == null ? TdsEnums.SNI_SUCCESS : SNIProxy.Singleton.CheckConnection(handle);
-        }
-
-        internal override PacketHandle ReadAsync(SessionHandle handle, out uint error)
-        {
-            SNIPacket packet;
-            error = SNIProxy.Singleton.ReadAsync(handle.ManagedHandle, out packet);
-            return PacketHandle.FromManagedPacket(packet);
-        }
-
-        internal override PacketHandle CreateAndSetAttentionPacket()
-        {
-            PacketHandle packetHandle = GetResetWritePacket(TdsEnums.HEADER_LEN);
-            SetPacketData(packetHandle, SQL.AttentionHeader, TdsEnums.HEADER_LEN);
-            return packetHandle;
-        }
-
-        internal override uint WritePacket(PacketHandle packet, bool sync)
-        {
-            return SNIProxy.Singleton.WritePacket(Handle, packet.ManagedPacket, sync);
-        }
-
-        internal override PacketHandle AddPacketToPendingList(PacketHandle packet)
-        {
-            // No-Op
-            return packet;
-        }
-
-        internal override bool IsValidPacket(PacketHandle packet)
-        {
-            Debug.Assert(packet.Type == PacketHandle.ManagedPacketType, "unexpected packet type when requiring ManagedPacket");
-            return (
-                packet.Type == PacketHandle.ManagedPacketType &&
-                packet.ManagedPacket != null &&
-                !packet.ManagedPacket.IsInvalid
-            );
-        }
-
-        internal override PacketHandle GetResetWritePacket(int dataSize)
-        {
-            var packet = new SNIPacket(headerSize: _sessionHandle.ReserveHeaderSize, dataSize: dataSize);
-            Debug.Assert(packet.ReservedHeaderSize == _sessionHandle.ReserveHeaderSize, "failed to reserve header");
-            return PacketHandle.FromManagedPacket(packet);
-        }
-
-        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 uint SniGetConnectionId(ref Guid clientConnectionId) => SNIProxy.Singleton.GetConnectionId(Handle, ref clientConnectionId);
-
-        internal override uint DisabeSsl() => SNIProxy.Singleton.DisableSsl(Handle);
-
-        internal override uint EnableMars(ref uint info)
-        {
-            _marsConnection = new SNIMarsConnection(Handle);
-            if (_marsConnection.StartReceive() == TdsEnums.SNI_SUCCESS_IO_PENDING)
-            {
-                return TdsEnums.SNI_SUCCESS;
-            }
-
-            return TdsEnums.SNI_ERROR;
-        }
-
-        internal override uint EnableSsl(ref uint info) => SNIProxy.Singleton.EnableSsl(Handle, info);
-
-        internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) => SNIProxy.Singleton.SetConnectionBufferSize(Handle, unsignedPacketSize);
-
-        internal override uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer)
-        {
-            if (_sspiClientContextStatus == null)
-            {
-                _sspiClientContextStatus = new SspiClientContextStatus();
-            }
-            SNIProxy.Singleton.GenSspiClientContext(_sspiClientContextStatus, receivedBuff, ref sendBuff, _sniSpnBuffer);
-            sendLength = (uint)(sendBuff != null ? sendBuff.Length : 0);
-            return 0;
-        }
-
-        internal override uint WaitForSSLHandShakeToComplete() => 0;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectNative.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectNative.cs
deleted file mode 100644 (file)
index a6c8688..0000000
+++ /dev/null
@@ -1,386 +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.Generic;
-using System.Data.Common;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient
-{
-    internal class TdsParserStateObjectNative : TdsParserStateObject
-    {
-        private SNIHandle _sessionHandle = null;              // the SNI handle we're to work on
-
-        private SNIPacket _sniPacket = null;                // Will have to re-vamp this for MARS
-        internal SNIPacket _sniAsyncAttnPacket = null;                // Packet to use to send Attn
-        private readonly WritePacketCache _writePacketCache = new WritePacketCache(); // Store write packets that are ready to be re-used
-
-        public TdsParserStateObjectNative(TdsParser parser) : base(parser) { }
-
-        private GCHandle _gcHandle;                                    // keeps this object alive until we're closed.
-
-        private readonly Dictionary<IntPtr, SNIPacket> _pendingWritePackets = new Dictionary<IntPtr, SNIPacket>(); // Stores write packets that have been sent to SNI, but have not yet finished writing (i.e. we are waiting for SNI's callback)
-
-        internal TdsParserStateObjectNative(TdsParser parser, TdsParserStateObject physicalConnection, bool async) :
-            base(parser, physicalConnection, async)
-        {
-        }
-
-        internal SNIHandle Handle => _sessionHandle;
-
-        internal override uint Status => _sessionHandle != null ? _sessionHandle.Status : TdsEnums.SNI_UNINITIALIZED;
-
-        internal override SessionHandle SessionHandle => SessionHandle.FromNativeHandle(_sessionHandle);
-
-        protected override void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async)
-        {
-            Debug.Assert(physicalConnection is TdsParserStateObjectNative, "Expected a stateObject of type " + this.GetType());
-            TdsParserStateObjectNative nativeSNIObject = physicalConnection as TdsParserStateObjectNative;
-            SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async);
-            _sessionHandle = new SNIHandle(myInfo, nativeSNIObject.Handle);
-        }
-
-        private SNINativeMethodWrapper.ConsumerInfo CreateConsumerInfo(bool async)
-        {
-            SNINativeMethodWrapper.ConsumerInfo myInfo = default;
-
-            Debug.Assert(_outBuff.Length == _inBuff.Length, "Unexpected unequal buffers.");
-
-            myInfo.defaultBufferSize = _outBuff.Length; // Obtain packet size from outBuff size.
-
-            if (async)
-            {
-                myInfo.readDelegate = SNILoadHandle.SingletonInstance.ReadAsyncCallbackDispatcher;
-                myInfo.writeDelegate = SNILoadHandle.SingletonInstance.WriteAsyncCallbackDispatcher;
-                _gcHandle = GCHandle.Alloc(this, GCHandleType.Normal);
-                myInfo.key = (IntPtr)_gcHandle;
-            }
-            return myInfo;
-        }
-
-        internal override void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool fParallel, bool isIntegratedSecurity)
-        {
-            // We assume that the loadSSPILibrary has been called already. now allocate proper length of buffer
-            spnBuffer = null;
-            if (isIntegratedSecurity)
-            {
-                // now allocate proper length of buffer
-                spnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength];
-            }
-
-            SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async);
-
-            // Translate to SNI timeout values (Int32 milliseconds)
-            long timeout;
-            if (long.MaxValue == timerExpire)
-            {
-                timeout = int.MaxValue;
-            }
-            else
-            {
-                timeout = ADP.TimerRemainingMilliseconds(timerExpire);
-                if (timeout > int.MaxValue)
-                {
-                    timeout = int.MaxValue;
-                }
-                else if (0 > timeout)
-                {
-                    timeout = 0;
-                }
-            }
-
-            _sessionHandle = new SNIHandle(myInfo, serverName, spnBuffer, ignoreSniOpenTimeout, checked((int)timeout), out instanceName, flushCache, !async, fParallel);
-        }
-
-        protected override uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize)
-        {
-            Debug.Assert(packet.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
-            return SNINativeMethodWrapper.SNIPacketGetData(packet.NativePointer, _inBuff, ref dataSize);
-        }
-
-        protected override bool CheckPacket(PacketHandle packet, TaskCompletionSource<object> source)
-        {
-            Debug.Assert(packet.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
-            IntPtr ptr = packet.NativePointer;
-            return IntPtr.Zero == ptr || IntPtr.Zero != ptr && source != null;
-        }
-
-        public void ReadAsyncCallback(IntPtr key, IntPtr packet, uint error) => ReadAsyncCallback(key, packet, error);
-
-        public void WriteAsyncCallback(IntPtr key, IntPtr packet, uint sniError) => WriteAsyncCallback(key, packet, sniError);
-
-        protected override void RemovePacketFromPendingList(PacketHandle ptr)
-        {
-            Debug.Assert(ptr.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
-            IntPtr pointer = ptr.NativePointer;
-
-            SNIPacket recoveredPacket;
-
-            lock (_writePacketLockObject)
-            {
-                if (_pendingWritePackets.TryGetValue(pointer, out recoveredPacket))
-                {
-                    _pendingWritePackets.Remove(pointer);
-                    _writePacketCache.Add(recoveredPacket);
-                }
-#if DEBUG
-                else
-                {
-                    Debug.Fail("Removing a packet from the pending list that was never added to it");
-                }
-#endif
-            }
-        }
-
-
-        internal override void Dispose()
-        {
-            SafeHandle packetHandle = _sniPacket;
-            SafeHandle sessionHandle = _sessionHandle;
-            SafeHandle asyncAttnPacket = _sniAsyncAttnPacket;
-
-            _sniPacket = null;
-            _sessionHandle = null;
-            _sniAsyncAttnPacket = null;
-
-            DisposeCounters();
-
-            if (null != sessionHandle || null != packetHandle)
-            {
-                packetHandle?.Dispose();
-                asyncAttnPacket?.Dispose();
-
-                if (sessionHandle != null)
-                {
-                    sessionHandle.Dispose();
-                    DecrementPendingCallbacks(true); // Will dispose of GC handle.
-                }
-            }
-
-            DisposePacketCache();
-        }
-
-        protected override void FreeGcHandle(int remaining, bool release)
-        {
-            if ((0 == remaining || release) && _gcHandle.IsAllocated)
-            {
-                _gcHandle.Free();
-            }
-        }
-
-        internal override bool IsFailedHandle() => _sessionHandle.Status != TdsEnums.SNI_SUCCESS;
-
-        internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error)
-        {
-            SNIHandle handle = Handle;
-            if (handle == null)
-            {
-                throw ADP.ClosedConnectionError();
-            }
-            IntPtr readPacketPtr = IntPtr.Zero;
-            error = SNINativeMethodWrapper.SNIReadSyncOverAsync(handle, ref readPacketPtr, GetTimeoutRemaining());
-            return PacketHandle.FromNativePointer(readPacketPtr);
-        }
-
-        protected override PacketHandle EmptyReadPacket => PacketHandle.FromNativePointer(default);
-
-        internal override bool IsPacketEmpty(PacketHandle readPacket)
-        {
-            Debug.Assert(readPacket.Type == PacketHandle.NativePointerType || readPacket.Type == 0, "unexpected packet type when requiring NativePointer");
-            return IntPtr.Zero == readPacket.NativePointer;
-        }
-
-        internal override void ReleasePacket(PacketHandle syncReadPacket)
-        {
-            Debug.Assert(syncReadPacket.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
-            SNINativeMethodWrapper.SNIPacketRelease(syncReadPacket.NativePointer);
-        }
-
-        internal override uint CheckConnection()
-        {
-            SNIHandle handle = Handle;
-            return handle == null ? TdsEnums.SNI_SUCCESS : SNINativeMethodWrapper.SNICheckConnection(handle);
-        }
-
-        internal override PacketHandle ReadAsync(SessionHandle handle, out uint error)
-        {
-            Debug.Assert(handle.Type == SessionHandle.NativeHandleType, "unexpected handle type when requiring NativePointer");
-            IntPtr readPacketPtr = IntPtr.Zero;
-            error = SNINativeMethodWrapper.SNIReadAsync(handle.NativeHandle, ref readPacketPtr);
-            return PacketHandle.FromNativePointer(readPacketPtr);
-        }
-
-        internal override PacketHandle CreateAndSetAttentionPacket()
-        {
-            SNIHandle handle = Handle;
-            SNIPacket attnPacket = new SNIPacket(handle);
-            _sniAsyncAttnPacket = attnPacket;
-            SetPacketData(PacketHandle.FromNativePacket(attnPacket), SQL.AttentionHeader, TdsEnums.HEADER_LEN);
-            return PacketHandle.FromNativePacket(attnPacket);
-        }
-
-        internal override uint WritePacket(PacketHandle packet, bool sync)
-        {
-            Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket");
-            return SNINativeMethodWrapper.SNIWritePacket(Handle, packet.NativePacket, sync);
-        }
-
-        internal override PacketHandle AddPacketToPendingList(PacketHandle packetToAdd)
-        {
-            Debug.Assert(packetToAdd.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket");
-            SNIPacket packet = packetToAdd.NativePacket;
-            Debug.Assert(packet == _sniPacket, "Adding a packet other than the current packet to the pending list");
-            _sniPacket = null;
-            IntPtr pointer = packet.DangerousGetHandle();
-
-            lock (_writePacketLockObject)
-            {
-                _pendingWritePackets.Add(pointer, packet);
-            }
-
-            return PacketHandle.FromNativePointer(pointer);
-        }
-
-        internal override bool IsValidPacket(PacketHandle packetPointer)
-        {
-            Debug.Assert(packetPointer.Type == PacketHandle.NativePointerType || packetPointer.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePointer");
-            return (
-                (packetPointer.Type == PacketHandle.NativePointerType && packetPointer.NativePointer != IntPtr.Zero)
-                ||
-                (packetPointer.Type == PacketHandle.NativePacketType && packetPointer.NativePacket != null)
-            );
-        }
-
-        internal override PacketHandle GetResetWritePacket(int dataSize)
-        {
-            if (_sniPacket != null)
-            {
-                SNINativeMethodWrapper.SNIPacketReset(Handle, SNINativeMethodWrapper.IOType.WRITE, _sniPacket, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
-            }
-            else
-            {
-                lock (_writePacketLockObject)
-                {
-                    _sniPacket = _writePacketCache.Take(Handle);
-                }
-            }
-            return PacketHandle.FromNativePacket(_sniPacket);
-        }
-
-        internal override void ClearAllWritePackets()
-        {
-            if (_sniPacket != null)
-            {
-                _sniPacket.Dispose();
-                _sniPacket = null;
-            }
-            lock (_writePacketLockObject)
-            {
-                Debug.Assert(_pendingWritePackets.Count == 0 && _asyncWriteCount == 0, "Should not clear all write packets if there are packets pending");
-                _writePacketCache.Clear();
-            }
-        }
-
-        internal override void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed)
-        {
-            Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket");
-            SNINativeMethodWrapper.SNIPacketSetData(packet.NativePacket, buffer, bytesUsed);
-        }
-
-        internal override uint SniGetConnectionId(ref Guid clientConnectionId)
-            => SNINativeMethodWrapper.SniGetConnectionId(Handle, ref clientConnectionId);
-
-        internal override uint DisabeSsl()
-            => SNINativeMethodWrapper.SNIRemoveProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV);
-
-        internal override uint EnableMars(ref uint info)
-            => SNINativeMethodWrapper.SNIAddProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SMUX_PROV, ref info);
-
-        internal override uint EnableSsl(ref uint info)
-        {
-            // Add SSL (Encryption) SNI provider.
-            return SNINativeMethodWrapper.SNIAddProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV, ref info);
-        }
-
-        internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize)
-            => SNINativeMethodWrapper.SNISetInfo(Handle, SNINativeMethodWrapper.QTypes.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize);
-
-        internal override uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer)
-            => SNINativeMethodWrapper.SNISecGenClientContext(Handle, receivedBuff, receivedLength, sendBuff, ref sendLength, _sniSpnBuffer);
-
-
-        internal override uint WaitForSSLHandShakeToComplete()
-            => SNINativeMethodWrapper.SNIWaitForSSLHandshakeToComplete(Handle, GetTimeoutRemaining());
-
-        internal override void DisposePacketCache()
-        {
-            lock (_writePacketLockObject)
-            {
-                _writePacketCache.Dispose();
-                // Do not set _writePacketCache to null, just in case a WriteAsyncCallback completes after this point
-            }
-        }
-
-        internal sealed class WritePacketCache : IDisposable
-        {
-            private bool _disposed;
-            private readonly Stack<SNIPacket> _packets;
-
-            public WritePacketCache()
-            {
-                _disposed = false;
-                _packets = new Stack<SNIPacket>();
-            }
-
-            public SNIPacket Take(SNIHandle sniHandle)
-            {
-                SNIPacket packet;
-                if (_packets.Count > 0)
-                {
-                    // Success - reset the packet
-                    packet = _packets.Pop();
-                    SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
-                }
-                else
-                {
-                    // Failed to take a packet - create a new one
-                    packet = new SNIPacket(sniHandle);
-                }
-                return packet;
-            }
-
-            public void Add(SNIPacket packet)
-            {
-                if (!_disposed)
-                {
-                    _packets.Push(packet);
-                }
-                else
-                {
-                    // If we're disposed, then get rid of any packets added to us
-                    packet.Dispose();
-                }
-            }
-
-            public void Clear()
-            {
-                while (_packets.Count > 0)
-                {
-                    _packets.Pop().Dispose();
-                }
-            }
-
-            public void Dispose()
-            {
-                if (!_disposed)
-                {
-                    _disposed = true;
-                    Clear();
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStaticMethods.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStaticMethods.cs
deleted file mode 100644 (file)
index 5bc300a..0000000
+++ /dev/null
@@ -1,189 +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.Data.Common;
-
-
-namespace System.Data.SqlClient
-{
-    internal sealed class TdsParserStaticMethods
-    {
-        // Obfuscate password to be sent to SQL Server
-        // Blurb from the TDS spec at https://msdn.microsoft.com/en-us/library/dd304523.aspx
-        // "Before submitting a password from the client to the server, for every byte in the password buffer
-        // starting with the position pointed to by IbPassword, the client SHOULD first swap the four high bits
-        // with the four low bits and then do a bit-XOR with 0xA5 (10100101). After reading a submitted password,
-        // for every byte in the password buffer starting with the position pointed to by IbPassword, the server SHOULD
-        // first do a bit-XOR with 0xA5 (10100101) and then swap the four high bits with the four low bits."
-        // The password exchange during Login phase happens over a secure channel i.e. SSL/TLS
-        // Note: The same logic is used in SNIPacketSetData (SniManagedWrapper) to encrypt passwords stored in SecureString
-        //       If this logic changed, SNIPacketSetData needs to be changed as well
-        internal static byte[] ObfuscatePassword(string password)
-        {
-            byte[] bObfuscated = new byte[password.Length << 1];
-            int s;
-            byte bLo;
-            byte bHi;
-
-            for (int i = 0; i < password.Length; i++)
-            {
-                s = (int)password[i];
-                bLo = (byte)(s & 0xff);
-                bHi = (byte)((s >> 8) & 0xff);
-                bObfuscated[i << 1] = (byte)((((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5);
-                bObfuscated[(i << 1) + 1] = (byte)((((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5);
-            }
-            return bObfuscated;
-        }
-
-        internal static byte[] ObfuscatePassword(byte[] password)
-        {
-            byte bLo;
-            byte bHi;
-
-            for (int i = 0; i < password.Length; i++)
-            {
-                bLo = (byte)(password[i] & 0x0f);
-                bHi = (byte)(password[i] & 0xf0);
-                password[i] = (byte)(((bHi >> 4) | (bLo << 4)) ^ 0xa5);
-            }
-            return password;
-        }
-
-        private const int NoProcessId = -1;
-        private static int s_currentProcessId = NoProcessId;
-        internal static int GetCurrentProcessIdForTdsLoginOnly()
-        {
-            if (s_currentProcessId == NoProcessId)
-            {
-                // Pick up the process Id from the current process instead of randomly generating it.
-                // This would be helpful while tracing application related issues.
-                int processId;
-                using (System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess())
-                {
-                    processId = p.Id;
-                }
-                System.Threading.Volatile.Write(ref s_currentProcessId, processId);
-            }
-            return s_currentProcessId;
-        }
-
-
-        internal static int GetCurrentThreadIdForTdsLoginOnly()
-        {
-            return Environment.CurrentManagedThreadId;
-        }
-
-
-        private static byte[] s_nicAddress = null;
-        internal static byte[] GetNetworkPhysicalAddressForTdsLoginOnly()
-        {
-            // For ProjectK\CoreCLR we don't want to take a dependency on the registry to try to read a value
-            // that isn't usually set, so we'll just use a random value each time instead
-            if (null == s_nicAddress)
-            {
-                byte[] newNicAddress = new byte[TdsEnums.MAX_NIC_SIZE];
-                Random random = new Random();
-                random.NextBytes(newNicAddress);
-                Threading.Interlocked.CompareExchange(ref s_nicAddress, newNicAddress, null);
-            }
-
-            return s_nicAddress;
-        }
-
-        // translates remaining time in stateObj (from user specified timeout) to timeout value for SNI
-        internal static int GetTimeoutMilliseconds(long timeoutTime)
-        {
-            // User provided timeout t | timeout value for SNI | meaning
-            // ------------------------+-----------------------+------------------------------
-            //      t == long.MaxValue |                    -1 | infinite timeout (no timeout)
-            //   t>0 && t<int.MaxValue |                     t |
-            //          t>int.MaxValue |          int.MaxValue | must not exceed int.MaxValue
-
-            if (long.MaxValue == timeoutTime)
-            {
-                return -1;  // infinite timeout
-            }
-
-            long msecRemaining = ADP.TimerRemainingMilliseconds(timeoutTime);
-
-            if (msecRemaining < 0)
-            {
-                return 0;
-            }
-            if (msecRemaining > (long)int.MaxValue)
-            {
-                return int.MaxValue;
-            }
-            return (int)msecRemaining;
-        }
-
-
-        internal static long GetTimeout(long timeoutMilliseconds)
-        {
-            long result;
-            if (timeoutMilliseconds <= 0)
-            {
-                result = long.MaxValue; // no timeout...
-            }
-            else
-            {
-                try
-                {
-                    result = checked(ADP.TimerCurrent() + ADP.TimerFromMilliseconds(timeoutMilliseconds));
-                }
-                catch (OverflowException)
-                {
-                    // In case of overflow, set to 'infinite' timeout
-                    result = long.MaxValue;
-                }
-            }
-            return result;
-        }
-
-        internal static bool TimeoutHasExpired(long timeoutTime)
-        {
-            bool result = false;
-
-            if (0 != timeoutTime && long.MaxValue != timeoutTime)
-            {
-                result = ADP.TimerHasExpired(timeoutTime);
-            }
-            return result;
-        }
-
-        internal static int NullAwareStringLength(string str)
-        {
-            if (str == null)
-            {
-                return 0;
-            }
-            else
-            {
-                return str.Length;
-            }
-        }
-
-        internal static int GetRemainingTimeout(int timeout, long start)
-        {
-            if (timeout <= 0)
-            {
-                return timeout;
-            }
-            long remaining = ADP.TimerRemainingSeconds(start + ADP.TimerFromSeconds(timeout));
-            if (remaining <= 0)
-            {
-                return 1;
-            }
-            else
-            {
-                return checked((int)remaining);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsRecordBufferSetter.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsRecordBufferSetter.cs
deleted file mode 100644 (file)
index 3cbcec6..0000000
+++ /dev/null
@@ -1,308 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-
-
-//------------------------------------------------------------------------------
-
-using Microsoft.SqlServer.Server;
-using System.Diagnostics;
-using System.Data.SqlTypes;
-
-namespace System.Data.SqlClient
-{
-    // TdsRecordBufferSetter handles writing a structured value out to a TDS stream
-    internal class TdsRecordBufferSetter : SmiRecordBuffer
-    {
-        #region Fields (private)
-
-        private readonly TdsValueSetter[] _fieldSetters;      // setters for individual fields
-
-        private readonly TdsParserStateObject _stateObj;          // target to write to
-        private readonly SmiMetaData _metaData;          // metadata describing value
-#if DEBUG
-        private const int ReadyForToken = -1;         // must call new/end element next
-        private const int EndElementsCalled = -2;     // already called EndElements, can only call Close
-
-        private int _currentField;      // validate that caller sets columns in correct order.
-#endif
-
-        #endregion
-
-        #region Exposed Construct and control methods/properties
-
-        internal TdsRecordBufferSetter(TdsParserStateObject stateObj, SmiMetaData md)
-        {
-            Debug.Assert(SqlDbType.Structured == md.SqlDbType, "Unsupported SqlDbType: " + md.SqlDbType);
-            _fieldSetters = new TdsValueSetter[md.FieldMetaData.Count];
-            for (int i = 0; i < md.FieldMetaData.Count; i++)
-            {
-                _fieldSetters[i] = new TdsValueSetter(stateObj, md.FieldMetaData[i]);
-            }
-            _stateObj = stateObj;
-            _metaData = md;
-#if DEBUG
-            _currentField = ReadyForToken;
-#endif
-        }
-
-        // TdsRecordBufferSetter supports Setting only
-        internal override bool CanGet
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        internal override bool CanSet
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        #endregion
-
-        #region Setters
-
-        // Set value to null
-        //  valid for all types
-        public override void SetDBNull(SmiEventSink sink, int ordinal)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetDBNull();
-        }
-
-        //  valid for SqlDbType.Bit
-        public override void SetBoolean(SmiEventSink sink, int ordinal, bool value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetBoolean(value);
-        }
-
-        //  valid for SqlDbType.TinyInt
-        public override void SetByte(SmiEventSink sink, int ordinal, byte value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetByte(value);
-        }
-
-        // Semantics for SetBytes are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
-        //      (VarBinary assumed for variants)
-        public override int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            CheckWritingToColumn(ordinal);
-            return _fieldSetters[ordinal].SetBytes(fieldOffset, buffer, bufferOffset, length);
-        }
-        public override void SetBytesLength(SmiEventSink sink, int ordinal, long length)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetBytesLength(length);
-        }
-
-        // Semantics for SetChars are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        //      (NVarChar and global clr collation assumed for variants)
-        public override int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            CheckWritingToColumn(ordinal);
-            return _fieldSetters[ordinal].SetChars(fieldOffset, buffer, bufferOffset, length);
-        }
-
-        public override void SetCharsLength(SmiEventSink sink, int ordinal, long length)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetCharsLength(length);
-        }
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        public override void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetString(value, offset, length);
-        }
-
-        // valid for SqlDbType.SmallInt
-        public override void SetInt16(SmiEventSink sink, int ordinal, short value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetInt16(value);
-        }
-
-        // valid for SqlDbType.Int
-        public override void SetInt32(SmiEventSink sink, int ordinal, int value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetInt32(value);
-        }
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        public override void SetInt64(SmiEventSink sink, int ordinal, long value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetInt64(value);
-        }
-
-        // valid for SqlDbType.Real
-        public override void SetSingle(SmiEventSink sink, int ordinal, float value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetSingle(value);
-        }
-
-        // valid for SqlDbType.Float
-        public override void SetDouble(SmiEventSink sink, int ordinal, double value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetDouble(value);
-        }
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        public override void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetSqlDecimal(value);
-        }
-
-        // valid for DateTime, SmallDateTime, Date, DateTime2
-        public override void SetDateTime(SmiEventSink sink, int ordinal, DateTime value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetDateTime(value);
-        }
-
-        // valid for UniqueIdentifier
-        public override void SetGuid(SmiEventSink sink, int ordinal, Guid value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetGuid(value);
-        }
-
-        // valid for SqlDbType.Time
-        public override void SetTimeSpan(SmiEventSink sink, int ordinal, TimeSpan value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetTimeSpan(value);
-        }
-
-        // valid for DateTimeOffset
-        public override void SetDateTimeOffset(SmiEventSink sink, int ordinal, DateTimeOffset value)
-        {
-            CheckSettingColumn(ordinal);
-            _fieldSetters[ordinal].SetDateTimeOffset(value);
-        }
-
-        // valid for SqlDbType.Variant
-        public override void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData)
-        {
-            CheckWritingToColumn(ordinal);
-            _fieldSetters[ordinal].SetVariantType(metaData);
-        }
-
-        // valid for multi-valued types
-        internal override void NewElement(SmiEventSink sink)
-        {
-#if DEBUG
-            SkipPossibleDefaultedColumns(ReadyForToken);
-            Debug.Assert(ReadyForToken == _currentField, "Not on first or last column!");
-#endif
-
-            // For TVP types, write new-row token
-            Debug.Assert(_metaData.IsMultiValued, "Unsupported call for single-valued types");
-            _stateObj.WriteByte(TdsEnums.TVP_ROW_TOKEN);
-#if DEBUG
-            _currentField = 0;
-#endif
-        }
-
-        internal override void EndElements(SmiEventSink sink)
-        {
-#if DEBUG
-            SkipPossibleDefaultedColumns(ReadyForToken);
-            Debug.Assert(ReadyForToken == _currentField, "Not on first or last column!");
-            Debug.Assert(_metaData.IsMultiValued, "Unsupported call for single-valued types");
-#endif
-            // For TVP types, write no-more-rows token
-            _stateObj.WriteByte(TdsEnums.TVP_END_TOKEN);
-#if DEBUG
-            _currentField = EndElementsCalled;
-#endif
-        }
-
-
-        #endregion
-
-        #region private methods
-        [Conditional("DEBUG")]
-        private void CheckWritingToColumn(int ordinal)
-        {
-#if DEBUG
-            Debug.Assert(0 <= ordinal, "TdsRecordBufferSetter.CheckWritingToColumn: Targeting invalid column: " + ordinal);
-            SkipPossibleDefaultedColumns(ordinal);
-
-            Debug.Assert(0 <= _currentField && _metaData.FieldMetaData.Count > _currentField, "_currentField out of range for setting a column:" + _currentField);
-            Debug.Assert(ordinal == _currentField, "Setter called out of order.  Should be " + _currentField + ", but was " + ordinal);
-            // Must not write to field with a DefaultFieldsProperty set to true
-            Debug.Assert(!((SmiDefaultFieldsProperty)_metaData.ExtendedProperties[SmiPropertySelector.DefaultFields])[ordinal],
-                "Attempt to write to a default-valued field: " + ordinal);
-#endif
-        }
-
-        // Handle logic of skipping default columns
-        [Conditional("DEBUG")]
-        private void SkipPossibleDefaultedColumns(int targetColumn)
-        {
-#if DEBUG
-            Debug.Assert(targetColumn < _metaData.FieldMetaData.Count && targetColumn >= ReadyForToken, "TdsRecordBufferSetter.SkipPossibleDefaultedColumns: Invalid target column: " + targetColumn);
-
-            // special setup for ReadyForToken as the target
-            if (targetColumn == ReadyForToken)
-            {
-                if (ReadyForToken == _currentField)
-                {
-                    return;
-                }
-
-                // Handle readyfortoken by using count of columns in the loop.
-                targetColumn = _metaData.FieldMetaData.Count;
-            }
-
-            // Handle skipping default-valued fields
-            while (targetColumn > _currentField)
-            {
-                // All intermediate fields must be default fields (i.e. have a "true" entry in SmiDefaultFieldsProperty
-                Debug.Assert(((SmiDefaultFieldsProperty)_metaData.ExtendedProperties[SmiPropertySelector.DefaultFields])[_currentField],
-                    "Skipping a field that was not default: " + _currentField);
-                _currentField++;
-            }
-
-            if (_metaData.FieldMetaData.Count == _currentField)
-            {
-                _currentField = ReadyForToken;
-            }
-#endif
-        }
-
-        [Conditional("DEBUG")]
-        internal void CheckSettingColumn(int ordinal)
-        {
-#if DEBUG
-            // Make sure target column can be written to.
-            CheckWritingToColumn(ordinal);
-
-            _currentField++;
-            if (_metaData.FieldMetaData.Count == _currentField)
-            {
-                _currentField = ReadyForToken;
-            }
-#endif
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsValueSetter.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlClient/TdsValueSetter.cs
deleted file mode 100644 (file)
index d47cd17..0000000
+++ /dev/null
@@ -1,716 +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.SqlServer.Server;
-using System.Data.Common;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.Text;
-
-using MSS = Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient
-{
-    // TdsValueSetter handles writing a single value out to a TDS stream
-    //   This class can easily be extended to handle multiple versions of TDS by sub-classing and virtualizing
-    //   methods that have different formats or are not supported in one or the other version.
-    internal class TdsValueSetter
-    {
-        #region Private fields
-
-        private readonly TdsParserStateObject _stateObj;      // target to write to
-        private readonly SmiMetaData _metaData;      // metadata describing value
-        private readonly bool _isPlp;         // should this column be sent in PLP format?
-        private bool _plpUnknownSent; // did we send initial UNKNOWN_LENGTH marker?
-        private Encoder _encoder;       // required for chunking character type data
-        private SmiMetaData _variantType;   // required for sql_variant
-#if DEBUG
-        private int _currentOffset; // for chunking, verify that caller is using correct offsets
-#endif
-
-        #endregion
-
-        #region Exposed Construct/factory methods
-
-        internal TdsValueSetter(TdsParserStateObject stateObj, SmiMetaData md)
-        {
-            _stateObj = stateObj;
-            _metaData = md;
-            _isPlp = MetaDataUtilsSmi.IsPlpFormat(md);
-            _plpUnknownSent = false;
-            _encoder = null;
-#if DEBUG
-            _currentOffset = 0;
-#endif
-        }
-
-        #endregion
-
-        #region Setters
-
-        // Set value to null
-        //  valid for all types
-        internal void SetDBNull()
-        {
-            Debug.Assert(!_plpUnknownSent, "Setting a column to null that we already stated sending!");
-            if (_isPlp)
-            {
-                _stateObj.Parser.WriteUnsignedLong(TdsEnums.SQL_PLP_NULL, _stateObj);
-            }
-            else
-            {
-                switch (_metaData.SqlDbType)
-                {
-                    case SqlDbType.BigInt:
-                    case SqlDbType.Bit:
-                    case SqlDbType.DateTime:
-                    case SqlDbType.Decimal:
-                    case SqlDbType.Float:
-                    case SqlDbType.Int:
-                    case SqlDbType.Money:
-                    case SqlDbType.Real:
-                    case SqlDbType.UniqueIdentifier:
-                    case SqlDbType.SmallDateTime:
-                    case SqlDbType.SmallInt:
-                    case SqlDbType.SmallMoney:
-                    case SqlDbType.TinyInt:
-                    case SqlDbType.Date:
-                    case SqlDbType.Time:
-                    case SqlDbType.DateTime2:
-                    case SqlDbType.DateTimeOffset:
-                        _stateObj.WriteByte(TdsEnums.FIXEDNULL);
-                        break;
-                    case SqlDbType.Binary:
-                    case SqlDbType.Char:
-                    case SqlDbType.Image:
-                    case SqlDbType.NChar:
-                    case SqlDbType.NText:
-                    case SqlDbType.NVarChar:
-                    case SqlDbType.Text:
-                    case SqlDbType.Timestamp:
-                    case SqlDbType.VarBinary:
-                    case SqlDbType.VarChar:
-                        _stateObj.Parser.WriteShort(TdsEnums.VARNULL, _stateObj);
-                        break;
-                    case SqlDbType.Udt:
-                    case SqlDbType.Xml:
-                        Debug.Fail("PLP-only types shouldn't get to this point. Type: " + _metaData.SqlDbType);
-                        break;
-                    case SqlDbType.Variant:
-                        _stateObj.Parser.WriteInt(TdsEnums.FIXEDNULL, _stateObj);
-                        break;
-                    case SqlDbType.Structured:
-                        Debug.Fail("Not yet implemented.  Not needed until Structured UDTs");
-                        break;
-                    default:
-                        Debug.Fail("Unexpected SqlDbType: " + _metaData.SqlDbType);
-                        break;
-                }
-            }
-        }
-
-        //  valid for SqlDbType.Bit
-        internal void SetBoolean(bool value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetBoolean));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(3, TdsEnums.SQLBIT, 0, _stateObj);
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-            }
-            if (value)
-            {
-                _stateObj.WriteByte(1);
-            }
-            else
-            {
-                _stateObj.WriteByte(0);
-            }
-        }
-
-        //  valid for SqlDbType.TinyInt
-        internal void SetByte(byte value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetByte));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(3, TdsEnums.SQLINT1, 0, _stateObj);
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-            }
-            _stateObj.WriteByte(value);
-        }
-
-        // Semantics for SetBytes are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
-        //      (VarBinary assumed for variants)
-        internal int SetBytes(long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetBytes));
-            CheckSettingOffset(fieldOffset);
-
-            SetBytesNoOffsetHandling(fieldOffset, buffer, bufferOffset, length);
-#if DEBUG
-            _currentOffset += length;
-#endif
-            return length;
-        }
-
-        private void SetBytesNoOffsetHandling(long fieldOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            if (_isPlp)
-            {
-                if (!_plpUnknownSent)
-                {
-                    _stateObj.Parser.WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, _stateObj);
-                    _plpUnknownSent = true;
-                }
-
-                // Write chunk length & chunk
-                _stateObj.Parser.WriteInt(length, _stateObj);
-                _stateObj.WriteByteArray(buffer, length, bufferOffset);
-            }
-            else
-            {
-                // Non-plp data must be sent in one chunk for now.
-#if DEBUG
-                Debug.Assert(0 == _currentOffset, "SetBytes doesn't yet support chunking for non-plp data: " + _currentOffset);
-
-#endif
-                Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong,
-                    "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType);
-
-                if (SqlDbType.Variant == _metaData.SqlDbType)
-                {
-                    _stateObj.Parser.WriteSqlVariantHeader(4 + length, TdsEnums.SQLBIGVARBINARY, 2, _stateObj);
-                }
-                _stateObj.Parser.WriteShort(length, _stateObj);
-                _stateObj.WriteByteArray(buffer, length, bufferOffset);
-            }
-        }
-
-        internal void SetBytesLength(long length)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetBytes));
-            CheckSettingOffset(length);
-
-            if (0 == length)
-            {
-                if (_isPlp)
-                {
-                    Debug.Assert(!_plpUnknownSent, "A plpUnknown has already been sent before setting length to zero.");
-
-                    _stateObj.Parser.WriteLong(0, _stateObj);
-                    _plpUnknownSent = true;
-                }
-                else
-                {
-                    Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong,
-                        "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType);
-
-                    if (SqlDbType.Variant == _metaData.SqlDbType)
-                    {
-                        _stateObj.Parser.WriteSqlVariantHeader(4, TdsEnums.SQLBIGVARBINARY, 2, _stateObj);
-                    }
-                    _stateObj.Parser.WriteShort(0, _stateObj);
-                }
-            }
-            if (_plpUnknownSent)
-            {
-                _stateObj.Parser.WriteInt(TdsEnums.SQL_PLP_CHUNK_TERMINATOR, _stateObj);
-                _plpUnknownSent = false;
-            }
-
-#if DEBUG
-            _currentOffset = 0;
-#endif
-        }
-
-        // Semantics for SetChars are to modify existing value, not overwrite
-        //  Use in combination with SetLength to ensure overwriting when necessary
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        //      (NVarChar and global clr collation assumed for variants)
-        internal int SetChars(long fieldOffset, char[] buffer, int bufferOffset, int length)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetChars));
-
-            // ANSI types must convert to byte[] because that's the tool we have.
-            if (MetaDataUtilsSmi.IsAnsiType(_metaData.SqlDbType))
-            {
-                if (null == _encoder)
-                {
-                    _encoder = _stateObj.Parser._defaultEncoding.GetEncoder();
-                }
-                byte[] bytes = new byte[_encoder.GetByteCount(buffer, bufferOffset, length, false)];
-                _encoder.GetBytes(buffer, bufferOffset, length, bytes, 0, false);
-                SetBytesNoOffsetHandling(fieldOffset, bytes, 0, bytes.Length);
-            }
-            else
-            {
-                CheckSettingOffset(fieldOffset);
-
-                // Send via PLP format if we can.
-                if (_isPlp)
-                {
-                    // Handle initial PLP markers
-                    if (!_plpUnknownSent)
-                    {
-                        _stateObj.Parser.WriteUnsignedLong(TdsEnums.SQL_PLP_UNKNOWNLEN, _stateObj);
-                        _plpUnknownSent = true;
-                    }
-
-                    // Write chunk length
-                    _stateObj.Parser.WriteInt(length * ADP.CharSize, _stateObj);
-                    _stateObj.Parser.WriteCharArray(buffer, length, bufferOffset, _stateObj);
-                }
-                else
-                {
-                    // Non-plp data must be sent in one chunk for now.
-#if DEBUG
-                    Debug.Assert(0 == _currentOffset, "SetChars doesn't yet support chunking for non-plp data: " + _currentOffset);
-#endif
-
-                    if (SqlDbType.Variant == _metaData.SqlDbType)
-                    {
-                        _stateObj.Parser.WriteSqlVariantValue(new string(buffer, bufferOffset, length), length, 0, _stateObj);
-                    }
-                    else
-                    {
-                        Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong,
-                                "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType);
-                        _stateObj.Parser.WriteShort(length * ADP.CharSize, _stateObj);
-                        _stateObj.Parser.WriteCharArray(buffer, length, bufferOffset, _stateObj);
-                    }
-                }
-            }
-
-#if DEBUG
-            _currentOffset += length;
-#endif
-            return length;
-        }
-        internal void SetCharsLength(long length)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetChars));
-            CheckSettingOffset(length);
-
-            if (0 == length)
-            {
-                if (_isPlp)
-                {
-                    Debug.Assert(!_plpUnknownSent, "A plpUnknown has already been sent before setting length to zero.");
-
-                    _stateObj.Parser.WriteLong(0, _stateObj);
-                    _plpUnknownSent = true;
-                }
-                else
-                {
-                    Debug.Assert(!MetaType.GetMetaTypeFromSqlDbType(_metaData.SqlDbType, _metaData.IsMultiValued).IsLong,
-                        "We're assuming long length types are sent as PLP. SqlDbType = " + _metaData.SqlDbType);
-
-                    _stateObj.Parser.WriteShort(0, _stateObj);
-                }
-            }
-            if (_plpUnknownSent)
-            {
-                _stateObj.Parser.WriteInt(TdsEnums.SQL_PLP_CHUNK_TERMINATOR, _stateObj);
-                _plpUnknownSent = false;
-            }
-            _encoder = null;
-
-#if DEBUG
-            _currentOffset = 0;
-#endif
-        }
-
-        // valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
-        internal void SetString(string value, int offset, int length)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetString));
-
-            // ANSI types must convert to byte[] because that's the tool we have.
-            if (MetaDataUtilsSmi.IsAnsiType(_metaData.SqlDbType))
-            {
-                byte[] bytes;
-                // Optimize for common case of writing entire string
-                if (offset == 0 && value.Length <= length)
-                {
-                    bytes = _stateObj.Parser._defaultEncoding.GetBytes(value);
-                }
-                else
-                {
-                    char[] chars = value.ToCharArray(offset, length);
-                    bytes = _stateObj.Parser._defaultEncoding.GetBytes(chars);
-                }
-                SetBytes(0, bytes, 0, bytes.Length);
-                SetBytesLength(bytes.Length);
-            }
-            else if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                Debug.Assert(null != _variantType && SqlDbType.NVarChar == _variantType.SqlDbType, "Invalid variant type");
-
-                SqlCollation collation = new SqlCollation();
-                collation.LCID = checked((int)_variantType.LocaleId);
-                collation.SqlCompareOptions = _variantType.CompareOptions;
-
-                if (length * ADP.CharSize > TdsEnums.TYPE_SIZE_LIMIT)
-                { // send as varchar for length greater than 4000
-                    byte[] bytes;
-                    // Optimize for common case of writing entire string
-                    if (offset == 0 && value.Length <= length)
-                    {
-                        bytes = _stateObj.Parser._defaultEncoding.GetBytes(value);
-                    }
-                    else
-                    {
-                        bytes = _stateObj.Parser._defaultEncoding.GetBytes(value.ToCharArray(offset, length));
-                    }
-                    _stateObj.Parser.WriteSqlVariantHeader(9 + bytes.Length, TdsEnums.SQLBIGVARCHAR, 7, _stateObj);
-                    _stateObj.Parser.WriteUnsignedInt(collation.info, _stateObj); // propbytes: collation.Info
-                    _stateObj.WriteByte(collation.sortId); // propbytes: collation.SortId
-                    _stateObj.Parser.WriteShort(bytes.Length, _stateObj); // propbyte: varlen
-                    _stateObj.WriteByteArray(bytes, bytes.Length, 0);
-                }
-                else
-                {
-                    _stateObj.Parser.WriteSqlVariantHeader(9 + length * ADP.CharSize, TdsEnums.SQLNVARCHAR, 7, _stateObj);
-                    _stateObj.Parser.WriteUnsignedInt(collation.info, _stateObj); // propbytes: collation.Info
-                    _stateObj.WriteByte(collation.sortId); // propbytes: collation.SortId
-                    _stateObj.Parser.WriteShort(length * ADP.CharSize, _stateObj); // propbyte: varlen
-                    _stateObj.Parser.WriteString(value, length, offset, _stateObj);
-                }
-                _variantType = null;
-            }
-            else if (_isPlp)
-            {
-                // Send the string as a complete PLP chunk.
-                _stateObj.Parser.WriteLong(length * ADP.CharSize, _stateObj);  // PLP total length
-                _stateObj.Parser.WriteInt(length * ADP.CharSize, _stateObj);   // Chunk length
-                _stateObj.Parser.WriteString(value, length, offset, _stateObj);  // Data
-                if (length != 0)
-                {
-                    _stateObj.Parser.WriteInt(TdsEnums.SQL_PLP_CHUNK_TERMINATOR, _stateObj); // Terminator
-                }
-            }
-            else
-            {
-                _stateObj.Parser.WriteShort(length * ADP.CharSize, _stateObj);
-                _stateObj.Parser.WriteString(value, length, offset, _stateObj);
-            }
-        }
-
-        // valid for SqlDbType.SmallInt
-        internal void SetInt16(short value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetInt16));
-
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(4, TdsEnums.SQLINT2, 0, _stateObj);
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-            }
-            _stateObj.Parser.WriteShort(value, _stateObj);
-        }
-
-        // valid for SqlDbType.Int
-        internal void SetInt32(int value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetInt32));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(6, TdsEnums.SQLINT4, 0, _stateObj);
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-            }
-            _stateObj.Parser.WriteInt(value, _stateObj);
-        }
-
-        // valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
-        internal void SetInt64(long value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetInt64));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                if (null == _variantType)
-                {
-                    _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLINT8, 0, _stateObj);
-                    _stateObj.Parser.WriteLong(value, _stateObj);
-                }
-                else
-                {
-                    Debug.Assert(SqlDbType.Money == _variantType.SqlDbType, "Invalid variant type");
-
-                    _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLMONEY, 0, _stateObj);
-                    _stateObj.Parser.WriteInt((int)(value >> 0x20), _stateObj);
-                    _stateObj.Parser.WriteInt((int)value, _stateObj);
-                    _variantType = null;
-                }
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-                if (SqlDbType.SmallMoney == _metaData.SqlDbType)
-                {
-                    _stateObj.Parser.WriteInt((int)value, _stateObj);
-                }
-                else if (SqlDbType.Money == _metaData.SqlDbType)
-                {
-                    _stateObj.Parser.WriteInt((int)(value >> 0x20), _stateObj);
-                    _stateObj.Parser.WriteInt((int)value, _stateObj);
-                }
-                else
-                {
-                    _stateObj.Parser.WriteLong(value, _stateObj);
-                }
-            }
-        }
-
-        // valid for SqlDbType.Real
-        internal void SetSingle(float value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetSingle));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(6, TdsEnums.SQLFLT4, 0, _stateObj);
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-            }
-            _stateObj.Parser.WriteFloat(value, _stateObj);
-        }
-
-        // valid for SqlDbType.Float
-        internal void SetDouble(double value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetDouble));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLFLT8, 0, _stateObj);
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-            }
-            _stateObj.Parser.WriteDouble(value, _stateObj);
-        }
-
-        // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
-        internal void SetSqlDecimal(SqlDecimal value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetSqlDecimal));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(21, TdsEnums.SQLNUMERICN, 2, _stateObj);
-                _stateObj.WriteByte(value.Precision); // propbytes: precision
-                _stateObj.WriteByte(value.Scale); // propbytes: scale
-                _stateObj.Parser.WriteSqlDecimal(value, _stateObj);
-            }
-            else
-            {
-                _stateObj.WriteByte(checked((byte)MetaType.MetaDecimal.FixedLength)); // SmiMetaData's length and actual wire format's length are different
-                _stateObj.Parser.WriteSqlDecimal(SqlDecimal.ConvertToPrecScale(value, _metaData.Precision, _metaData.Scale), _stateObj);
-            }
-        }
-
-        // valid for DateTime, SmallDateTime, Date, DateTime2
-        internal void SetDateTime(DateTime value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetDateTime));
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                if ((_variantType != null) && (_variantType.SqlDbType == SqlDbType.DateTime2))
-                {
-                    _stateObj.Parser.WriteSqlVariantDateTime2(value, _stateObj);
-                }
-                else if ((_variantType != null) && (_variantType.SqlDbType == SqlDbType.Date))
-                {
-                    _stateObj.Parser.WriteSqlVariantDate(value, _stateObj);
-                }
-                else
-                {
-                    TdsDateTime dt = MetaType.FromDateTime(value, 8);
-                    _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLDATETIME, 0, _stateObj);
-                    _stateObj.Parser.WriteInt(dt.days, _stateObj);
-                    _stateObj.Parser.WriteInt(dt.time, _stateObj);
-                }
-
-                // Clean the variant metadata to prevent sharing it with next row.
-                // As a reminder, SetVariantType raises an assert if _variantType is not clean
-                _variantType = null;
-            }
-            else
-            {
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-                if (SqlDbType.SmallDateTime == _metaData.SqlDbType)
-                {
-                    TdsDateTime dt = MetaType.FromDateTime(value, (byte)_metaData.MaxLength);
-                    Debug.Assert(0 <= dt.days && dt.days <= ushort.MaxValue, "Invalid DateTime '" + value + "' for SmallDateTime");
-
-                    _stateObj.Parser.WriteShort(dt.days, _stateObj);
-                    _stateObj.Parser.WriteShort(dt.time, _stateObj);
-                }
-                else if (SqlDbType.DateTime == _metaData.SqlDbType)
-                {
-                    TdsDateTime dt = MetaType.FromDateTime(value, (byte)_metaData.MaxLength);
-                    _stateObj.Parser.WriteInt(dt.days, _stateObj);
-                    _stateObj.Parser.WriteInt(dt.time, _stateObj);
-                }
-                else
-                { // date and datetime2
-                    int days = value.Subtract(DateTime.MinValue).Days;
-                    if (SqlDbType.DateTime2 == _metaData.SqlDbType)
-                    {
-                        long time = value.TimeOfDay.Ticks / TdsEnums.TICKS_FROM_SCALE[_metaData.Scale];
-                        _stateObj.WriteByteArray(BitConverter.GetBytes(time), (int)_metaData.MaxLength - 3, 0);
-                    }
-                    _stateObj.WriteByteArray(BitConverter.GetBytes(days), 3, 0);
-                }
-            }
-        }
-
-        // valid for UniqueIdentifier
-        internal void SetGuid(Guid value)
-        {
-            Debug.Assert(SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetGuid));
-#if NETCOREAPP
-            Span<byte> bytes = stackalloc byte[16];
-            value.TryWriteBytes(bytes);
-#else
-            byte[] bytes = value.ToByteArray();
-#endif
-            Debug.Assert(SmiMetaData.DefaultUniqueIdentifier.MaxLength == bytes.Length, "Invalid length for guid bytes: " + bytes.Length);
-
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                _stateObj.Parser.WriteSqlVariantHeader(18, TdsEnums.SQLUNIQUEID, 0, _stateObj);
-            }
-            else
-            {
-                Debug.Assert(_metaData.MaxLength == bytes.Length, "Unexpected uniqueid metadata length: " + _metaData.MaxLength);
-
-                _stateObj.WriteByte((byte)_metaData.MaxLength);
-            }
-#if NETCOREAPP
-            _stateObj.WriteByteSpan(bytes);
-#else
-            _stateObj.WriteByteArray(bytes, bytes.Length, 0);
-#endif
-        }
-
-        // valid for SqlDbType.Time
-        internal void SetTimeSpan(TimeSpan value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetTime));
-            byte scale;
-            byte length;
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                scale = SmiMetaData.DefaultTime.Scale;
-                length = (byte)SmiMetaData.DefaultTime.MaxLength;
-                _stateObj.Parser.WriteSqlVariantHeader(8, TdsEnums.SQLTIME, 1, _stateObj);
-                _stateObj.WriteByte(scale); //propbytes: scale
-            }
-            else
-            {
-                scale = _metaData.Scale;
-                length = (byte)_metaData.MaxLength;
-                _stateObj.WriteByte(length);
-            }
-            long time = value.Ticks / TdsEnums.TICKS_FROM_SCALE[scale];
-            _stateObj.WriteByteArray(BitConverter.GetBytes(time), length, 0);
-        }
-
-        // valid for DateTimeOffset
-        internal void SetDateTimeOffset(DateTimeOffset value)
-        {
-            Debug.Assert(
-                SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetDateTimeOffset));
-            byte scale;
-            byte length;
-            if (SqlDbType.Variant == _metaData.SqlDbType)
-            {
-                // VSTFDevDiv #885208 - DateTimeOffset throws ArgumentException for when passing DateTimeOffset value to a sql_variant TVP
-                //                      using a SqlDataRecord or SqlDataReader
-                MSS.SmiMetaData dateTimeOffsetMetaData = MSS.SmiMetaData.DefaultDateTimeOffset;
-                scale = MetaType.MetaDateTimeOffset.Scale;
-                length = (byte)dateTimeOffsetMetaData.MaxLength;
-                _stateObj.Parser.WriteSqlVariantHeader(13, TdsEnums.SQLDATETIMEOFFSET, 1, _stateObj);
-                _stateObj.WriteByte(scale); //propbytes: scale
-            }
-            else
-            {
-                scale = _metaData.Scale;
-                length = (byte)_metaData.MaxLength;
-                _stateObj.WriteByte(length);
-            }
-            DateTime utcDateTime = value.UtcDateTime;
-            long time = utcDateTime.TimeOfDay.Ticks / TdsEnums.TICKS_FROM_SCALE[scale];
-            int days = utcDateTime.Subtract(DateTime.MinValue).Days;
-            short offset = (short)value.Offset.TotalMinutes;
-
-            _stateObj.WriteByteArray(BitConverter.GetBytes(time), length - 5, 0); // time
-            _stateObj.WriteByteArray(BitConverter.GetBytes(days), 3, 0); // date
-            _stateObj.WriteByte((byte)(offset & 0xff)); // offset byte 1
-            _stateObj.WriteByte((byte)((offset >> 8) & 0xff)); // offset byte 2
-        }
-
-        internal void SetVariantType(SmiMetaData value)
-        {
-            Debug.Assert(null == _variantType, "Variant type can only be set once");
-            Debug.Assert(value != null &&
-                (value.SqlDbType == SqlDbType.Money ||
-                value.SqlDbType == SqlDbType.NVarChar ||
-                value.SqlDbType == SqlDbType.Date ||
-                value.SqlDbType == SqlDbType.DateTime ||
-                value.SqlDbType == SqlDbType.DateTime2 ||
-                value.SqlDbType == SqlDbType.DateTimeOffset ||
-                value.SqlDbType == SqlDbType.SmallDateTime
-                ), "Invalid variant type");
-            _variantType = value;
-        }
-
-#endregion
-
-#region private methods
-        [Conditional("DEBUG")]
-        private void CheckSettingOffset(long offset)
-        {
-#if DEBUG
-            Debug.Assert(offset == _currentOffset, "Invalid offset passed. Should be: " + _currentOffset + ", but was: " + offset);
-#endif
-        }
-#endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/src/System/Data/SqlTypes/SqlTypeWorkarounds.cs b/src/libraries/System.Data.SqlClient/src/System/Data/SqlTypes/SqlTypeWorkarounds.cs
deleted file mode 100644 (file)
index d342ba3..0000000
+++ /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.Diagnostics;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Xml;
-
-namespace System.Data.SqlTypes
-{
-    /// <summary>
-    /// This type provides workarounds for the separation between System.Data.Common
-    /// and System.Data.SqlClient.  The latter wants to access internal members of the former, and
-    /// this class provides ways to do that.  We must review and update this implementation any time the
-    /// implementation of the corresponding types in System.Data.Common change.
-    /// </summary>
-    internal static class SqlTypeWorkarounds
-    {
-        #region Work around inability to access SqlXml.CreateSqlXmlReader
-        private static readonly XmlReaderSettings s_defaultXmlReaderSettings = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment };
-        private static readonly XmlReaderSettings s_defaultXmlReaderSettingsCloseInput = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true };
-        private static readonly XmlReaderSettings s_defaultXmlReaderSettingsAsyncCloseInput = new XmlReaderSettings() { Async = true, ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true };
-
-        internal const SqlCompareOptions SqlStringValidSqlCompareOptionMask =
-            SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreWidth |
-            SqlCompareOptions.IgnoreNonSpace | SqlCompareOptions.IgnoreKanaType |
-            SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2;
-
-        internal static XmlReader SqlXmlCreateSqlXmlReader(Stream stream, bool closeInput = false, bool async = false)
-        {
-            Debug.Assert(closeInput || !async, "Currently we do not have pre-created settings for !closeInput+async");
-
-            XmlReaderSettings settingsToUse = closeInput ?
-                (async ? s_defaultXmlReaderSettingsAsyncCloseInput : s_defaultXmlReaderSettingsCloseInput) :
-                s_defaultXmlReaderSettings;
-
-            return XmlReader.Create(stream, settingsToUse);
-        }
-
-        internal static XmlReader SqlXmlCreateSqlXmlReader(TextReader textReader, bool closeInput = false, bool async = false)
-        {
-            Debug.Assert(closeInput || !async, "Currently we do not have pre-created settings for !closeInput+async");
-
-            XmlReaderSettings settingsToUse = closeInput ?
-                (async ? s_defaultXmlReaderSettingsAsyncCloseInput : s_defaultXmlReaderSettingsCloseInput) :
-                s_defaultXmlReaderSettings;
-
-            return XmlReader.Create(textReader, settingsToUse);
-        }
-        #endregion
-
-        #region Work around inability to access SqlDateTime.ToDateTime
-        internal static DateTime SqlDateTimeToDateTime(int daypart, int timepart)
-        {
-            // Values need to match those from SqlDateTime
-            const double SQLTicksPerMillisecond = 0.3;
-            const int SQLTicksPerSecond = 300;
-            const int SQLTicksPerMinute = SQLTicksPerSecond * 60;
-            const int SQLTicksPerHour = SQLTicksPerMinute * 60;
-            const int SQLTicksPerDay = SQLTicksPerHour * 24;
-            const int MinDay = -53690;                // Jan 1 1753
-            const int MaxDay = 2958463;               // Dec 31 9999 is this many days from Jan 1 1900
-            const int MinTime = 0;                    // 00:00:0:000PM
-            const int MaxTime = SQLTicksPerDay - 1; // = 25919999,  11:59:59:997PM
-
-            if (daypart < MinDay || daypart > MaxDay || timepart < MinTime || timepart > MaxTime)
-            {
-                throw new OverflowException(SQLResource.DateTimeOverflowMessage);
-            }
-
-            long baseDateTicks = new DateTime(1900, 1, 1).Ticks;
-            long dayticks = daypart * TimeSpan.TicksPerDay;
-            long timeticks = ((long)(timepart / SQLTicksPerMillisecond + 0.5)) * TimeSpan.TicksPerMillisecond;
-
-            return new DateTime(baseDateTicks + dayticks + timeticks);
-        }
-        #endregion
-
-        #region Work around inability to access SqlMoney.ctor(long, int) and SqlMoney.ToSqlInternalRepresentation
-        /// <summary>
-        /// Constructs a SqlMoney from a long value without scaling. The ignored parameter exists
-        /// only to distinguish this constructor from the constructor that takes a long.
-        /// Used only internally.
-        /// </summary>
-        internal static SqlMoney SqlMoneyCtor(long value, int ignored)
-        {
-            var c = default(SqlMoneyCaster);
-
-            // Same behavior as the internal SqlMoney.ctor(long, bool) overload
-            c.Fake._fNotNull = true;
-            c.Fake._value = value;
-
-            return c.Real;
-        }
-
-        internal static long SqlMoneyToSqlInternalRepresentation(SqlMoney money)
-        {
-            var c = default(SqlMoneyCaster);
-            c.Real = money;
-
-            // Same implementation as the internal SqlMoney.ToSqlInternalRepresentation implementation
-            if (money.IsNull)
-            {
-                throw new SqlNullValueException();
-            }
-            return c.Fake._value;
-        }
-
-        [StructLayout(LayoutKind.Sequential)]
-        private struct SqlMoneyLookalike // exact same shape as SqlMoney, but with accessible fields
-        {
-            internal bool _fNotNull;
-            internal long _value;
-        }
-
-        [StructLayout(LayoutKind.Explicit)]
-        private struct SqlMoneyCaster
-        {
-            [FieldOffset(0)]
-            internal SqlMoney Real;
-            [FieldOffset(0)]
-            internal SqlMoneyLookalike Fake;
-        }
-        #endregion
-
-        #region Work around inability to access SqlDecimal._data1/2/3/4
-        internal static void SqlDecimalExtractData(SqlDecimal d, out uint data1, out uint data2, out uint data3, out uint data4)
-        {
-            // Extract the four data elements from SqlDecimal.
-            var c = default(SqlDecimalCaster);
-            c.Real = d;
-            data1 = c.Fake._data1;
-            data2 = c.Fake._data2;
-            data3 = c.Fake._data3;
-            data4 = c.Fake._data4;
-        }
-
-        [StructLayout(LayoutKind.Sequential)]
-        private struct SqlDecimalLookalike // exact same shape as SqlDecimal, but with accessible fields
-        {
-            internal byte _bStatus;
-            internal byte _bLen;
-            internal byte _bPrec;
-            internal byte _bScale;
-            internal uint _data1;
-            internal uint _data2;
-            internal uint _data3;
-            internal uint _data4;
-        }
-
-        [StructLayout(LayoutKind.Explicit)]
-        private struct SqlDecimalCaster
-        {
-            [FieldOffset(0)]
-            internal SqlDecimal Real;
-            [FieldOffset(0)]
-            internal SqlDecimalLookalike Fake;
-        }
-        #endregion
-
-        #region Work around inability to access SqlBinary.ctor(byte[], bool)
-        internal static SqlBinary SqlBinaryCtor(byte[] value, bool ignored)
-        {
-            // Construct a SqlBinary without allocating/copying the byte[].  This provides
-            // the same behavior as SqlBinary.ctor(byte[], bool).
-            var c = default(SqlBinaryCaster);
-            c.Fake._value = value;
-            return c.Real;
-        }
-
-        [StructLayout(LayoutKind.Sequential)]
-        private struct SqlBinaryLookalike
-        {
-            internal byte[] _value;
-        }
-
-        [StructLayout(LayoutKind.Explicit)]
-        private struct SqlBinaryCaster
-        {
-            [FieldOffset(0)]
-            internal SqlBinary Real;
-            [FieldOffset(0)]
-            internal SqlBinaryLookalike Fake;
-        }
-        #endregion
-
-        #region Work around inability to access SqlGuid.ctor(byte[], bool)
-        internal static SqlGuid SqlGuidCtor(byte[] value, bool ignored)
-        {
-            // Construct a SqlGuid without allocating/copying the byte[].  This provides
-            // the same behavior as SqlGuid.ctor(byte[], bool).
-            var c = default(SqlGuidCaster);
-            c.Fake._value = value;
-            return c.Real;
-        }
-
-        [StructLayout(LayoutKind.Sequential)]
-        private struct SqlGuidLookalike
-        {
-            internal byte[] _value;
-        }
-
-        [StructLayout(LayoutKind.Explicit)]
-        private struct SqlGuidCaster
-        {
-            [FieldOffset(0)]
-            internal SqlGuid Real;
-            [FieldOffset(0)]
-            internal SqlGuidLookalike Fake;
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/AADAccessTokenTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/AADAccessTokenTest.cs
deleted file mode 100644 (file)
index eb341ec..0000000
+++ /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 Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class AADAccessTokenTest
-    {
-        private SqlConnectionStringBuilder _builder;
-        private SqlCredential _credential = null;
-        [Theory]
-        [InlineData("Test combination of Access Token and IntegratedSecurity", new object[] { "Integrated Security", true })]
-        [InlineData("Test combination of Access Token and User Id", new object[] { "UID", "sampleUserId" })]
-        [InlineData("Test combination of Access Token and Password", new object[] { "PWD", "samplePassword" })]
-        [InlineData("Test combination of Access Token and Credentials", new object[] { "sampleUserId" })]
-        public void InvalidCombinationOfAccessToken(string description, object[] Params)
-        {
-            _ = description;
-            _builder = new SqlConnectionStringBuilder
-            {
-                ["Data Source"] = "sample.database.windows.net"
-            };
-
-            if (Params.Length == 1)
-            {
-                Security.SecureString password = new Security.SecureString();
-                password.MakeReadOnly();
-                _credential = new SqlCredential(Params[0] as string, password);
-            }
-            else
-            {
-                _builder[Params[0] as string] = Params[1];
-            }
-            InvalidCombinationCheck(_credential);
-        }
-
-        private void InvalidCombinationCheck(SqlCredential credential)
-        {
-            using (SqlConnection connection = new SqlConnection(_builder.ConnectionString, credential))
-            {
-                Assert.Throws<InvalidOperationException>(() => connection.AccessToken = "SampleAccessToken");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs
deleted file mode 100644 (file)
index 987e53c..0000000
+++ /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.Threading.Tasks;
-using System.Transactions;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class AmbientTransactionFailureTest
-    {
-
-        private static readonly string s_servername = Guid.NewGuid().ToString();
-        private static readonly string s_connectionStringWithEnlistAsDefault = $"Data Source={s_servername}; Integrated Security=true; Connect Timeout=1;";
-        private static readonly string s_connectionStringWithEnlistOff = $"Data Source={s_servername}; Integrated Security=true; Connect Timeout=1;Enlist=False";
-
-        private static Action<string> ConnectToServer = (connectionString) =>
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-            }
-        };
-
-        private static Action<string> ConnectToServerTask = (connectionString) =>
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.OpenAsync();
-            }
-        };
-
-        private static Func<string, Task> ConnectToServerInTransactionScopeTask = (connectionString) =>
-        {
-            return Task.Run(() =>
-            {
-                using (TransactionScope scope = new TransactionScope())
-                {
-                    ConnectToServerTask(connectionString);
-                }
-            });
-        };
-
-        private static Action<string> ConnectToServerInTransactionScope = (connectionString) =>
-        {
-            using (TransactionScope scope = new TransactionScope())
-            {
-                ConnectToServer(connectionString);
-            }
-        };
-
-        private static Action<string> EnlistConnectionInTransaction = (connectionString) =>
-        {
-            using (TransactionScope scope = new TransactionScope())
-            {
-                SqlConnection connection = new SqlConnection(connectionString);
-                connection.EnlistTransaction(Transaction.Current);
-            }
-        };
-
-        public static readonly object[][] ExceptionTestDataForSqlException =
-        {
-            new object[] { ConnectToServerInTransactionScope, s_connectionStringWithEnlistOff },
-            new object[] { ConnectToServer, s_connectionStringWithEnlistAsDefault }
-        };
-
-        public static readonly object[][] ExceptionTestDataForNotSupportedException =
-        {
-            new object[] { ConnectToServerInTransactionScope, s_connectionStringWithEnlistAsDefault },
-            new object[] { EnlistConnectionInTransaction, s_connectionStringWithEnlistAsDefault },
-            new object[] { EnlistConnectionInTransaction, s_connectionStringWithEnlistOff }
-        };
-
-        [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArmProcess))] // https://github.com/dotnet/corefx/issues/21598
-        [MemberData(nameof(ExceptionTestDataForSqlException))]
-        public void TestSqlException(Action<string> connectAction, string connectionString)
-        {
-            Assert.Throws<SqlException>(() =>
-            {
-                connectAction(connectionString);
-            });
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/AssemblyInfo.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/AssemblyInfo.cs
deleted file mode 100644 (file)
index 9a17fee..0000000
+++ /dev/null
@@ -1,8 +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;
-
-[assembly: SkipOnCoreClr("Timeout in stress tests on Linux/arm32", TestPlatforms.Linux, RuntimeTestModes.CheckedRuntime)]
-[assembly: SkipOnMono("Timeout in stress tests on Linux/arm32", TestPlatforms.Linux)]
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/BaseProviderAsyncTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/BaseProviderAsyncTest.cs
deleted file mode 100644 (file)
index 89c5432..0000000
+++ /dev/null
@@ -1,219 +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.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class BaseProviderAsyncTest
-    {
-        [Fact]
-        public static void TestDbConnection()
-        {
-            MockConnection connection = new MockConnection();
-            CancellationTokenSource source = new CancellationTokenSource();
-
-            // ensure OpenAsync() calls OpenAsync(CancellationToken.None)
-            AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
-            connection.OpenAsync().Wait();
-            Assert.False(connection.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-            AssertEqualsWithDescription(ConnectionState.Open, connection.State, "Connection state should have been marked as Open");
-            connection.Close();
-
-            // Verify cancellationToken over-ride
-            AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
-            connection.OpenAsync(source.Token).Wait();
-            AssertEqualsWithDescription(ConnectionState.Open, connection.State, "Connection state should have been marked as Open");
-            connection.Close();
-
-            // Verify exceptions are routed through task
-            MockConnection connectionFail = new MockConnection()
-            {
-                Fail = true
-            };
-            connectionFail.OpenAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            connectionFail.OpenAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-
-            // Verify base implementation does not call Open when passed an already cancelled cancellation token
-            source.Cancel();
-            AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
-            connection.OpenAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription(ConnectionState.Closed, connection.State, "Connection state should have been marked as Closed");
-        }
-
-        [Fact]
-        public static void TestDbCommand()
-        {
-            MockCommand command = new MockCommand()
-            {
-                ScalarResult = 1,
-                Results = Enumerable.Range(1, 5).Select((x) => new object[] { x, x.ToString() })
-            };
-            CancellationTokenSource source = new CancellationTokenSource();
-
-            // Verify parameter routing and correct synchronous implementation is called
-            command.ExecuteNonQueryAsync().Wait();
-            Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-            AssertEqualsWithDescription("ExecuteNonQuery", command.LastCommand, "Last command was not as expected");
-            command.ExecuteReaderAsync().Wait();
-            AssertEqualsWithDescription(CommandBehavior.Default, command.CommandBehavior, "Command behavior should have been marked as Default");
-            Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-            AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
-            command.ExecuteScalarAsync().Wait();
-            Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-            AssertEqualsWithDescription("ExecuteScalar", command.LastCommand, "Last command was not as expected");
-
-            command.ExecuteNonQueryAsync(source.Token).Wait();
-            AssertEqualsWithDescription("ExecuteNonQuery", command.LastCommand, "Last command was not as expected");
-            command.ExecuteReaderAsync(source.Token).Wait();
-            AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
-            command.ExecuteScalarAsync(source.Token).Wait();
-            AssertEqualsWithDescription("ExecuteScalar", command.LastCommand, "Last command was not as expected");
-
-            command.ExecuteReaderAsync(CommandBehavior.SequentialAccess).Wait();
-            AssertEqualsWithDescription(CommandBehavior.SequentialAccess, command.CommandBehavior, "Command behavior should have been marked as SequentialAccess");
-            Assert.False(command.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-            AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
-
-            command.ExecuteReaderAsync(CommandBehavior.SingleRow, source.Token).Wait();
-            AssertEqualsWithDescription(CommandBehavior.SingleRow, command.CommandBehavior, "Command behavior should have been marked as SingleRow");
-            AssertEqualsWithDescription("ExecuteReader", command.LastCommand, "Last command was not as expected");
-
-            // Verify exceptions are routed through task
-            MockCommand commandFail = new MockCommand
-            {
-                Fail = true
-            };
-            commandFail.ExecuteNonQueryAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            commandFail.ExecuteNonQueryAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            commandFail.ExecuteReaderAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            commandFail.ExecuteReaderAsync(CommandBehavior.SequentialAccess).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            commandFail.ExecuteReaderAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            commandFail.ExecuteReaderAsync(CommandBehavior.SequentialAccess, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            commandFail.ExecuteScalarAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            commandFail.ExecuteScalarAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-
-            // Verify base implementation does not call Open when passed an already cancelled cancellation token
-            source.Cancel();
-            command.LastCommand = "Nothing";
-            command.ExecuteNonQueryAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
-            command.ExecuteReaderAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
-            command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
-            command.ExecuteScalarAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription("Nothing", command.LastCommand, "Expected last command to be 'Nothing'");
-
-            // Verify cancellation
-            command.WaitForCancel = true;
-            source = new CancellationTokenSource();
-            Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
-            Task result = command.ExecuteNonQueryAsync(source.Token);
-            Assert.True(result.IsFaulted, "Task result should be faulted");
-
-            source = new CancellationTokenSource();
-            Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
-            result = command.ExecuteReaderAsync(source.Token);
-            Assert.True(result.IsFaulted, "Task result should be faulted");
-
-            source = new CancellationTokenSource();
-            Task.Factory.StartNew(() => { command.WaitForWaitingForCancel(); source.Cancel(); });
-            result = command.ExecuteScalarAsync(source.Token);
-            Assert.True(result.IsFaulted, "Task result should be faulted");
-        }
-
-        [Fact]
-        public static void TestDbDataReader()
-        {
-            var query = Enumerable.Range(1, 2).Select((x) => new object[] { x, x.ToString(), DBNull.Value });
-            MockDataReader reader = new MockDataReader { Results = query.GetEnumerator() };
-            CancellationTokenSource source = new CancellationTokenSource();
-
-            Task<bool> result;
-
-            result = reader.ReadAsync(); result.Wait();
-            AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
-            Assert.True(result.Result, "Should have received a Result from the ReadAsync");
-            Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-
-            GetFieldValueAsync(reader, 0, 1);
-            Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-            GetFieldValueAsync(reader, source.Token, 1, "1");
-
-            result = reader.ReadAsync(source.Token); result.Wait();
-            AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
-            Assert.True(result.Result, "Should have received a Result from the ReadAsync");
-
-            GetFieldValueAsync<object>(reader, 2, DBNull.Value);
-            GetFieldValueAsync<DBNull>(reader, 2, DBNull.Value);
-            reader.GetFieldValueAsync<int?>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            reader.GetFieldValueAsync<string>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            reader.GetFieldValueAsync<bool>(2).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
-
-            result = reader.ReadAsync(); result.Wait();
-            AssertEqualsWithDescription("Read", reader.LastCommand, "Last command was not as expected");
-            Assert.False(result.Result, "Should NOT have received a Result from the ReadAsync");
-
-            result = reader.NextResultAsync();
-            AssertEqualsWithDescription("NextResult", reader.LastCommand, "Last command was not as expected");
-            Assert.False(result.Result, "Should NOT have received a Result from NextResultAsync");
-            Assert.False(reader.CancellationToken.CanBeCanceled, "Default cancellation token should not be cancellable");
-            result = reader.NextResultAsync(source.Token);
-            AssertEqualsWithDescription("NextResult", reader.LastCommand, "Last command was not as expected");
-            Assert.False(result.Result, "Should NOT have received a Result from NextResultAsync");
-
-            MockDataReader readerFail = new MockDataReader { Results = query.GetEnumerator(), Fail = true };
-            readerFail.ReadAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            readerFail.ReadAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            readerFail.NextResultAsync().ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            readerFail.NextResultAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            readerFail.GetFieldValueAsync<object>(0).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-            readerFail.GetFieldValueAsync<object>(0, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnFaulted).Wait();
-
-            source.Cancel();
-            reader.LastCommand = "Nothing";
-            reader.ReadAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
-            reader.NextResultAsync(source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
-            reader.GetFieldValueAsync<object>(0, source.Token).ContinueWith((t) => { }, TaskContinuationOptions.OnlyOnCanceled).Wait();
-            AssertEqualsWithDescription("Nothing", reader.LastCommand, "Expected last command to be 'Nothing'");
-        }
-
-        private static void GetFieldValueAsync<T>(MockDataReader reader, int ordinal, T expected)
-        {
-            Task<T> result = reader.GetFieldValueAsync<T>(ordinal);
-            result.Wait();
-            AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
-            AssertEqualsWithDescription(expected, result.Result, "GetFieldValueAsync did not return expected value");
-        }
-
-        private static void GetFieldValueAsync<T>(MockDataReader reader, CancellationToken cancellationToken, int ordinal, T expected)
-        {
-            Task<T> result = reader.GetFieldValueAsync<T>(ordinal, cancellationToken);
-            result.Wait();
-            AssertEqualsWithDescription("GetValue", reader.LastCommand, "Last command was not as expected");
-            AssertEqualsWithDescription(expected, result.Result, "GetFieldValueAsync did not return expected value");
-        }
-
-        private static void AssertEqualsWithDescription(object expectedValue, object actualValue, string failMessage)
-        {
-            if (expectedValue == null || actualValue == null)
-            {
-                var msg = string.Format("{0}\nExpected: {1}\nActual: {2}", failMessage, expectedValue, actualValue);
-                Assert.True(expectedValue == actualValue, msg);
-            }
-            else
-            {
-                var msg = string.Format("{0}\nExpected: {1} ({2})\nActual: {3} ({4})", failMessage, expectedValue, expectedValue.GetType(), actualValue, actualValue.GetType());
-                Assert.True(expectedValue.Equals(actualValue), msg);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockCommand.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockCommand.cs
deleted file mode 100644 (file)
index 2f65e17..0000000
+++ /dev/null
@@ -1,197 +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.Generic;
-using System.Data.Common;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class MockCommand : DbCommand
-    {
-        public bool Fail { get; set; }
-
-        public string LastCommand { get; set; }
-
-        public object ScalarResult { get; set; }
-
-        public IEnumerable<object[]> Results { get; set; }
-
-        public CancellationToken CancellationToken { get; set; }
-
-        public bool WaitForCancel { get; set; }
-
-        private ManualResetEvent _cancelEvent = new ManualResetEvent(false);
-
-        private ManualResetEvent _waitingForCancelEvent = new ManualResetEvent(false);
-
-        public override void Cancel()
-        {
-            _cancelEvent.Set();
-        }
-
-        public override string CommandText
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        public override int CommandTimeout
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        public override System.Data.CommandType CommandType
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        protected override DbParameter CreateDbParameter()
-        {
-            throw new NotImplementedException();
-        }
-
-        protected override DbConnection DbConnection
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        protected override DbParameterCollection DbParameterCollection
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        protected override DbTransaction DbTransaction
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        public override bool DesignTimeVisible
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        protected override DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior)
-        {
-            CheckCancel();
-            if (Fail) { throw new InvalidOperationException("Failure requested"); }
-            LastCommand = "ExecuteReader";
-            return new MockDataReader() { Results = Results.GetEnumerator() };
-        }
-
-        public override int ExecuteNonQuery()
-        {
-            CheckCancel();
-            if (Fail) { throw new InvalidOperationException("Failure requested"); }
-            LastCommand = "ExecuteNonQuery";
-            return (int)ScalarResult;
-        }
-
-        public override object ExecuteScalar()
-        {
-            CheckCancel();
-            if (Fail) { throw new InvalidOperationException("Failure requested"); }
-            LastCommand = "ExecuteScalar";
-            return ScalarResult;
-        }
-
-        public override void Prepare()
-        {
-            throw new NotImplementedException();
-        }
-
-        public override System.Data.UpdateRowSource UpdatedRowSource
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        public CommandBehavior CommandBehavior { get; set; }
-
-        protected override Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
-        {
-            CancellationToken = cancellationToken;
-            CommandBehavior = behavior;
-            return base.ExecuteDbDataReaderAsync(behavior, cancellationToken);
-        }
-
-        public override Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
-        {
-            CancellationToken = cancellationToken;
-            return base.ExecuteNonQueryAsync(cancellationToken);
-        }
-
-        public override Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
-        {
-            CancellationToken = cancellationToken;
-            return base.ExecuteScalarAsync(cancellationToken);
-        }
-
-        public void WaitForWaitingForCancel()
-        {
-            _waitingForCancelEvent.WaitOne();
-        }
-
-        private void CheckCancel()
-        {
-            if (WaitForCancel)
-            {
-                _cancelEvent.Reset();
-                _waitingForCancelEvent.Set();
-                _cancelEvent.WaitOne();
-                _waitingForCancelEvent.Reset();
-
-                throw new Exception("Command canceled");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockConnection.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockConnection.cs
deleted file mode 100644 (file)
index df0b36d..0000000
+++ /dev/null
@@ -1,88 +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.Data.Common;
-using System.Threading;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class MockConnection : DbConnection
-    {
-        private ConnectionState _state;
-
-        public bool Fail { get; set; }
-
-        protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override void ChangeDatabase(string databaseName)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override void Close()
-        {
-            _state = ConnectionState.Closed;
-        }
-
-        public override string ConnectionString
-        {
-            get
-            {
-                throw new NotImplementedException();
-            }
-            set
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        protected override DbCommand CreateDbCommand()
-        {
-            throw new NotImplementedException();
-        }
-
-        public override string DataSource
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override string Database
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override void Open()
-        {
-            if (_state != ConnectionState.Closed)
-            {
-                throw new InvalidOperationException("You can only open closed connections");
-            }
-            if (Fail)
-            {
-                throw new InvalidOperationException("MockConnection was asked to fail");
-            }
-            _state = ConnectionState.Open;
-        }
-
-        public override string ServerVersion
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override System.Data.ConnectionState State
-        {
-            get { return _state; }
-        }
-
-        public CancellationToken CancellationToken { get; set; }
-        public override System.Threading.Tasks.Task OpenAsync(CancellationToken cancellationToken)
-        {
-            CancellationToken = cancellationToken;
-            return base.OpenAsync(cancellationToken);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockDataReader.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/BaseProviderAsyncTest/MockDataReader.cs
deleted file mode 100644 (file)
index 224fa65..0000000
+++ /dev/null
@@ -1,194 +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.Generic;
-using System.Data.Common;
-using System.Threading;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    internal class MockDataReader : DbDataReader
-    {
-        public bool Fail { get; set; }
-        public int Ordinal { get; set; }
-        public CancellationToken CancellationToken { get; set; }
-        public string LastCommand { get; set; }
-
-        public IEnumerator<object[]> Results { get; set; }
-
-        public override int Depth
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override int FieldCount
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override bool GetBoolean(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override byte GetByte(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override char GetChar(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override string GetDataTypeName(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override DateTime GetDateTime(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override decimal GetDecimal(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override double GetDouble(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override System.Collections.IEnumerator GetEnumerator()
-        {
-            throw new NotImplementedException();
-        }
-
-        public override Type GetFieldType(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override float GetFloat(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override Guid GetGuid(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override short GetInt16(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override int GetInt32(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override long GetInt64(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override string GetName(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override int GetOrdinal(string name)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override string GetString(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override object GetValue(int ordinal)
-        {
-            if (Fail) { throw new InvalidOperationException("Fail requested"); }
-            LastCommand = "GetValue";
-            Ordinal = ordinal;
-            return Results.Current[ordinal];
-        }
-
-        public override int GetValues(object[] values)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override bool HasRows
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override bool IsClosed
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override bool IsDBNull(int ordinal)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override bool NextResult()
-        {
-            if (Fail) { throw new InvalidOperationException("Fail requested"); }
-            LastCommand = "NextResult";
-            return false;
-        }
-
-        public override bool Read()
-        {
-            if (Fail) { throw new InvalidOperationException("Fail requested"); }
-            LastCommand = "Read";
-            return Results.MoveNext();
-        }
-
-        public override int RecordsAffected
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override object this[string name]
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override object this[int ordinal]
-        {
-            get { throw new NotImplementedException(); }
-        }
-
-        public override System.Threading.Tasks.Task<bool> NextResultAsync(CancellationToken cancellationToken)
-        {
-            CancellationToken = cancellationToken;
-            return base.NextResultAsync(cancellationToken);
-        }
-
-        public override System.Threading.Tasks.Task<bool> ReadAsync(CancellationToken cancellationToken)
-        {
-            CancellationToken = cancellationToken;
-            return base.ReadAsync(cancellationToken);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/CloneTests.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/CloneTests.cs
deleted file mode 100644 (file)
index a726ded..0000000
+++ /dev/null
@@ -1,84 +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;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class CloneTests
-    {
-        [Fact]
-        public void CloneSqlConnection()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
-            builder.DataSource = "mybadServer";
-            builder.ConnectTimeout = 1;
-            builder.InitialCatalog = "northwinddb";
-            SqlConnection connection = new SqlConnection(builder.ConnectionString);
-
-            SqlConnection clonedConnection = (connection as ICloneable).Clone() as SqlConnection;
-            Assert.Equal(connection.ConnectionString, clonedConnection.ConnectionString);
-            Assert.Equal(connection.ConnectionTimeout, clonedConnection.ConnectionTimeout);
-            Assert.NotEqual(connection, clonedConnection);
-        }
-
-        [Fact]
-        public void CloneSqlCommand()
-        {
-            SqlConnection connection = new SqlConnection();
-
-            SqlCommand command = connection.CreateCommand();
-            command.CommandText = "select 1";
-            command.CommandTimeout = 45;
-            command.ResetCommandTimeout();
-            Assert.Equal(30, command.CommandTimeout);
-            command.CommandType = CommandType.Text;
-
-            SqlParameter parameter = command.CreateParameter();
-            parameter.Direction = ParameterDirection.Input;
-            parameter.DbType = DbType.Currency;
-            parameter.Size = 10;
-            parameter.Precision = 3;
-            parameter.Scale = 5;
-
-            command.Parameters.Add(parameter);
-
-            SqlCommand clonedCommand = command.Clone();
-            compareCommands(command, clonedCommand);
-
-            SqlCommand clonedByICloneable = (command as ICloneable).Clone() as SqlCommand;
-            compareCommands(command, clonedByICloneable);
-        }
-
-        [Fact]
-        public void CloneParameters()
-        {
-            SqlParameter parameter = new SqlParameter();
-            parameter.Direction = ParameterDirection.Input;
-            parameter.DbType = DbType.Currency;
-            parameter.Size = 10;
-            parameter.Precision = 3;
-            parameter.Scale = 5;
-
-            SqlParameter clonedParameter = (parameter as ICloneable).Clone() as SqlParameter;
-
-            Assert.Equal(parameter.Direction, clonedParameter.Direction);
-            Assert.Equal(parameter.DbType, clonedParameter.DbType);
-            Assert.Equal(parameter.Size, clonedParameter.Size);
-            Assert.Equal(parameter.Precision, clonedParameter.Precision);
-            Assert.Equal(parameter.Scale, clonedParameter.Scale);
-            Assert.NotEqual(parameter, clonedParameter);
-        }
-
-        private void compareCommands(SqlCommand original, SqlCommand cloned)
-        {
-            Assert.Equal(original.CommandText, cloned.CommandText);
-            Assert.Equal(original.CommandTimeout, cloned.CommandTimeout);
-            Assert.Equal(original.CommandType, cloned.CommandType);
-            Assert.Equal(original.Connection, cloned.Connection);
-            Assert.Equal(original.Parameters.Count, cloned.Parameters.Count);
-            Assert.NotEqual(original, cloned);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/Configurations.props b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/Configurations.props
deleted file mode 100644 (file)
index 9f1e7e9..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      $(NetFrameworkCurrent)-Windows_NT;
-      $(NetCoreAppCurrent)-Unix;
-      $(NetCoreAppCurrent)-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/DiagnosticTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/DiagnosticTest.cs
deleted file mode 100644 (file)
index 3152ab0..0000000
+++ /dev/null
@@ -1,924 +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.Diagnostics;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Threading.Tasks;
-using System.Xml;
-using Microsoft.DotNet.RemoteExecutor;
-using Microsoft.SqlServer.TDS;
-using Microsoft.SqlServer.TDS.Done;
-using Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.Error;
-using Microsoft.SqlServer.TDS.Servers;
-using Microsoft.SqlServer.TDS.SQLBatch;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class DiagnosticTest
-    {
-        private const string BadConnectionString = "data source = bad; initial catalog = bad; uid = bad; password = bad; connection timeout = 1;";
-        private static readonly string s_tcpConnStr = Environment.GetEnvironmentVariable("TEST_TCP_CONN_STR") ?? string.Empty;
-
-        public static bool IsConnectionStringConfigured() => s_tcpConnStr != string.Empty;
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteScalarTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name();";
-
-                        conn.Open();
-                        var output = cmd.ExecuteScalar();
-                    }
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteScalarErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select 1 / 0;";
-
-                        conn.Open();
-
-                        try { var output = cmd.ExecuteScalar(); }
-                        catch { }
-                    }
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteNonQueryTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name();";
-
-                        conn.Open();
-                        var output = cmd.ExecuteNonQuery();
-                    }
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteNonQueryErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    {
-                        using (SqlCommand cmd = new SqlCommand())
-                        {
-                            cmd.Connection = conn;
-                            cmd.CommandText = "select 1 / 0;";
-
-                            // Limiting the command timeout to 3 seconds. This should be lower than the Process timeout.
-                            cmd.CommandTimeout = 3;
-                            conn.Open();
-                            Console.WriteLine("SqlClient.DiagnosticTest.ExecuteNonQueryErrorTest Connection Open Successful");
-
-                            try
-                            {
-                                var output = cmd.ExecuteNonQuery();
-                            }
-                            catch (Exception e)
-                            {
-                                Console.WriteLine("SqlClient.DiagnosticTest.ExecuteNonQueryErrorTest " + e.Message);
-                            }
-                            Console.WriteLine("SqlClient.DiagnosticTest.ExecuteNonQueryErrorTest Command Executed");
-                        }
-                        Console.WriteLine("SqlClient.DiagnosticTest.ExecuteNonQueryErrorTest Command Disposed");
-                    }
-                    Console.WriteLine("SqlClient.DiagnosticTest.ExecuteNonQueryErrorTest Connection Disposed");
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteReaderTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name();";
-
-                        conn.Open();
-                        SqlDataReader reader = cmd.ExecuteReader();
-                        while (reader.Read()) { }
-                    }
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteReaderErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select 1 / 0;";
-
-                        try
-                        {
-                            SqlDataReader reader = cmd.ExecuteReader();
-                            while (reader.Read()) { }
-                        }
-                        catch { }
-                    }
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteReaderWithCommandBehaviorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name();";
-
-                        conn.Open();
-                        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
-                        while (reader.Read()) { }
-                    }
-                });
-            }).Dispose();
-        }
-
-        [ConditionalFact(nameof(IsConnectionStringConfigured))]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteXmlReaderTest()
-        {
-            RemoteExecutor.Invoke(cs =>
-            {
-                CollectStatisticsDiagnostics(_ =>
-                {
-                    using (SqlConnection conn = new SqlConnection(cs))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select * from sys.objects for xml auto, xmldata;";
-
-                        conn.Open();
-                        XmlReader reader = cmd.ExecuteXmlReader();
-                        while (reader.Read()) { }
-                    }
-                });
-            }, s_tcpConnStr).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteXmlReaderErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select *, baddata = 1 / 0 from sys.objects for xml auto, xmldata;";
-
-                        try
-                        {
-                            XmlReader reader = cmd.ExecuteXmlReader();
-                            while (reader.Read()) { }
-                        }
-                        catch { }
-                    }
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteScalarAsyncTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name();";
-
-                        conn.Open();
-                        var output = await cmd.ExecuteScalarAsync();
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteScalarAsyncErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select 1 / 0;";
-
-                        conn.Open();
-
-                        try { var output = await cmd.ExecuteScalarAsync(); }
-                        catch { }
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteNonQueryAsyncTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name();";
-
-                        conn.Open();
-                        var output = await cmd.ExecuteNonQueryAsync();
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteNonQueryAsyncErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select 1 / 0;";
-
-                        conn.Open();
-                        try { var output = await cmd.ExecuteNonQueryAsync(); }
-                        catch { }
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteReaderAsyncTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name();";
-
-                        conn.Open();
-                        SqlDataReader reader = await cmd.ExecuteReaderAsync();
-                        while (reader.Read()) { }
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteReaderAsyncErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async connectionString =>
-                {
-                    using (SqlConnection conn = new SqlConnection(connectionString))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select 1 / 0;";
-
-                        try
-                        {
-                            SqlDataReader reader = await cmd.ExecuteReaderAsync();
-                            while (reader.Read()) { }
-                        }
-                        catch { }
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        [ConditionalFact(nameof(IsConnectionStringConfigured))]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteXmlReaderAsyncTest()
-        {
-            RemoteExecutor.Invoke(cs =>
-            {
-                CollectStatisticsDiagnosticsAsync(async _ =>
-                {
-                    using (SqlConnection conn = new SqlConnection(cs))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select * from sys.objects for xml auto, xmldata;";
-
-                        conn.Open();
-                        XmlReader reader = await cmd.ExecuteXmlReaderAsync();
-                        while (reader.Read()) { }
-                    }
-                }).GetAwaiter().GetResult();
-            }, s_tcpConnStr).Dispose();
-        }
-
-        [ConditionalFact(nameof(IsConnectionStringConfigured))]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ExecuteXmlReaderAsyncErrorTest()
-        {
-            RemoteExecutor.Invoke(cs =>
-            {
-                CollectStatisticsDiagnosticsAsync(async _ =>
-                {
-                    using (SqlConnection conn = new SqlConnection(cs))
-                    using (SqlCommand cmd = new SqlCommand())
-                    {
-                        cmd.Connection = conn;
-                        cmd.CommandText = "select *, baddata = 1 / 0 from sys.objects for xml auto, xmldata;";
-
-                        try
-                        {
-                            XmlReader reader = await cmd.ExecuteXmlReaderAsync();
-                            while (reader.Read()) { }
-                        }
-                        catch { }
-                    }
-                }).GetAwaiter().GetResult();
-            }, s_tcpConnStr).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ConnectionOpenTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(connectionString =>
-                {
-                    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
-                    {
-                        sqlConnection.Open();
-                        Console.WriteLine("SqlClient.DiagnosticsTest.ConnectionOpenTest:: Connection Opened ");
-                    }
-                    Console.WriteLine("SqlClient.DiagnosticsTest.ConnectionOpenTest:: Connection Should Be Disposed");
-                }, true);
-
-                Console.WriteLine("SqlClient.DiagnosticsTest.ConnectionOpenTest:: Done with Diagnostics collection");
-            }).Dispose();
-        }
-
-        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue("https://github.com/dotnet/corefx/issues/11057")]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ConnectionOpenErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnostics(_ =>
-                {
-                    using (SqlConnection sqlConnection = new SqlConnection(BadConnectionString))
-                    {
-                        try { sqlConnection.Open(); } catch { }
-                    }
-                });
-            }).Dispose();
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ConnectionOpenAsyncTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async connectionString =>
-                {
-                    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
-                    {
-                        await sqlConnection.OpenAsync();
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue("https://github.com/dotnet/corefx/issues/11057")]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework,  "Feature not available on Framework")]
-        public void ConnectionOpenAsyncErrorTest()
-        {
-            RemoteExecutor.Invoke(() =>
-            {
-                CollectStatisticsDiagnosticsAsync(async _ =>
-                {
-                    using (SqlConnection sqlConnection = new SqlConnection(BadConnectionString))
-                    {
-                        try { await sqlConnection.OpenAsync(); } catch { }
-                    }
-                }).GetAwaiter().GetResult();
-            }).Dispose();
-        }
-
-        private static void CollectStatisticsDiagnostics(Action<string> sqlOperation, bool enableServerLogging = false, [CallerMemberName] string methodName = "")
-        {
-            bool statsLogged = false;
-            bool operationHasError = false;
-            Guid beginOperationId = Guid.Empty;
-
-            FakeDiagnosticListenerObserver diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
-                {
-                    IDictionary statistics;
-
-                    if (kvp.Key.Equals("System.Data.SqlClient.WriteCommandBefore"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        Guid retrievedOperationId = GetPropertyValueFromType<Guid>(kvp.Value, "OperationId");
-                        Assert.NotEqual(retrievedOperationId, Guid.Empty);
-
-                        SqlCommand sqlCommand = GetPropertyValueFromType<SqlCommand>(kvp.Value, "Command");
-                        Assert.NotNull(sqlCommand);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                        if (sqlCommand.Connection.State == ConnectionState.Open)
-                        {
-                            Assert.NotEqual(connectionId, Guid.Empty);
-                        }
-
-                        beginOperationId = retrievedOperationId;
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteCommandAfter"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        Guid retrievedOperationId = GetPropertyValueFromType<Guid>(kvp.Value, "OperationId");
-                        Assert.NotEqual(retrievedOperationId, Guid.Empty);
-
-                        SqlCommand sqlCommand = GetPropertyValueFromType<SqlCommand>(kvp.Value, "Command");
-                        Assert.NotNull(sqlCommand);
-
-                        statistics = GetPropertyValueFromType<IDictionary>(kvp.Value, "Statistics");
-                        if (!operationHasError)
-                            Assert.NotNull(statistics);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                        if (sqlCommand.Connection.State == ConnectionState.Open)
-                        {
-                            Assert.NotEqual(connectionId, Guid.Empty);
-                        }
-
-                        // if we get to this point, then statistics exist and this must be the "end"
-                        // event, so we need to make sure the operation IDs match
-                        Assert.Equal(retrievedOperationId, beginOperationId);
-                        beginOperationId = Guid.Empty;
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteCommandError"))
-                    {
-                        operationHasError = true;
-                        Assert.NotNull(kvp.Value);
-
-                        SqlCommand sqlCommand = GetPropertyValueFromType<SqlCommand>(kvp.Value, "Command");
-                        Assert.NotNull(sqlCommand);
-
-                        Exception ex = GetPropertyValueFromType<Exception>(kvp.Value, "Exception");
-                        Assert.NotNull(ex);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                        if (sqlCommand.Connection.State == ConnectionState.Open)
-                        {
-                            Assert.NotEqual(connectionId, Guid.Empty);
-                        }
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionOpenBefore"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                        Assert.NotNull(sqlConnection);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionOpenAfter"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                        Assert.NotNull(sqlConnection);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        statistics = GetPropertyValueFromType<IDictionary>(kvp.Value, "Statistics");
-                        Assert.NotNull(statistics);
-
-                        Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                        Assert.NotEqual(connectionId, Guid.Empty);
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionOpenError"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                        Assert.NotNull(sqlConnection);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        Exception ex = GetPropertyValueFromType<Exception>(kvp.Value, "Exception");
-                        Assert.NotNull(ex);
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionCloseBefore"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                        Assert.NotNull(sqlConnection);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                        Assert.NotEqual(connectionId, Guid.Empty);
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionCloseAfter"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                        Assert.NotNull(sqlConnection);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        statistics = GetPropertyValueFromType<IDictionary>(kvp.Value, "Statistics");
-
-                        Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                        Assert.NotEqual(connectionId, Guid.Empty);
-
-                        statsLogged = true;
-                    }
-                    else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionCloseError"))
-                    {
-                        Assert.NotNull(kvp.Value);
-
-                        SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                        Assert.NotNull(sqlConnection);
-
-                        string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                        Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                        Exception ex = GetPropertyValueFromType<Exception>(kvp.Value, "Exception");
-                        Assert.NotNull(ex);
-
-                        Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                        Assert.NotEqual(connectionId, Guid.Empty);
-
-                        statsLogged = true;
-                    }
-                });
-
-            diagnosticListenerObserver.Enable();
-            using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
-            {
-
-                Console.WriteLine(string.Format("Test: {0} Enabled Listeners", methodName));
-                using (var server = TestTdsServer.StartServerWithQueryEngine(new DiagnosticsQueryEngine(), enableLog:enableServerLogging, methodName: methodName))
-                {
-                    Console.WriteLine(string.Format("Test: {0} Started Server", methodName));
-                    sqlOperation(server.ConnectionString);
-
-                    Console.WriteLine(string.Format("Test: {0} SqlOperation Successful", methodName));
-
-                    Assert.True(statsLogged);
-
-                    diagnosticListenerObserver.Disable();
-
-                    Console.WriteLine(string.Format("Test: {0} Listeners Disabled", methodName));
-                }
-                Console.WriteLine(string.Format("Test: {0} Server Disposed", methodName));
-            }
-            Console.WriteLine(string.Format("Test: {0} Listeners Disposed Successfully", methodName));
-        }
-
-        private static async Task CollectStatisticsDiagnosticsAsync(Func<string, Task> sqlOperation, [CallerMemberName] string methodName = "")
-        {
-            bool statsLogged = false;
-            bool operationHasError = false;
-            Guid beginOperationId = Guid.Empty;
-
-            FakeDiagnosticListenerObserver diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
-            {
-                IDictionary statistics;
-
-                if (kvp.Key.Equals("System.Data.SqlClient.WriteCommandBefore"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    Guid retrievedOperationId = GetPropertyValueFromType<Guid>(kvp.Value, "OperationId");
-                    Assert.NotEqual(retrievedOperationId, Guid.Empty);
-
-                    SqlCommand sqlCommand = GetPropertyValueFromType<SqlCommand>(kvp.Value, "Command");
-                    Assert.NotNull(sqlCommand);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    beginOperationId = retrievedOperationId;
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteCommandAfter"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    Guid retrievedOperationId = GetPropertyValueFromType<Guid>(kvp.Value, "OperationId");
-                    Assert.NotEqual(retrievedOperationId, Guid.Empty);
-
-                    SqlCommand sqlCommand = GetPropertyValueFromType<SqlCommand>(kvp.Value, "Command");
-                    Assert.NotNull(sqlCommand);
-
-                    statistics = GetPropertyValueFromType<IDictionary>(kvp.Value, "Statistics");
-                    if (!operationHasError)
-                        Assert.NotNull(statistics);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    // if we get to this point, then statistics exist and this must be the "end"
-                    // event, so we need to make sure the operation IDs match
-                    Assert.Equal(retrievedOperationId, beginOperationId);
-                    beginOperationId = Guid.Empty;
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteCommandError"))
-                {
-                    operationHasError = true;
-                    Assert.NotNull(kvp.Value);
-
-                    SqlCommand sqlCommand = GetPropertyValueFromType<SqlCommand>(kvp.Value, "Command");
-                    Assert.NotNull(sqlCommand);
-
-                    Exception ex = GetPropertyValueFromType<Exception>(kvp.Value, "Exception");
-                    Assert.NotNull(ex);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionOpenBefore"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                    Assert.NotNull(sqlConnection);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionOpenAfter"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                    Assert.NotNull(sqlConnection);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    statistics = GetPropertyValueFromType<IDictionary>(kvp.Value, "Statistics");
-                    Assert.NotNull(statistics);
-
-                    Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                    if (sqlConnection.State == ConnectionState.Open)
-                    {
-                        Assert.NotEqual(connectionId, Guid.Empty);
-                    }
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionOpenError"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                    Assert.NotNull(sqlConnection);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    Exception ex = GetPropertyValueFromType<Exception>(kvp.Value, "Exception");
-                    Assert.NotNull(ex);
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionCloseBefore"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                    Assert.NotNull(sqlConnection);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                    Assert.NotEqual(connectionId, Guid.Empty);
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionCloseAfter"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                    Assert.NotNull(sqlConnection);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    statistics = GetPropertyValueFromType<IDictionary>(kvp.Value, "Statistics");
-
-                    Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                    Assert.NotEqual(connectionId, Guid.Empty);
-
-                    statsLogged = true;
-                }
-                else if (kvp.Key.Equals("System.Data.SqlClient.WriteConnectionCloseError"))
-                {
-                    Assert.NotNull(kvp.Value);
-
-                    SqlConnection sqlConnection = GetPropertyValueFromType<SqlConnection>(kvp.Value, "Connection");
-                    Assert.NotNull(sqlConnection);
-
-                    string operation = GetPropertyValueFromType<string>(kvp.Value, "Operation");
-                    Assert.False(string.IsNullOrWhiteSpace(operation));
-
-                    Exception ex = GetPropertyValueFromType<Exception>(kvp.Value, "Exception");
-                    Assert.NotNull(ex);
-
-                    Guid connectionId = GetPropertyValueFromType<Guid>(kvp.Value, "ConnectionId");
-                    Assert.NotEqual(connectionId, Guid.Empty);
-
-                    statsLogged = true;
-                }
-            });
-
-            diagnosticListenerObserver.Enable();
-            using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
-            {
-                Console.WriteLine(string.Format("Test: {0} Enabled Listeners", methodName));
-                using (var server = TestTdsServer.StartServerWithQueryEngine(new DiagnosticsQueryEngine(), methodName: methodName))
-                {
-                    Console.WriteLine(string.Format("Test: {0} Started Server", methodName));
-
-                    await sqlOperation(server.ConnectionString);
-
-                    Console.WriteLine(string.Format("Test: {0} SqlOperation Successful", methodName));
-
-                    Assert.True(statsLogged);
-
-                    diagnosticListenerObserver.Disable();
-
-                    Console.WriteLine(string.Format("Test: {0} Listeners Disabled", methodName));
-                }
-                Console.WriteLine(string.Format("Test: {0} Server Disposed", methodName));
-            }
-            Console.WriteLine(string.Format("Test: {0} Listeners Disposed Successfully", methodName));
-        }
-
-        private static T GetPropertyValueFromType<T>(object obj, string propName)
-        {
-            Type type = obj.GetType();
-            PropertyInfo pi = type.GetRuntimeProperty(propName);
-
-            var propertyValue = pi.GetValue(obj);
-            return (T)propertyValue;
-        }
-    }
-
-    public class DiagnosticsQueryEngine : QueryEngine
-    {
-        public DiagnosticsQueryEngine() : base(new TDSServerArguments())
-        {
-        }
-
-        protected override TDSMessageCollection CreateQueryResponse(ITDSServerSession session, TDSSQLBatchToken batchRequest)
-        {
-            string lowerBatchText = batchRequest.Text.ToLowerInvariant();
-
-            if (lowerBatchText.Contains("1 / 0")) // SELECT 1/0
-            {
-                TDSErrorToken errorToken = new TDSErrorToken(8134, 1, 16, "Divide by zero error encountered.");
-                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-                TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken, doneToken);
-                return new TDSMessageCollection(responseMessage);
-            }
-            else
-            {
-                return base.CreateQueryResponse(session, batchRequest);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs
deleted file mode 100644 (file)
index 86d52fd..0000000
+++ /dev/null
@@ -1,224 +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 Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class ExceptionTest
-    {
-        // test connection string
-        private string connectionString = "server=tcp:server,1432;database=test;uid=admin;pwd=SQLDB;connect timeout=60;";
-
-        // data value and server consts
-        private const string badServer = "NotAServer";
-        private const string sqlsvrBadConn = "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.";
-        private const string execReaderFailedMessage = "ExecuteReader requires an open and available Connection. The connection's current state is closed.";
-        private const string orderIdQuery = "select orderid from orders where orderid < 10250";
-
-        [Fact]
-        public void ExceptionTests()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
-
-            // tests improper server name thrown from constructor of tdsparser
-            SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
-
-            VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), sqlsvrBadConn, VerifyException);
-        }
-
-        [Fact]
-        public void VariousExceptionTests()
-        {
-            // Test exceptions - makes sure they are only thrown from upper layers
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
-
-            SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
-            using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
-            {
-                using (SqlCommand command = sqlConnection.CreateCommand())
-                {
-                    command.CommandText = orderIdQuery;
-                    VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
-                }
-            }
-        }
-
-        [Fact]
-        public void IndependentConnectionExceptionTestOpenConnection()
-        {
-            // Test exceptions for existing connection to ensure proper exception and call stack
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
-
-            SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
-            using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
-            {
-                VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), sqlsvrBadConn, VerifyException);
-            }
-        }
-
-        [Fact]
-        public void IndependentConnectionExceptionTestExecuteReader()
-        {
-            // Test exceptions for existing connection to ensure proper exception and call stack
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
-
-            SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
-            using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
-            {
-                using (SqlCommand command = new SqlCommand(orderIdQuery, sqlConnection))
-                {
-                    VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
-                }
-            }
-        }
-
-        [Theory]
-        [InlineData(@"np:\\.\pipe\sqlbad\query")]
-        [InlineData(@"np:\\.\pipe\MSSQL$NonExistentInstance\sql\query")]
-        [InlineData(@"\\.\pipe\sqlbad\query")]
-        [InlineData(@"\\.\pipe\MSSQL$NonExistentInstance\sql\query")]
-        [InlineData(@"np:\\localhost\pipe\sqlbad\query")]
-        [InlineData(@"np:\\localhost\pipe\MSSQL$NonExistentInstance\sqlbad\query")]
-        [InlineData(@"\\localhost\pipe\sqlbad\query")]
-        [InlineData(@"\\localhost\pipe\MSSQL$NonExistentInstance\sqlbad\query")]
-        [PlatformSpecific(TestPlatforms.Windows)] // Named pipes with the given input strings are not supported on Unix
-        public void NamedPipeTest(string dataSource)
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
-            builder.DataSource = dataSource;
-            builder.ConnectTimeout = 1;
-
-            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
-            {
-                string expectedErrorMsg = "(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)";
-                VerifyConnectionFailure<SqlException>(() => connection.Open(), expectedErrorMsg);
-            }
-        }
-
-        public static bool IsUsingManagedSNI() => ManualTesting.Tests.DataTestUtility.IsUsingManagedSNI();
-
-        [ConditionalFact(nameof(IsUsingManagedSNI))]
-        public void NamedPipeInvalidConnStringTest_ManagedSNI()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
-            builder.ConnectTimeout = 1;
-
-            string invalidConnStringError = "(provider: Named Pipes Provider, error: 25 - Connection string is not valid)";
-            string fakeServerName = Guid.NewGuid().ToString("N");
-
-            // Using forward slashes
-            builder.DataSource = "np://" + fakeServerName + "/pipe/sql/query";
-            OpenBadConnection(builder.ConnectionString, invalidConnStringError);
-
-            // Without pipe token
-            builder.DataSource = @"np:\\" + fakeServerName + @"\sql\query";
-            OpenBadConnection(builder.ConnectionString, invalidConnStringError);
-
-            // Without a pipe name
-            builder.DataSource = @"np:\\" + fakeServerName + @"\pipe";
-            OpenBadConnection(builder.ConnectionString, invalidConnStringError);
-
-            // Nothing after server
-            builder.DataSource = @"np:\\" + fakeServerName;
-            OpenBadConnection(builder.ConnectionString, invalidConnStringError);
-
-            // No leading slashes
-            builder.DataSource = @"np:" + fakeServerName + @"\pipe\sql\query";
-            OpenBadConnection(builder.ConnectionString, invalidConnStringError);
-
-            // No server name
-            builder.DataSource = @"np:\\\pipe\sql\query";
-            OpenBadConnection(builder.ConnectionString, invalidConnStringError);
-
-            // Nothing but slashes
-            builder.DataSource = @"np:\\\\\";
-            OpenBadConnection(builder.ConnectionString, invalidConnStringError);
-        }
-
-        private void GenerateConnectionException(string connectionString)
-        {
-            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
-            {
-                sqlConnection.Open();
-                using (SqlCommand command = sqlConnection.CreateCommand())
-                {
-                    command.CommandText = orderIdQuery;
-                    command.ExecuteReader();
-                }
-            }
-        }
-
-        private TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage, Func<TException, bool> exVerifier) where TException : Exception
-        {
-            TException ex = Assert.Throws<TException>(connectAction);
-
-            // Some exception messages are different between Framework and Core
-            if (!PlatformDetection.IsNetFramework)
-            {
-                Assert.Contains(expectedExceptionMessage, ex.Message);
-            }
-            Assert.True(exVerifier(ex), "FAILED Exception verifier failed on the exception.");
-
-            return ex;
-        }
-
-        private void OpenBadConnection(string connectionString, string errorMsg)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                VerifyConnectionFailure<SqlException>(() => conn.Open(), errorMsg);
-            }
-        }
-
-        private TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage) where TException : Exception
-        {
-            return VerifyConnectionFailure<TException>(connectAction, expectedExceptionMessage, (ex) => true);
-        }
-
-        private bool VerifyException(SqlException exception)
-        {
-            VerifyException(exception, 1);
-            return true;
-        }
-
-        private bool VerifyException(SqlException exception, int count, int? errorNumber = null, int? errorState = null, int? severity = null)
-        {
-            Assert.NotEmpty(exception.Errors);
-            Assert.Equal(count, exception.Errors.Count);
-
-            // Ensure that all errors have an error-level severity
-            for (int i = 0; i < count; i++)
-            {
-                Assert.InRange(exception.Errors[i].Class, 10, byte.MaxValue);
-            }
-
-            // Check the properties of the exception populated by the server are correct
-            if (errorNumber.HasValue)
-            {
-                Assert.Equal(errorNumber.Value, exception.Number);
-            }
-
-            if (errorState.HasValue)
-            {
-                Assert.Equal(errorState.Value, exception.State);
-            }
-
-            if (severity.HasValue)
-            {
-                Assert.Equal(severity.Value, exception.Class);
-            }
-
-            if ((errorNumber.HasValue) && (errorState.HasValue) && (severity.HasValue))
-            {
-                string expected = $"Error Number:{errorNumber.Value},State:{errorState.Value},Class:{severity.Value}";
-                Assert.Contains(expected, exception.ToString());
-            }
-
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/FakeDiagnosticListenerObserver.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/FakeDiagnosticListenerObserver.cs
deleted file mode 100644 (file)
index f9f6e92..0000000
+++ /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.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient.Tests
-{
-    public sealed class FakeDiagnosticListenerObserver : IObserver<DiagnosticListener>
-    {
-        private class FakeDiagnosticSourceWriteObserver : IObserver<KeyValuePair<string, object>>
-        {
-            private readonly Action<KeyValuePair<string, object>> _writeCallback;
-
-            public FakeDiagnosticSourceWriteObserver(Action<KeyValuePair<string, object>> writeCallback)
-            {
-                _writeCallback = writeCallback;
-            }
-
-            public void OnCompleted()
-            {
-            }
-
-            public void OnError(Exception error)
-            {
-            }
-
-            public void OnNext(KeyValuePair<string, object> value)
-            {
-                _writeCallback(value);
-            }
-        }
-
-        private readonly Action<KeyValuePair<string, object>> _writeCallback;
-        private bool _writeObserverEnabled;
-
-        public FakeDiagnosticListenerObserver(Action<KeyValuePair<string, object>> writeCallback)
-        {
-            _writeCallback = writeCallback;
-        }
-
-        public void OnCompleted()
-        {
-        }
-
-        public void OnError(Exception error)
-        {
-        }
-
-        public void OnNext(DiagnosticListener value)
-        {
-            if (value.Name.Equals("SqlClientDiagnosticListener"))
-            {
-                value.Subscribe(new FakeDiagnosticSourceWriteObserver(_writeCallback), IsEnabled);
-            }
-        }
-
-        public void Enable()
-        {
-            _writeObserverEnabled = true;
-        }
-        public void Disable()
-        {
-            _writeObserverEnabled = false;
-        }
-        private bool IsEnabled(string s)
-        {
-            return _writeObserverEnabled;
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlBulkCopyColumnMappingCollectionTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlBulkCopyColumnMappingCollectionTest.cs
deleted file mode 100644 (file)
index 9323139..0000000
+++ /dev/null
@@ -1,521 +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.Diagnostics;
-
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlBulkCopyColumnMappingCollectionTest
-    {
-        private static SqlBulkCopyColumnMappingCollection CreateCollection() => new SqlBulkCopy(new SqlConnection()).ColumnMappings;
-
-        private static SqlBulkCopyColumnMappingCollection CreateCollection(params SqlBulkCopyColumnMapping[] mappings)
-        {
-            Debug.Assert(mappings != null);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-
-            foreach (SqlBulkCopyColumnMapping mapping in mappings)
-            {
-                Debug.Assert(mapping != null);
-                collection.Add(mapping);
-            }
-
-            return collection;
-        }
-
-        [Fact]
-        public void Properties_ReturnFalse()
-        {
-            IList list = CreateCollection();
-            Assert.False(list.IsSynchronized);
-            Assert.False(list.IsFixedSize);
-            Assert.False(list.IsReadOnly);
-        }
-
-        [Fact]
-        public void Methods_NullParameterPassed_ThrowsArgumentNullException()
-        {
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-            collection.Add(new SqlBulkCopyColumnMapping());
-
-            Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0));
-
-            // Passing null to the public Add method should really throw ArgumentNullException
-            // (which would be consistent with the explicit implementation of IList.Add), but
-            // the full framework does not check for null in the public Add method. Instead it
-            // accesses the parameter without first checking for null, resulting in
-            // NullReferenceExpcetion being thrown.
-            Assert.Throws<NullReferenceException>(() => collection.Add(null));
-
-            // Passing null to the public Insert and Remove methods should really throw
-            // ArgumentNullException (which would be consistent with the explicit
-            // implementations of IList.Insert and IList.Remove), but the full framework
-            // does not check for null in these methods.
-            collection.Insert(0, null);
-            collection.Remove(null);
-
-
-            IList list = collection;
-            Assert.Throws<ArgumentNullException>(() => list[0] = null);
-            Assert.Throws<ArgumentNullException>(() => list.Add(null));
-            Assert.Throws<ArgumentNullException>(() => list.CopyTo(null, 0));
-            Assert.Throws<ArgumentNullException>(() => list.Insert(0, null));
-            Assert.Throws<ArgumentNullException>(() => list.Remove(null));
-        }
-
-        [Fact]
-        public void Members_InvalidRange_ThrowsArgumentOutOfRangeException()
-        {
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-
-            var item = new SqlBulkCopyColumnMapping(0, 0);
-
-            Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]);
-            Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]);
-            Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, item));
-            Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, item));
-            Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1));
-            Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count));
-
-            IList list = collection;
-            Assert.Throws<ArgumentOutOfRangeException>(() => list[-1]);
-            Assert.Throws<ArgumentOutOfRangeException>(() => list[collection.Count]);
-            Assert.Throws<ArgumentOutOfRangeException>(() => list[-1] = item);
-            Assert.Throws<ArgumentOutOfRangeException>(() => list[collection.Count] = item);
-            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, item));
-            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(collection.Count + 1, item));
-            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
-            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(collection.Count));
-        }
-
-        [Fact]
-        public void Add_AddItems_ItemsAddedAsEpected()
-        {
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            Assert.Same(item1, collection.Add(item1));
-            Assert.Same(item1, collection[0]);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            Assert.Same(item2, collection.Add(item2));
-            Assert.Same(item2, collection[1]);
-
-            IList list = CreateCollection();
-            int index = list.Add(item1);
-            Assert.Equal(0, index);
-            Assert.Same(item1, list[0]);
-            index = list.Add(item2);
-            Assert.Equal(1, index);
-            Assert.Same(item2, list[1]);
-        }
-
-        [Fact]
-        public void Add_HelperOverloads_ItemsAddedAsExpected()
-        {
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-            SqlBulkCopyColumnMapping item;
-
-            item = collection.Add(3, 4);
-            Assert.NotNull(item);
-            Assert.Equal(3, item.SourceOrdinal);
-            Assert.Equal(4, item.DestinationOrdinal);
-
-            item = collection.Add(5, "destination");
-            Assert.NotNull(item);
-            Assert.Equal(5, item.SourceOrdinal);
-            Assert.Equal("destination", item.DestinationColumn);
-
-            item = collection.Add("source", 6);
-            Assert.NotNull(item);
-            Assert.Equal("source", item.SourceColumn);
-            Assert.Equal(6, item.DestinationOrdinal);
-
-            item = collection.Add("src", "dest");
-            Assert.NotNull(item);
-            Assert.Equal("src", item.SourceColumn);
-            Assert.Equal("dest", item.DestinationColumn);
-        }
-
-        [Fact]
-        public void Add_InvalidItems_ThrowsInvalidOperationException()
-        {
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-            Assert.Throws<InvalidOperationException>(() => collection.Add(new SqlBulkCopyColumnMapping { SourceColumn = null }));
-            Assert.Throws<InvalidOperationException>(() => collection.Add(new SqlBulkCopyColumnMapping { DestinationColumn = null }));
-
-            // The explicitly implemented IList.Add should really throw InvalidOperationException to match the public
-            // Add method behavior, but does not throw in the full framework.
-            IList list = CreateCollection();
-            Assert.Equal(0, list.Add(new SqlBulkCopyColumnMapping { SourceColumn = null }));
-            Assert.Equal(1, list.Add(new SqlBulkCopyColumnMapping { DestinationColumn = null }));
-        }
-
-        [Fact]
-        public void IListAddInsert_InsertNonSqlBulkCopyColumnMappingItems_DoNotThrow()
-        {
-            IList list = CreateCollection();
-            list.Add(new SqlBulkCopyColumnMapping());
-
-            // The following operations should really throw ArgumentException due to the
-            // mismatched types, but do not throw in the full framework.
-            string bogus = "Bogus";
-            list[0] = bogus;
-            list.Add(bogus);
-            list.Insert(0, bogus);
-        }
-
-        [Fact]
-        public void GetEnumerator_NoItems_EmptyEnumerator()
-        {
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-            IEnumerator e = collection.GetEnumerator();
-            Assert.Throws<InvalidOperationException>(() => e.Current);
-            Assert.False(e.MoveNext());
-            Assert.Throws<InvalidOperationException>(() => e.Current);
-        }
-
-        [Fact]
-        public void GetEnumerator_ItemsAdded_AllItemsReturnedAndEnumeratorBehavesAsExpected()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2, item3);
-
-            IEnumerator e = collection.GetEnumerator();
-
-            const int Iterations = 2;
-            for (int i = 0; i < Iterations; i++)
-            {
-                // Not started
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                Assert.True(e.MoveNext());
-                Assert.Same(item1, e.Current);
-
-                Assert.True(e.MoveNext());
-                Assert.Same(item2, e.Current);
-
-                Assert.True(e.MoveNext());
-                Assert.Same(item3, e.Current);
-
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-
-                // Ended
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                e.Reset();
-            }
-        }
-
-        [Fact]
-        public void GetEnumerator_ItemsAdded_ItemsFromEnumeratorMatchesItemsFromIndexer()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2, item3);
-
-            int index = 0;
-            foreach (SqlBulkCopyColumnMapping enumeratorItem in collection)
-            {
-                SqlBulkCopyColumnMapping indexerItem = collection[index];
-
-                Assert.NotNull(enumeratorItem);
-                Assert.NotNull(indexerItem);
-
-                Assert.Same(indexerItem, enumeratorItem);
-                index++;
-            }
-        }
-
-        [Fact]
-        public void GetEnumerator_ModifiedCollectionDuringEnumeration_ThrowsInvalidOperationException()
-        {
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-
-            IEnumerator e = collection.GetEnumerator();
-
-            collection.Add(0, 0);
-
-            // Collection changed.
-            Assert.Throws<InvalidOperationException>(() => e.MoveNext());
-            Assert.Throws<InvalidOperationException>(() => e.Reset());
-        }
-
-
-        [Fact]
-        public void Contains_ItemsAdded_MatchesExpectation()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2, item3);
-
-            Assert.True(collection.Contains(item1));
-            Assert.True(collection.Contains(item2));
-            Assert.True(collection.Contains(item3));
-            Assert.False(collection.Contains(null));
-
-            IList list = collection;
-            Assert.True(list.Contains(item1));
-            Assert.True(list.Contains(item2));
-            Assert.True(list.Contains(item3));
-            Assert.False(list.Contains(null));
-            Assert.False(list.Contains("Bogus"));
-        }
-
-        [Fact]
-        public void CopyTo_ItemsAdded_ItemsCopiedToArray()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2, item3);
-
-            var array1 = new SqlBulkCopyColumnMapping[collection.Count];
-            collection.CopyTo(array1, 0);
-
-            Assert.Same(item1, array1[0]);
-            Assert.Same(item2, array1[1]);
-            Assert.Same(item3, array1[2]);
-
-            var array2 = new SqlBulkCopyColumnMapping[collection.Count];
-            ((ICollection)collection).CopyTo(array2, 0);
-
-            Assert.Same(item1, array2[0]);
-            Assert.Same(item2, array2[1]);
-            Assert.Same(item3, array2[2]);
-        }
-
-        [Fact]
-        public void CopyTo_InvalidArrayType_Throws()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            ICollection collection = CreateCollection(item1, item2, item3);
-
-            Assert.Throws<InvalidCastException>(() => collection.CopyTo(new int[collection.Count], 0));
-            Assert.Throws<InvalidCastException>(() => collection.CopyTo(new string[collection.Count], 0));
-        }
-
-        [Fact]
-        public void Indexer_BehavesAsExpected()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2, item3);
-
-            Assert.Same(item1, collection[0]);
-            Assert.Same(item2, collection[1]);
-            Assert.Same(item3, collection[2]);
-
-            IList list = collection;
-            list[0] = item2;
-            list[1] = item3;
-            list[2] = item1;
-            Assert.Same(item2, list[0]);
-            Assert.Same(item3, list[1]);
-            Assert.Same(item1, list[2]);
-        }
-
-        [Fact]
-        public void IndexOf_BehavesAsExpected()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2);
-
-            Assert.Equal(0, collection.IndexOf(item1));
-            Assert.Equal(1, collection.IndexOf(item2));
-            Assert.Equal(-1, collection.IndexOf(item3));
-
-            IList list = collection;
-            Assert.Equal(0, list.IndexOf(item1));
-            Assert.Equal(1, list.IndexOf(item2));
-            Assert.Equal(-1, list.IndexOf(item3));
-            Assert.Equal(-1, list.IndexOf("bogus"));
-        }
-
-        [Fact]
-        public void Insert_BehavesAsExpected()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-
-            collection.Insert(0, item3);
-            collection.Insert(0, item2);
-            collection.Insert(0, item1);
-
-            Assert.Equal(3, collection.Count);
-            Assert.Same(item1, collection[0]);
-            Assert.Same(item2, collection[1]);
-            Assert.Same(item3, collection[2]);
-        }
-
-        [Fact]
-        public void InsertAndClear_BehavesAsExpected()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection();
-
-            collection.Insert(0, item1);
-            collection.Insert(1, item2);
-            collection.Insert(2, item3);
-            Assert.Equal(3, collection.Count);
-            Assert.Same(item1, collection[0]);
-            Assert.Same(item2, collection[1]);
-            Assert.Same(item3, collection[2]);
-
-            collection.Clear();
-            Assert.Equal(0, collection.Count);
-
-            collection.Add(item1);
-            collection.Add(item3);
-            Assert.Equal(2, collection.Count);
-            Assert.Same(item1, collection[0]);
-            Assert.Same(item3, collection[1]);
-
-            collection.Insert(1, item2);
-            Assert.Equal(3, collection.Count);
-            Assert.Same(item1, collection[0]);
-            Assert.Same(item2, collection[1]);
-            Assert.Same(item3, collection[2]);
-
-            collection.Clear();
-            Assert.Equal(0, collection.Count);
-
-            IList list = collection;
-            list.Insert(0, item1);
-            list.Insert(1, item2);
-            list.Insert(2, item3);
-            Assert.Equal(3, list.Count);
-            Assert.Same(item1, list[0]);
-            Assert.Same(item2, list[1]);
-            Assert.Same(item3, list[2]);
-
-            list.Clear();
-            Assert.Equal(0, list.Count);
-
-            list.Add(item1);
-            list.Add(item3);
-            Assert.Equal(2, list.Count);
-            Assert.Same(item1, list[0]);
-            Assert.Same(item3, list[1]);
-
-            list.Insert(1, item2);
-            Assert.Equal(3, list.Count);
-            Assert.Same(item1, list[0]);
-            Assert.Same(item2, list[1]);
-            Assert.Same(item3, list[2]);
-
-            list.Clear();
-            Assert.Equal(0, list.Count);
-        }
-
-        [Fact]
-        public void Remove_BehavesAsExpected()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2);
-
-            collection.Remove(item1);
-            Assert.Equal(1, collection.Count);
-            Assert.Same(item2, collection[0]);
-
-            collection.Remove(item2);
-            Assert.Equal(0, collection.Count);
-
-            // The explicit implementation of IList.Remove throws ArgumentException if
-            // the item isn't in the collection, but the public Remove method does not
-            // throw in the full framework.
-            collection.Remove(item2);
-            collection.Remove(new SqlBulkCopyColumnMapping(2, 2));
-
-
-            IList list = CreateCollection(item1, item2);
-
-            list.Remove(item1);
-            Assert.Equal(1, list.Count);
-            Assert.Same(item2, list[0]);
-
-            list.Remove(item2);
-            Assert.Equal(0, list.Count);
-
-            AssertExtensions.Throws<ArgumentException>(null, () => list.Remove(item2));
-            AssertExtensions.Throws<ArgumentException>(null, () => list.Remove(new SqlBulkCopyColumnMapping(2, 2)));
-            AssertExtensions.Throws<ArgumentException>(null, () => list.Remove("bogus"));
-        }
-
-        [Fact]
-        public void RemoveAt_BehavesAsExpected()
-        {
-            var item1 = new SqlBulkCopyColumnMapping(0, 0);
-            var item2 = new SqlBulkCopyColumnMapping(1, 1);
-            var item3 = new SqlBulkCopyColumnMapping(2, 2);
-
-            SqlBulkCopyColumnMappingCollection collection = CreateCollection(item1, item2, item3);
-
-            collection.RemoveAt(0);
-            Assert.Equal(2, collection.Count);
-            Assert.Same(item2, collection[0]);
-            Assert.Same(item3, collection[1]);
-
-            collection.RemoveAt(1);
-            Assert.Equal(1, collection.Count);
-            Assert.Same(item2, collection[0]);
-
-            collection.RemoveAt(0);
-            Assert.Equal(0, collection.Count);
-
-
-            IList list = CreateCollection(item1, item2, item3);
-
-            list.RemoveAt(0);
-            Assert.Equal(2, list.Count);
-            Assert.Same(item2, list[0]);
-            Assert.Same(item3, list[1]);
-
-            list.RemoveAt(1);
-            Assert.Equal(1, list.Count);
-            Assert.Same(item2, list[0]);
-
-            list.RemoveAt(0);
-            Assert.Equal(0, list.Count);
-        }
-
-        [Fact]
-        public void SyncRoot_NotNullAndSameObject()
-        {
-            ICollection collection = CreateCollection();
-            Assert.NotNull(collection.SyncRoot);
-            Assert.Same(collection.SyncRoot, collection.SyncRoot);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlClientFactoryTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlClientFactoryTest.cs
deleted file mode 100644 (file)
index 25366b9..0000000
+++ /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 Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlClientFactoryTest
-    {
-        [Fact]
-        public void InstanceTest()
-        {
-            SqlClientFactory instance = SqlClientFactory.Instance;
-            Assert.NotNull(instance);
-            Assert.Same(instance, SqlClientFactory.Instance);
-        }
-
-        public static readonly object[][] FactoryMethodTestData =
-        {
-            new object[] { new Func<object>(SqlClientFactory.Instance.CreateCommand), typeof(SqlCommand) },
-            new object[] { new Func<object>(SqlClientFactory.Instance.CreateConnection), typeof(SqlConnection) },
-            new object[] { new Func<object>(SqlClientFactory.Instance.CreateConnectionStringBuilder), typeof(SqlConnectionStringBuilder) },
-            new object[] { new Func<object>(SqlClientFactory.Instance.CreateDataAdapter), typeof(SqlDataAdapter) },
-            new object[] { new Func<object>(SqlClientFactory.Instance.CreateParameter), typeof(SqlParameter) },
-        };
-
-        [Theory]
-        [MemberData(nameof(FactoryMethodTestData))]
-        public void FactoryMethodTest(Func<object> factory, Type expectedType)
-        {
-            object value1 = factory();
-            Assert.NotNull(value1);
-            Assert.IsType(expectedType, value1);
-
-            object value2 = factory();
-            Assert.NotNull(value2);
-            Assert.IsType(expectedType, value2);
-
-            Assert.NotSame(value1, value2);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs
deleted file mode 100644 (file)
index d050902..0000000
+++ /dev/null
@@ -1,167 +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.Data.Common;
-using System.Reflection;
-using System.Security;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlConnectionBasicTests
-    {
-        [Fact]
-        public void ConnectionTest()
-        {
-            using (TestTdsServer server = TestTdsServer.StartTestServer())
-            {
-                using (SqlConnection connection = new SqlConnection(server.ConnectionString))
-                {
-                    connection.Open();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer), nameof(PlatformDetection.IsNotArmProcess))]
-        [PlatformSpecific(TestPlatforms.Windows)]
-        public void IntegratedAuthConnectionTest()
-        {
-            using (TestTdsServer server = TestTdsServer.StartTestServer())
-            {
-                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(server.ConnectionString);
-                builder.IntegratedSecurity = true;
-                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
-                {
-                    connection.Open();
-                }
-            }
-        }
-
-        [Fact]
-        public void SqlConnectionDbProviderFactoryTest()
-        {
-            SqlConnection con = new SqlConnection();
-            PropertyInfo dbProviderFactoryProperty = con.GetType().GetProperty("DbProviderFactory", BindingFlags.NonPublic | BindingFlags.Instance);
-            Assert.NotNull(dbProviderFactoryProperty);
-            DbProviderFactory factory = dbProviderFactoryProperty.GetValue(con) as DbProviderFactory;
-            Assert.NotNull(factory);
-            Assert.Same(typeof(SqlClientFactory), factory.GetType());
-            Assert.Same(SqlClientFactory.Instance, factory);
-        }
-
-        [Fact]
-        public void SqlConnectionValidParameters()
-        {
-            var con = new SqlConnection("Timeout=1234;packet Size=5678 ;;; ;");
-            Assert.Equal(1234, con.ConnectionTimeout);
-            Assert.Equal(5678, con.PacketSize);
-        }
-
-        [Fact]
-        public void SqlConnectionEmptyParameters()
-        {
-            var con = new SqlConnection("Timeout=;packet Size= ;Integrated Security=;");
-            //default values are defined in internal class DbConnectionStringDefaults
-            Assert.Equal(15, con.ConnectionTimeout);
-            Assert.Equal(8000, con.PacketSize);
-            Assert.False(new SqlConnectionStringBuilder(con.ConnectionString).IntegratedSecurity);
-        }
-
-        [Fact]
-        public void SqlConnectionInvalidParameters()
-        {
-            Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout=null;"));
-            Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout= null;"));
-            Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout=1 1;"));
-            Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout=1a;"));
-            Assert.Throws<ArgumentException>(() => new SqlConnection("Integrated Security=truee"));
-        }
-
-        [Fact]
-        public void ClosedConnectionSchemaRetrieval()
-        {
-            using (SqlConnection connection = new SqlConnection(string.Empty))
-            {
-                Assert.Throws<InvalidOperationException>(() => connection.GetSchema());
-            }
-        }
-
-        [Theory]
-        [InlineData("RandomStringForTargetServer", false, true)]
-        [InlineData("RandomStringForTargetServer", true, false)]
-        [InlineData(null, false, false)]
-        [InlineData("", false, false)]
-        public void RetrieveWorkstationId(string workstation, bool withDispose, bool shouldMatchSetWorkstationId)
-        {
-            string connectionString = $"Workstation Id={workstation}";
-            SqlConnection conn = new SqlConnection(connectionString);
-            if (withDispose)
-            {
-                conn.Dispose();
-            }
-            string expected = shouldMatchSetWorkstationId ? workstation : Environment.MachineName;
-            Assert.Equal(expected, conn.WorkstationId);
-        }
-
-        [OuterLoop("Can take up to 4 seconds")]
-        [Fact]
-        public void ExceptionsWithMinPoolSizeCanBeHandled()
-        {
-            string connectionString = $"Data Source={Guid.NewGuid().ToString()};uid=random;pwd=asd;Connect Timeout=2; Min Pool Size=3";
-            for (int i = 0; i < 2; i++)
-            {
-                using (SqlConnection connection = new SqlConnection(connectionString))
-                {
-                    Exception exception = Record.Exception(() => connection.Open());
-                    Assert.True(exception is InvalidOperationException || exception is SqlException, $"Unexpected exception: {exception}");
-                }
-            }
-        }
-
-        [Fact]
-        public void ConnectionTestInvalidCredentialCombination()
-        {
-            var cleartextCredsConnStr = "User=test;Password=test;";
-            var sspiConnStr = "Integrated Security=true;";
-            var testPassword = new SecureString();
-            testPassword.MakeReadOnly();
-            var sqlCredential = new SqlCredential(string.Empty, testPassword);
-
-            // Verify that SSPI and cleartext username/password are not in the connection string.
-            Assert.Throws<ArgumentException>(() => { new SqlConnection(cleartextCredsConnStr, sqlCredential); });
-
-            Assert.Throws<ArgumentException>(() => { new SqlConnection(sspiConnStr, sqlCredential); });
-
-            // Verify that credential may not be set with cleartext username/password or SSPI.
-            using (var conn = new SqlConnection(cleartextCredsConnStr))
-            {
-                Assert.Throws<InvalidOperationException>(() => { conn.Credential = sqlCredential; });
-            }
-
-            using (var conn = new SqlConnection(sspiConnStr))
-            {
-                Assert.Throws<InvalidOperationException>(() => { conn.Credential = sqlCredential; });
-            }
-
-            // Verify that connection string with username/password or SSPI may not be set with credential present.
-            using (var conn = new SqlConnection(string.Empty, sqlCredential))
-            {
-                Assert.Throws<InvalidOperationException>(() => { conn.ConnectionString = cleartextCredsConnStr; });
-
-                Assert.Throws<InvalidOperationException>(() => { conn.ConnectionString = sspiConnStr; });
-            }
-        }
-
-        [Fact]
-        public void ConnectionTestValidCredentialCombination()
-        {
-            var testPassword = new SecureString();
-            testPassword.MakeReadOnly();
-            var sqlCredential = new SqlCredential(string.Empty, testPassword);
-            var conn = new SqlConnection(string.Empty, sqlCredential);
-
-            Assert.Equal(sqlCredential, conn.Credential);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.RetrieveStatistics.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.RetrieveStatistics.cs
deleted file mode 100644 (file)
index fef9f9e..0000000
+++ /dev/null
@@ -1,601 +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.Linq;
-
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public partial class SqlConnectionTest
-    {
-        private static readonly string[] s_retrieveStatisticsKeys =
-        {
-            "BuffersReceived",
-            "BuffersSent",
-            "BytesReceived",
-            "BytesSent",
-            "CursorOpens",
-            "IduCount",
-            "IduRows",
-            "PreparedExecs",
-            "Prepares",
-            "SelectCount",
-            "SelectRows",
-            "ServerRoundtrips",
-            "SumResultSets",
-            "Transactions",
-            "UnpreparedExecs",
-            "ConnectionTime",
-            "ExecutionTime",
-            "NetworkServerTime"
-        };
-
-        [Fact]
-        public void RetrieveStatistics_Success()
-        {
-            var connection = new SqlConnection();
-            IDictionary d = connection.RetrieveStatistics();
-            Assert.NotNull(d);
-            Assert.NotSame(d, connection.RetrieveStatistics());
-        }
-
-        [Fact]
-        public void RetrieveStatistics_ExpectedKeysInDictionary_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            Assert.NotEmpty(d);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
-
-            Assert.NotEmpty(d.Keys);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
-
-            Assert.NotEmpty(d.Values);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
-
-            foreach (string key in s_retrieveStatisticsKeys)
-            {
-                Assert.True(d.Contains(key));
-
-                object value = d[key];
-                Assert.NotNull(value);
-                Assert.IsType<long>(value);
-                Assert.Equal(0L, value);
-            }
-        }
-
-        [Fact]
-        public void RetrieveStatistics_UnexpectedKeysNotInDictionary_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            Assert.False(d.Contains("Foo"));
-            Assert.Null(d["Foo"]);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_IsSynchronized_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            Assert.False(d.IsSynchronized);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_SyncRoot_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            Assert.NotNull(d.SyncRoot);
-            Assert.Same(d.SyncRoot, d.SyncRoot);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_IsFixedSize_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            Assert.False(d.IsFixedSize);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_IsReadOnly_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            Assert.False(d.IsReadOnly);
-        }
-
-        public static readonly object[][] RetrieveStatisticsKeyValueData =
-        {
-            new object[] { "Foo", 100L },
-            new object[] { "Foo", null },
-            new object[] { "Blah", "Blah" },
-            new object[] { 100, "Value" }
-        };
-
-        [Theory]
-        [MemberData(nameof(RetrieveStatisticsKeyValueData))]
-        public void RetrieveStatistics_Add_Success(object key, object value)
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            d.Add(key, value);
-
-            Assert.True(d.Contains(key));
-
-            object v = d[key];
-            Assert.Same(value, v);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Add_ExistingKey_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            string key = s_retrieveStatisticsKeys[0];
-            AssertExtensions.Throws<ArgumentException>(null, () => d.Add(key, 100L));
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Add_NullKey_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            AssertExtensions.Throws<ArgumentNullException>("key", () => d.Add(null, 100L));
-        }
-
-        [Theory]
-        [MemberData(nameof(RetrieveStatisticsKeyValueData))]
-        public void RetrieveStatistics_Setter_Success(object key, object value)
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            d[key] = value;
-
-            Assert.True(d.Contains(key));
-
-            object v = d[key];
-            Assert.Same(value, v);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Setter_ExistingKey_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            string key = s_retrieveStatisticsKeys[0];
-
-            d[key] = 100L;
-            Assert.Equal(100L, d[key]);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Setter_NullKey_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            AssertExtensions.Throws<ArgumentNullException>("key", () => d[null] = 100L);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Clear_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            d.Clear();
-
-            Assert.Empty(d);
-            Assert.Equal(0, d.Count);
-
-            Assert.Empty(d.Keys);
-            Assert.Equal(0, d.Keys.Count);
-
-            Assert.Empty(d.Values);
-            Assert.Equal(0, d.Values.Count);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Remove_ExistingKey_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            string key = s_retrieveStatisticsKeys[0];
-
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
-            Assert.True(d.Contains(key));
-            Assert.NotNull(d[key]);
-
-            d.Remove(key);
-
-            Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Keys.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length - 1, d.Values.Count);
-            Assert.False(d.Contains(key));
-            Assert.Null(d[key]);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Remove_NonExistentKey_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            const string key = "Foo";
-
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
-            Assert.False(d.Contains(key));
-            Assert.Null(d[key]);
-
-            d.Remove(key);
-
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Keys.Count);
-            Assert.Equal(s_retrieveStatisticsKeys.Length, d.Values.Count);
-            Assert.False(d.Contains(key));
-            Assert.Null(d[key]);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Remove_NullKey_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            AssertExtensions.Throws<ArgumentNullException>("key", () => d.Remove(null));
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Contains_NullKey_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            AssertExtensions.Throws<ArgumentNullException>("key", () => d.Contains(null));
-        }
-
-        [Fact]
-        public void RetrieveStatistics_CopyTo_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            DictionaryEntry[] destination = new DictionaryEntry[d.Count];
-
-            d.CopyTo(destination, 0);
-
-            int i = 0;
-            foreach (DictionaryEntry entry in d)
-            {
-                Assert.Equal(entry, destination[i]);
-                i++;
-            }
-        }
-
-        [Fact]
-        public void RetrieveStatistics_CopyTo_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            AssertExtensions.Throws<ArgumentNullException>("array", () => d.CopyTo(null, 0));
-            AssertExtensions.Throws<ArgumentNullException>("array", () => d.CopyTo(null, -1));
-            AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => d.CopyTo(new DictionaryEntry[20], -1));
-            AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[20], 18));
-            AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[20], 1000));
-            AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(new DictionaryEntry[4, 3], 0));
-            Assert.Throws<InvalidCastException>(() => d.CopyTo(new string[20], 0));
-        }
-
-        [Fact]
-        public void RetrieveStatistics_IDictionary_GetEnumerator_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            IDictionaryEnumerator e = d.GetEnumerator();
-
-            Assert.NotNull(e);
-            Assert.NotSame(e, d.GetEnumerator());
-
-            for (int i = 0; i < 2; i++)
-            {
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                foreach (string ignored in s_retrieveStatisticsKeys)
-                {
-                    Assert.True(e.MoveNext());
-
-                    Assert.NotNull(e.Current);
-                    Assert.IsType<DictionaryEntry>(e.Current);
-
-                    Assert.NotNull(e.Entry.Key);
-                    Assert.IsType<string>(e.Entry.Key);
-                    Assert.NotNull(e.Entry.Value);
-                    Assert.IsType<long>(e.Entry.Value);
-
-                    Assert.Equal(e.Current, e.Entry);
-                    Assert.Same(e.Key, e.Entry.Key);
-                    Assert.Same(e.Value, e.Entry.Value);
-
-                    Assert.Contains(e.Entry.Key, s_retrieveStatisticsKeys);
-                }
-
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                e.Reset();
-            }
-        }
-
-        [Fact]
-        public void RetrieveStatistics_IEnumerable_GetEnumerator_Success()
-        {
-            // Treat the result as IEnumerable instead of IDictionary.
-            IEnumerable d = new SqlConnection().RetrieveStatistics();
-
-            IEnumerator e = d.GetEnumerator();
-
-            Assert.NotNull(e);
-            Assert.NotSame(e, d.GetEnumerator());
-
-            for (int i = 0; i < 2; i++)
-            {
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                foreach (string ignored in s_retrieveStatisticsKeys)
-                {
-                    Assert.True(e.MoveNext());
-
-                    Assert.NotNull(e.Current);
-
-                    // Verify the IEnumerable.GetEnumerator enumerator is yielding DictionaryEntry entries,
-                    // not KeyValuePair entries.
-                    Assert.IsType<DictionaryEntry>(e.Current);
-
-                    DictionaryEntry entry = (DictionaryEntry)e.Current;
-
-                    Assert.NotNull(entry.Key);
-                    Assert.IsType<string>(entry.Key);
-                    Assert.NotNull(entry.Value);
-                    Assert.IsType<long>(entry.Value);
-
-                    Assert.Contains(entry.Key, s_retrieveStatisticsKeys);
-                }
-
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                e.Reset();
-            }
-        }
-
-        [Fact]
-        public void RetrieveStatistics_GetEnumerator_ModifyCollection_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-
-            IDictionaryEnumerator e = d.GetEnumerator();
-
-            d.Add("Foo", 0L);
-
-            Assert.Throws<InvalidOperationException>(() => e.MoveNext());
-            Assert.Throws<InvalidOperationException>(() => e.Reset());
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            Assert.NotNull(d.Keys);
-            Assert.Same(d.Keys, d.Keys);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_IsSynchronized_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Keys;
-            Assert.False(c.IsSynchronized);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_SyncRoot_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Keys;
-            Assert.NotNull(c.SyncRoot);
-            Assert.Same(c.SyncRoot, c.SyncRoot);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_CopyTo_ObjectArray_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Keys;
-            object[] destination = new object[c.Count];
-
-            c.CopyTo(destination, 0);
-
-            Assert.Equal(c.Cast<object>().ToArray(), destination);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_CopyTo_StringArray_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Keys;
-            string[] destination = new string[c.Count];
-
-            c.CopyTo(destination, 0);
-
-            Assert.Equal(c.Cast<string>().ToArray(), destination);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_CopyTo_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Keys;
-
-            AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
-            AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, -1));
-            AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => c.CopyTo(new string[20], -1));
-            AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[20], 18));
-            AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[20], 1000));
-            AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new string[4, 3], 0));
-            Assert.Throws<InvalidCastException>(() => c.CopyTo(new Version[20], 0));
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_GetEnumerator_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Keys;
-
-            IEnumerator e = c.GetEnumerator();
-
-            Assert.NotNull(e);
-            Assert.NotSame(e, c.GetEnumerator());
-
-            for (int i = 0; i < 2; i++)
-            {
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                foreach (string ignored in s_retrieveStatisticsKeys)
-                {
-                    Assert.True(e.MoveNext());
-                    Assert.NotNull(e.Current);
-                    Assert.Contains(e.Current, s_retrieveStatisticsKeys);
-                }
-
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                e.Reset();
-            }
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Keys_GetEnumerator_ModifyCollection_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Keys;
-
-            IEnumerator e = c.GetEnumerator();
-
-            d.Add("Foo", 0L);
-
-            Assert.Throws<InvalidOperationException>(() => e.MoveNext());
-            Assert.Throws<InvalidOperationException>(() => e.Reset());
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            Assert.NotNull(d.Values);
-            Assert.Same(d.Values, d.Values);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_IsSynchronized_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Values;
-            Assert.False(c.IsSynchronized);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_SyncRoot_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Values;
-            Assert.NotNull(c.SyncRoot);
-            Assert.Same(c.SyncRoot, c.SyncRoot);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_CopyTo_ObjectArray_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Values;
-            object[] destination = new object[c.Count];
-
-            c.CopyTo(destination, 0);
-
-            Assert.Equal(c.Cast<object>().ToArray(), destination);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_CopyTo_Int64Array_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Values;
-            long[] destination = new long[c.Count];
-
-            c.CopyTo(destination, 0);
-
-            Assert.Equal(c.Cast<long>().ToArray(), destination);
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_CopyTo_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Values;
-
-            AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
-            AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, -1));
-            AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => c.CopyTo(new long[20], -1));
-            AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[20], 18));
-            AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[20], 1000));
-            AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new long[4, 3], 0));
-            Assert.Throws<InvalidCastException>(() => c.CopyTo(new Version[20], 0));
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_GetEnumerator_Success()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Values;
-
-            IEnumerator e = c.GetEnumerator();
-
-            Assert.NotNull(e);
-            Assert.NotSame(e, c.GetEnumerator());
-
-            for (int i = 0; i < 2; i++)
-            {
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                foreach (string ignored in s_retrieveStatisticsKeys)
-                {
-                    Assert.True(e.MoveNext());
-                    Assert.NotNull(e.Current);
-                    Assert.Equal(0L, e.Current);
-                }
-
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                e.Reset();
-            }
-        }
-
-        [Fact]
-        public void RetrieveStatistics_Values_GetEnumerator_ModifyCollection_Throws()
-        {
-            IDictionary d = new SqlConnection().RetrieveStatistics();
-            ICollection c = d.Values;
-
-            IEnumerator e = c.GetEnumerator();
-
-            d.Add("Foo", 0L);
-
-            Assert.Throws<InvalidOperationException>(() => e.MoveNext());
-            Assert.Throws<InvalidOperationException>(() => e.Reset());
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlCredentialTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlCredentialTest.cs
deleted file mode 100644 (file)
index 9194a65..0000000
+++ /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.Collections.Generic;
-using System.Data.SqlClient;
-using System.Linq;
-using System.Security;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public static class SqlCredentialTest
-    {
-        [Fact]
-        public static void Test_SqlCredential_Password_Requirements()
-        {
-            var userId = "user";
-
-            // Create password with value longer than max allowed length
-            var longPassword = new SecureString();
-
-            var genPassword = string.Empty.PadLeft(129, '0');
-            genPassword.ToCharArray().ToList().ForEach(c => longPassword.AppendChar(c));
-            longPassword.MakeReadOnly();
-
-            // Verify non-null password requirement
-            Assert.Throws<ArgumentNullException>(() => new SqlCredential(userId, null));
-
-            // Verify max length requirement
-            Assert.Throws<ArgumentException>(() => new SqlCredential(userId, longPassword));
-
-            // Verify read only password requirement
-            Assert.Throws<ArgumentException>(() => new SqlCredential(userId, new SecureString()));
-
-        }
-
-        [Fact]
-        public static void Test_SqlCredential_UserId_Requirements()
-        {
-            var password = new SecureString();
-            password.MakeReadOnly();
-
-            // Create userId longer than max allowed length
-            var userId = string.Empty.PadLeft(129, '0');
-
-            // Verify max length requirement
-            Assert.Throws<ArgumentException>(() => new SqlCredential(userId, password));
-
-            // Verify non-null userId requirement
-            Assert.Throws<ArgumentNullException>(() => new SqlCredential(null, password));
-
-        }
-
-        [Fact]
-        public static void Test_SqlCredential_Properties()
-        {
-            var userId = "user";
-            var password = new SecureString();
-            password.AppendChar('0');
-            password.MakeReadOnly();
-
-            var credential = new SqlCredential(userId, password);
-
-            Assert.Equal(userId, credential.UserId);
-            Assert.Equal(password, credential.Password);
-
-        }
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlDataRecordTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlDataRecordTest.cs
deleted file mode 100644 (file)
index 713d9ab..0000000
+++ /dev/null
@@ -1,397 +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.Data.SqlTypes;
-using Microsoft.SqlServer.Server;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlDataRecordTest
-    {
-
-        [Fact]
-        public void SqlRecordFillTest()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.Bit),
-                new SqlMetaData("col2", SqlDbType.TinyInt),
-                new SqlMetaData("col3", SqlDbType.VarBinary, 1000),
-                new SqlMetaData("col4", SqlDbType.NVarChar, 1000),
-                new SqlMetaData("col5", SqlDbType.DateTime),
-                new SqlMetaData("col6", SqlDbType.Float),
-                new SqlMetaData("col7", SqlDbType.UniqueIdentifier),
-                new SqlMetaData("col8", SqlDbType.SmallInt),
-                new SqlMetaData("col9", SqlDbType.Int),
-                new SqlMetaData("col10", SqlDbType.BigInt),
-                new SqlMetaData("col11", SqlDbType.Real),
-                new SqlMetaData("col12", SqlDbType.Decimal),
-                new SqlMetaData("col13", SqlDbType.Money),
-                new SqlMetaData("col14", SqlDbType.Variant)
-            };
-
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            for (int i = 0; i < record.FieldCount; i++)
-            {
-                Assert.Equal($"col{i + 1}", record.GetName(i));
-            }
-
-            record.SetBoolean(0, true);
-            Assert.True(record.GetBoolean(0));
-
-            record.SetByte(1, 1);
-            Assert.Equal(1, record.GetByte(1));
-
-            byte[] bb1 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
-            byte[] bb2 = new byte[5];
-            record.SetSqlBinary(2, new SqlBinary(new byte[0]));
-            record.SetBytes(2, 0, bb1, 0, 3);
-            record.SetBytes(2, 2, bb1, 6, 3);
-
-            // Verify the length of the byte array
-            Assert.Equal(5, record.GetBytes(2, 0, bb2, 0, 5));
-
-            Assert.Equal(5, record.GetBytes(2, 0, null, 0, 0));
-
-            byte[] expected = new byte[] { 1, 2, 7, 8, 9 };
-            Assert.Equal<byte>(expected, bb2);
-
-            char[] cb1 = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
-            char[] cb2 = new char[5];
-            record.SetChars(3, 0, cb1, 0, 3);
-            record.SetChars(3, 2, cb1, 4, 3);
-
-            char[] expectedValue = new char[] { 'a', 'b', 'e', 'f', 'g' };
-            Assert.Equal(expectedValue.Length, record.GetChars(3, 0, cb2, 0, 5));
-            Assert.Equal<char>(expectedValue, new string(cb2, 0, (int)record.GetChars(3, 0, null, 0, 0)));
-
-            record.SetString(3, "");
-            string xyz = "xyz";
-            record.SetString(3, "xyz");
-            Assert.Equal(xyz, record.GetString(3));
-            Assert.Equal(xyz.Length, record.GetChars(3, 0, cb2, 0, 5));
-            Assert.Equal(xyz, new string(cb2, 0, (int)record.GetChars(3, 0, null, 0, 0)));
-
-            record.SetChars(3, 2, cb1, 4, 3);
-            Assert.Equal(5, record.GetChars(3, 0, cb2, 0, 5));
-
-            string interleavedResult = "xyefg";
-            Assert.Equal(interleavedResult, new string(cb2, 0, (int)record.GetChars(3, 0, null, 0, 0)));
-            Assert.Equal(interleavedResult, record.GetString(3));
-
-            record.SetSqlDateTime(4, SqlDateTime.MaxValue);
-            Assert.Equal(SqlDateTime.MaxValue, record.GetSqlDateTime(4));
-
-            record.SetSqlDouble(5, SqlDouble.MaxValue);
-            Assert.Equal(SqlDouble.MaxValue, record.GetSqlDouble(5));
-
-            SqlGuid guid = new SqlGuid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4");
-            record.SetSqlGuid(6, guid);
-            Assert.Equal(guid, record.GetSqlGuid(6));
-
-            record.SetSqlInt16(7, SqlInt16.MaxValue);
-            Assert.Equal(SqlInt16.MaxValue, record.GetSqlInt16(7));
-
-            record.SetSqlInt32(8, SqlInt32.MaxValue);
-            Assert.Equal(SqlInt32.MaxValue, record.GetSqlInt32(8));
-
-            record.SetSqlInt64(9, SqlInt64.MaxValue);
-            Assert.Equal(SqlInt64.MaxValue, record.GetSqlInt64(9));
-
-            record.SetSqlSingle(10, SqlSingle.MinValue);
-            Assert.Equal(SqlSingle.MinValue, record.GetSqlSingle(10));
-
-            record.SetSqlDecimal(11, SqlDecimal.Null);
-            record.SetSqlDecimal(11, SqlDecimal.MaxValue);
-            Assert.Equal(SqlDecimal.MaxValue, record.GetSqlDecimal(11));
-
-            record.SetSqlMoney(12, SqlMoney.MaxValue);
-            Assert.Equal(SqlMoney.MaxValue, record.GetSqlMoney(12));
-
-
-            // Try adding different values to SqlVariant type
-            for (int i = 0; i < record.FieldCount - 1; ++i)
-            {
-                object valueToSet = record.GetSqlValue(i);
-                record.SetValue(record.FieldCount - 1, valueToSet);
-                object o = record.GetSqlValue(record.FieldCount - 1);
-
-                if (o is SqlBinary)
-                {
-                    Assert.Equal<byte>(((SqlBinary)valueToSet).Value, ((SqlBinary)o).Value);
-                }
-                else
-                {
-                    Assert.Equal(valueToSet, o);
-                }
-
-                record.SetDBNull(record.FieldCount - 1);
-                Assert.Equal(DBNull.Value, record.GetSqlValue(record.FieldCount - 1));
-
-                record.SetDBNull(i);
-                Assert.Equal(DBNull.Value, record.GetValue(i));
-            }
-        }
-        [Fact]
-        public void GetDataTypeName_ReturnsMetaDataTypeIfUdtType()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.Udt, typeof(TestUdt), "sql_TestUdt")
-            };
-
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            Assert.Equal("System.Data.SqlClient.Tests.TestUdt", record.GetDataTypeName(0));
-        }
-
-        [Fact]
-        public void GetDataTypeName_ReturnsTypeFromMetaTypeIfNotUdt()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50)
-            };
-
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            Assert.Equal("nvarchar", record.GetDataTypeName(0));
-        }
-        [Fact]
-        public void GetFieldType_ReturnMetaTypeClassType()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50)
-            };
-
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            Assert.Equal(typeof(string), record.GetFieldType(0));
-        }
-
-        [Fact]
-        public void GetValues_ThrowsIfNull()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50)
-            };
-
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            Assert.Throws<ArgumentNullException>(() => record.GetValues(null));
-        }
-
-        [Fact]
-        public void GetValues_IfValuesBiggerThanColumnCount_LastArrayItemKeptEmpty()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50),
-                new SqlMetaData("col2", SqlDbType.Int)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-            record.SetString(0, "test");
-            record.SetSqlInt32(1, 2);
-
-            object[] values = new object[5];
-            int columnCount = record.GetValues(values);
-
-            for (int i = 2; i < 5; i++)
-            {
-                Assert.Null(values[i]);
-            }
-            Assert.Equal(2, columnCount);
-        }
-
-        [Fact]
-        public void GetValues_IfValuesShorterThanColumnCount_FillOnlyFirstColumn()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50),
-                new SqlMetaData("col2", SqlDbType.Int)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-            record.SetString(0, "test");
-            record.SetSqlInt32(1, 2);
-
-            object[] values = new object[1];
-            int columnCount = record.GetValues(values);
-
-            Assert.Equal("test", values[0]);
-            Assert.Equal(1, columnCount);
-        }
-
-        [Fact]
-        public void GetValues_FillsArrayAndRespectColumnOrder()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50),
-                new SqlMetaData("col2", SqlDbType.Int)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-            record.SetString(0, "test");
-            record.SetSqlInt32(1, 2);
-
-            object[] values = new object[2];
-            int columnCount = record.GetValues(values);
-
-            Assert.Equal("test", values[0]);
-            Assert.Equal(2, values[1]);
-            Assert.Equal(2, columnCount);
-        }
-
-        [Fact]
-        public void GetOrdinal_ThrowsAgumentNull_IfNameIsNull()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-           {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50),
-                new SqlMetaData("col2", SqlDbType.Int)
-           };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            Assert.Throws<ArgumentNullException>(() => record.GetOrdinal(null));
-        }
-
-        [Fact]
-        public void GetOrdinal_ThrowsOutOfRange_IfNameIsNotAColumn()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50),
-                new SqlMetaData("col2", SqlDbType.Int)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-
-            Assert.Throws<IndexOutOfRangeException>(() => record.GetOrdinal("outofrange"));
-
-            Assert.Throws<IndexOutOfRangeException>(() => record.GetOrdinal("col1 "));
-
-        }
-
-        [Fact]
-        public void GetOrdinal_ReturnsIndexOfColumn()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50),
-                new SqlMetaData("col2", SqlDbType.Int)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            Assert.Equal(1, record.GetOrdinal("col2"));
-        }
-        [Fact]
-        public void GetOrdinal_ReturnsIndexOfColumn_CaseInsensitive()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 50),
-                new SqlMetaData("col2", SqlDbType.Int)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-
-            Assert.Equal(1, record.GetOrdinal("Col2"));
-        }
-
-        [Fact]
-        public void GetChar_ThrowsNotSupported()
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.Char, 100)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-            record.SetValue(0, 'c');
-            Assert.Throws<NotSupportedException>(() => record.GetChar(0));
-        }
-
-        [Theory]
-        [ClassData(typeof(GetXXXBadTypeTestData))]
-        public void GetXXX_ThrowsIfBadType(Func<SqlDataRecord, object> getXXX)
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", SqlDbType.NVarChar, 1)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-            record.SetValue(0, "a");
-            Assert.Throws<InvalidCastException>(() => getXXX(record));
-
-        }
-
-        [Theory]
-        [ClassData(typeof(GetXXXCheckValueTestData))]
-        public void GetXXX_ReturnValue(SqlDbType dbType, object value, Func<SqlDataRecord, object> getXXX)
-        {
-            SqlMetaData[] metaData = new SqlMetaData[]
-            {
-                new SqlMetaData("col1", dbType)
-            };
-            SqlDataRecord record = new SqlDataRecord(metaData);
-            record.SetValue(0, value);
-            Assert.Equal(value, getXXX(record));
-
-        }
-    }
-
-    public class GetXXXBadTypeTestData : IEnumerable<object[]>
-    {
-        public IEnumerator<object[]> GetEnumerator()
-        {
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetGuid(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetInt16(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetInt32(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetInt64(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetFloat(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetDouble(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetDecimal(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetDateTime(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetDateTimeOffset(0)) };
-            yield return new object[] { new Func<SqlDataRecord, object>(r => r.GetTimeSpan(0)) };
-        }
-
-        IEnumerator IEnumerable.GetEnumerator()
-        {
-            return GetEnumerator();
-        }
-    }
-
-    public class GetXXXCheckValueTestData : IEnumerable<object[]>
-    {
-        public IEnumerator<object[]> GetEnumerator()
-        {
-            yield return new object[] { SqlDbType.UniqueIdentifier, Guid.NewGuid(), new Func<SqlDataRecord, object>(r => r.GetGuid(0)) };
-            yield return new object[] { SqlDbType.SmallInt, (short)123, new Func<SqlDataRecord, object>(r => r.GetInt16(0)) };
-            yield return new object[] { SqlDbType.Int, 123456, new Func<SqlDataRecord, object>(r => r.GetInt32(0)) };
-            yield return new object[] { SqlDbType.BigInt, (long)123456789, new Func<SqlDataRecord, object>(r => r.GetInt64(0)) };
-            yield return new object[] { SqlDbType.Float, (double)1.2, new Func<SqlDataRecord, object>(r => r.GetDouble(0)) };
-            yield return new object[] { SqlDbType.Real, (float)1.2, new Func<SqlDataRecord, object>(r => r.GetFloat(0)) };
-            yield return new object[] { SqlDbType.Decimal, 1.2m, new Func<SqlDataRecord, object>(r => r.GetDecimal(0)) };
-            yield return new object[] { SqlDbType.DateTime, DateTime.Now, new Func<SqlDataRecord, object>(r => r.GetDateTime(0)) };
-            yield return new object[] { SqlDbType.DateTimeOffset, new DateTimeOffset(DateTime.Now), new Func<SqlDataRecord, object>(r => r.GetDateTimeOffset(0)) };
-            yield return new object[] { SqlDbType.Time, TimeSpan.FromHours(1), new Func<SqlDataRecord, object>(r => r.GetTimeSpan(0)) };
-        }
-
-        IEnumerator IEnumerable.GetEnumerator()
-        {
-            return GetEnumerator();
-        }
-    }
-    [SqlUserDefinedType(Format.UserDefined)]
-    public class TestUdt
-    {
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlErrorCollectionTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlErrorCollectionTest.cs
deleted file mode 100644 (file)
index e7ef723..0000000
+++ /dev/null
@@ -1,157 +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;
-
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlErrorCollectionTest
-    {
-        private const string badServer = "92B96911A0BD43E8ADA4451031F7E7CF";
-
-        [Fact]
-        public void IsSynchronized_Success()
-        {
-            ICollection c = CreateCollection();
-            Assert.False(c.IsSynchronized);
-        }
-
-        [Fact]
-        public void SyncRoot_Success()
-        {
-            ICollection c = CreateCollection();
-            Assert.Same(c, c.SyncRoot);
-        }
-
-        [Fact]
-        public void Indexer_Success()
-        {
-            SqlErrorCollection c = CreateCollection();
-            Assert.NotNull(c[0]);
-            Assert.Same(c[0], c[0]);
-        }
-
-        [Fact]
-        public void Indexer_Throws()
-        {
-            SqlErrorCollection c = CreateCollection();
-
-            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => c[-1]);
-            AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => c[c.Count]);
-        }
-
-        [Fact]
-        public void CopyTo_Success()
-        {
-            ValidateCopyTo((collection, array, index) => collection.CopyTo(array, index));
-        }
-
-        [Fact]
-        public void CopyTo_NonGeneric_Success()
-        {
-            ValidateCopyTo((collection, array, index) => ((ICollection)collection).CopyTo(array, index));
-        }
-
-        private static void ValidateCopyTo(Action<SqlErrorCollection, SqlError[], int> copyTo)
-        {
-            SqlErrorCollection c = CreateCollection();
-            SqlError[] destination = new SqlError[5];
-
-            copyTo(c, destination, 2);
-
-            Assert.Null(destination[0]);
-            Assert.Null(destination[1]);
-            Assert.Same(c[0], destination[2]);
-            Assert.Null(destination[3]);
-            Assert.Null(destination[4]);
-        }
-
-        [Fact]
-        public void CopyTo_Throws()
-        {
-            ValidateCopyToThrows((collection, array, index) => collection.CopyTo(array, index));
-        }
-
-        [Fact]
-        public void CopyTo_NonGeneric_Throws()
-        {
-            ValidateCopyToThrows((collection, array, index) => ((ICollection)collection).CopyTo(array, index), c =>
-            {
-                ICollection ic = c;
-                AssertExtensions.Throws<ArgumentException>(null, () => ic.CopyTo(new SqlError[4, 3], 0));
-                Assert.Throws<InvalidCastException>(() => ic.CopyTo(new string[10], 0));
-            });
-        }
-
-        private static void ValidateCopyToThrows(
-            Action<SqlErrorCollection, SqlError[], int> copyTo,
-            Action<SqlErrorCollection> additionalValidation = null)
-        {
-            SqlErrorCollection c = CreateCollection();
-
-            Assert.Throws<ArgumentNullException>(() => copyTo(c, null, 0));
-            Assert.Throws<ArgumentNullException>(() => copyTo(c, null, -1));
-            Assert.Throws<ArgumentOutOfRangeException>(() => copyTo(c, new SqlError[10], -1));
-            AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => copyTo(c, new SqlError[10], 1000));
-
-            additionalValidation?.Invoke(c);
-        }
-
-        [Fact]
-        public void GetEnumerator_Success()
-        {
-            SqlErrorCollection c = CreateCollection();
-
-            IEnumerator e = c.GetEnumerator();
-
-            Assert.NotNull(e);
-            Assert.NotSame(e, c.GetEnumerator());
-
-            for (int i = 0; i < 2; i++)
-            {
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                Assert.True(e.MoveNext());
-                Assert.Same(c[0], e.Current);
-
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-                Assert.False(e.MoveNext());
-
-                Assert.Throws<InvalidOperationException>(() => e.Current);
-
-                e.Reset();
-            }
-        }
-
-        private static SqlErrorCollection CreateCollection()
-        {
-            var builder = new SqlConnectionStringBuilder()
-            {
-                DataSource = badServer,
-                ConnectTimeout = 1,
-                Pooling = false
-            };
-
-            using (var connection = new SqlConnection(builder.ConnectionString))
-            {
-                try
-                {
-                    connection.Open();
-                }
-                catch (SqlException ex)
-                {
-                    Assert.NotNull(ex.Errors);
-                    Assert.Equal(1, ex.Errors.Count);
-
-                    return ex.Errors;
-                }
-            }
-
-            throw new InvalidOperationException("SqlException.Errors should have been returned.");
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlFacetAttributeTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlFacetAttributeTest.cs
deleted file mode 100644 (file)
index 2a1db6d..0000000
+++ /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 Microsoft.SqlServer.Server;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlFacetAttributeTests
-    {
-        [Fact]
-        public void Basic()
-        {
-            var attrib = new SqlFacetAttribute();
-
-            attrib.IsFixedLength = true;
-            attrib.IsNullable = false;
-            attrib.MaxSize = 123;
-            attrib.Precision = 234;
-            attrib.Scale = 345;
-
-            Assert.True(attrib.IsFixedLength);
-            Assert.False(attrib.IsNullable);
-            Assert.Equal(123, attrib.MaxSize);
-            Assert.Equal(234, attrib.Precision);
-            Assert.Equal(345, attrib.Scale);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlMetaDataTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlMetaDataTest.cs
deleted file mode 100644 (file)
index e3d6ed6..0000000
+++ /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 Microsoft.SqlServer.Server;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlMetaDataTest
-    {
-
-        // Test UDT constrtuctor without tvp extended properties
-        [Fact]
-        public void UdtConstructorTest()
-        {
-            Address address = Address.Parse("123 baker st || Redmond");
-            SqlMetaData metaData = new SqlMetaData("col1", SqlDbType.Udt, typeof(Address), "UdtTestDb.dbo.Address");
-            Assert.Equal("col1", metaData.Name);
-            Assert.Equal(SqlDbType.Udt, metaData.SqlDbType);
-            Assert.Equal(address.GetType(), metaData.Type);
-            Assert.Equal("UdtTestDb.dbo.Address", metaData.TypeName);
-            Assert.False(metaData.UseServerDefault);
-            Assert.False(metaData.IsUniqueKey);
-            Assert.Equal(SortOrder.Unspecified, metaData.SortOrder);
-            Assert.Equal(-1, metaData.SortOrdinal);
-        }
-
-
-        // Test UDT constrtuctor with tvp extended properties
-        [Fact]
-        public void UdtConstructorWithTvpTest()
-        {
-            Address address = Address.Parse("123 baker st || Redmond");
-            SqlMetaData metaData = new SqlMetaData("col2", SqlDbType.Udt, typeof(Address), "UdtTestDb.dbo.Address", true, true, SortOrder.Ascending, 0);
-            Assert.Equal("col2", metaData.Name);
-            Assert.Equal(SqlDbType.Udt, metaData.SqlDbType);
-            Assert.Equal(address.GetType(), metaData.Type);
-            Assert.Equal("UdtTestDb.dbo.Address", metaData.TypeName);
-            Assert.True(metaData.UseServerDefault);
-            Assert.True(metaData.IsUniqueKey);
-            Assert.Equal(SortOrder.Ascending, metaData.SortOrder);
-            Assert.Equal(0, metaData.SortOrdinal);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlParameterTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/SqlParameterTest.cs
deleted file mode 100644 (file)
index 40762d0..0000000
+++ /dev/null
@@ -1,106 +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.Data.Common;
-using Xunit;
-
-namespace System.Data.SqlClient.Tests
-{
-    public class SqlParameterTests
-    {
-        [Fact]
-        public void ParameterPrecisionOnInterfaceType()
-        {
-            SqlParameter parameter = new SqlParameter();
-            IDbDataParameter interfaceParameter = parameter;
-            interfaceParameter.Precision = 10;
-            interfaceParameter.Scale = 5;
-
-            Assert.Equal(10, interfaceParameter.Precision);
-            Assert.Equal(5, interfaceParameter.Scale);
-
-            Assert.Equal(10, parameter.Precision);
-            Assert.Equal(5, parameter.Scale);
-        }
-
-        [Fact]
-        public void ParameterPrecisionOnBaseType()
-        {
-            SqlParameter parameter = new SqlParameter();
-            DbParameter baseParameter = parameter;
-            baseParameter.Precision = 10;
-            baseParameter.Scale = 5;
-
-            Assert.Equal(10, baseParameter.Precision);
-            Assert.Equal(5, baseParameter.Scale);
-
-            Assert.Equal(10, parameter.Precision);
-            Assert.Equal(5, parameter.Scale);
-        }
-
-        [Fact]
-        public void CreateParameterWithValidXmlSchema()
-        {
-            string xmlDatabase = "database";
-            string xmlSchema = "schema";
-            string xmlName = "name";
-
-            SqlParameter parameter = new SqlParameter("@name", SqlDbType.Int, 4, ParameterDirection.Input, 0, 0, "name", DataRowVersion.Original, false, 1, xmlDatabase, xmlSchema, xmlName);
-
-            Assert.Equal(xmlDatabase, parameter.XmlSchemaCollectionDatabase);
-            Assert.Equal(xmlSchema, parameter.XmlSchemaCollectionOwningSchema);
-            Assert.Equal(xmlName, parameter.XmlSchemaCollectionName);
-        }
-
-        [Fact]
-        public void CreateParameterWithEmptyXmlSchema()
-        {
-            SqlParameter parameter = new SqlParameter("@name", SqlDbType.Int, 4, ParameterDirection.Input, 0, 0, "name", DataRowVersion.Original, false, 1, string.Empty, string.Empty, string.Empty);
-
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionDatabase);
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionOwningSchema);
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionName);
-        }
-
-        [Fact]
-        public void CreateParameterWithNullXmlSchema()
-        {
-            SqlParameter parameter = new SqlParameter("@name", SqlDbType.Int, 4, ParameterDirection.Input, 0, 0, "name", DataRowVersion.Original, false, 1, null, null, null);
-
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionDatabase);
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionOwningSchema);
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionName);
-        }
-
-        [Fact]
-        public void CreateParameterWithoutXmlSchema()
-        {
-            SqlParameter parameter = new SqlParameter();
-
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionDatabase);
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionOwningSchema);
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionName);
-        }
-
-        [Fact]
-        public void SetParameterXmlSchema()
-        {
-            SqlParameter parameter = new SqlParameter();
-
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionName);
-
-            // verify that if we set it to null we still get an empty string back
-            parameter.XmlSchemaCollectionName = null;
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionName);
-
-            // verify that if we set a value we get it back
-            parameter.XmlSchemaCollectionName = "name";
-            Assert.Equal("name", parameter.XmlSchemaCollectionName);
-
-            // verify that if we set it explicitly to null it reverts to empty string
-            parameter.XmlSchemaCollectionName = null;
-            Assert.Equal(string.Empty, parameter.XmlSchemaCollectionName);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj
deleted file mode 100644 (file)
index be14e74..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <IncludeRemoteExecutor>true</IncludeRemoteExecutor>
-    <Configurations>$(NetCoreAppCurrent)-Unix-Debug;$(NetCoreAppCurrent)-Unix-Release;$(NetCoreAppCurrent)-Windows_NT-Debug;$(NetCoreAppCurrent)-Windows_NT-Release;$(NetFrameworkCurrent)-Windows_NT-Debug;$(NetFrameworkCurrent)-Windows_NT-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="AssemblyInfo.cs" />
-    <Compile Include="AADAccessTokenTest.cs" />
-    <Compile Include="CloneTests.cs" />
-    <Compile Include="BaseProviderAsyncTest\BaseProviderAsyncTest.cs" />
-    <Compile Include="BaseProviderAsyncTest\MockCommand.cs" />
-    <Compile Include="BaseProviderAsyncTest\MockConnection.cs" />
-    <Compile Include="BaseProviderAsyncTest\MockDataReader.cs" />
-    <Compile Include="SqlCredentialTest.cs" />
-    <Compile Include="DiagnosticTest.cs" />
-    <Compile Include="AmbientTransactionFailureTest.cs" />
-    <Compile Include="ExceptionTest.cs" />
-    <Compile Include="FakeDiagnosticListenerObserver.cs" />
-    <Compile Include="SqlBulkCopyColumnMappingCollectionTest.cs" />
-    <Compile Include="SqlDataRecordTest.cs" />
-    <Compile Include="SqlMetaDataTest.cs" />
-    <Compile Include="SqlParameterTest.cs" />
-    <Compile Include="SqlClientFactoryTest.cs" />
-    <Compile Include="SqlConnectionTest.RetrieveStatistics.cs" />
-    <Compile Include="SqlErrorCollectionTest.cs" />
-    <Compile Include="TcpDefaultForAzureTest.cs" />
-    <Compile Include="SqlConnectionBasicTests.cs" />
-    <Compile Include="TestTdsServer.cs" />
-    <Compile Include="..\ManualTests\DataCommon\DataTestUtility.cs" />
-  </ItemGroup>
-  <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
-    <Compile Include="SqlFacetAttributeTest.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\ManualTests\SQL\UdtTest\UDTs\Address\Address.csproj" />
-    <ProjectReference Include="..\Tools\TDS\TDS.Servers\TDS.Servers.csproj" />
-    <ProjectReference Include="..\Tools\TDS\TDS.EndPoint\TDS.EndPoint.csproj" />
-    <ProjectReference Include="..\Tools\TDS\TDS\TDS.csproj" />
-  </ItemGroup>
-  <ItemGroup>
-    <PackageReference Include="runtime.native.System.Data.SqlClient.sni" Version="$(RuntimeWinX64RuntimeNativeSystemDataSqlClientSniVersion)" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs
deleted file mode 100644 (file)
index 9e82dd4..0000000
+++ /dev/null
@@ -1,127 +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.Data.SqlClient.Tests
-{
-    [OuterLoop("Takes minutes on some networks")]
-    public static class TcpDefaultForAzureTest
-    {
-        private const string NP = "Named Pipes Provider";
-        private const string TCP = "TCP Provider";
-        private const string InvalidHostname = "invalidHostname";
-        private const string ErrorMessage = "A network-related or instance-specific error occurred while establishing a connection to SQL Server.";
-
-        private static string[] AzureExtensions;
-        private static SqlConnectionStringBuilder builder;
-
-        static TcpDefaultForAzureTest()
-        {
-            AzureExtensions = new string[]
-                {
-                    ".database.windows.net",
-                    ".database.cloudapi.de",
-                    ".database.usgovcloudapi.net",
-                    ".database.chinacloudapi.cn"
-                };
-
-            builder = new SqlConnectionStringBuilder();
-            builder.ConnectTimeout = 1;
-        }
-
-        [Fact]
-        public static void NonAzureNoProtocolConnectionTest()
-        {
-            builder.DataSource = InvalidHostname;
-            CheckConnectionFailure(builder.ConnectionString, ManualTesting.Tests.DataTestUtility.IsUsingManagedSNI() ? TCP : NP);
-        }
-
-        [Fact]
-        public static void NonAzureTcpConnectionTest()
-        {
-            builder.DataSource = "tcp:" + InvalidHostname;
-            CheckConnectionFailure(builder.ConnectionString, TCP);
-        }
-
-        [Fact]
-        [PlatformSpecific(TestPlatforms.Windows)]  // NP NonAzure connection fails correctly on Windows
-        public static void NonAzureNpConnectionTest()
-        {
-            builder.DataSource = "np:\\\\" + InvalidHostname + "\\pipe\\sql\\query";
-            CheckConnectionFailure(builder.ConnectionString, NP);
-        }
-
-        [Fact]
-        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
-        public static void AzureNoProtocolConnectionTest()
-        {
-            foreach (string extension in AzureExtensions)
-            {
-                builder.DataSource = InvalidHostname + extension;
-                CheckConnectionFailure(builder.ConnectionString, TCP);
-            }
-        }
-
-        [Fact]
-        public static void AzureTcpConnectionTest()
-        {
-            foreach (string extension in AzureExtensions)
-            {
-                builder.DataSource = "tcp:" + InvalidHostname + extension;
-                CheckConnectionFailure(builder.ConnectionString, TCP);
-            }
-        }
-
-        [Fact]
-        [PlatformSpecific(TestPlatforms.Windows)]  // NP Azure connection fails correctly on Windows
-        public static void AzureNpConnectionTest()
-        {
-            foreach (string extension in AzureExtensions)
-            {
-                builder.DataSource = "np:\\\\" + InvalidHostname + extension + "\\pipe\\sql\\query";
-                CheckConnectionFailure(builder.ConnectionString, NP);
-            }
-        }
-
-        private static void CheckConnectionFailure(string connString, string protocol)
-        {
-            Debug.Assert(!string.IsNullOrWhiteSpace(connString));
-
-            string errorMessage = Connect(connString);
-
-            Assert.True(errorMessage != null, "Did not receive any error message");
-            Assert.True(errorMessage.Contains(ErrorMessage), string.Format("Expected error message {0}, but received: {1}", ErrorMessage, errorMessage));
-
-            if (protocol != null)
-            {
-                Assert.True(
-                    errorMessage.Contains(string.Format("provider: {0}, error", protocol)),
-                    string.Format("Expected protocol {0} in the error message, but received: {1}", protocol, errorMessage));
-            }
-        }
-
-        private static string Connect(string connString)
-        {
-            Debug.Assert(!string.IsNullOrWhiteSpace(connString));
-
-            string errorMessage = null;
-            using (SqlConnection connection = new SqlConnection(connString))
-            {
-                try
-                {
-                    connection.Open();
-                    connection.Close();
-                }
-                catch (Exception e)
-                {
-                    errorMessage = e.Message;
-                }
-            }
-
-            return errorMessage;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/FunctionalTests/TestTdsServer.cs b/src/libraries/System.Data.SqlClient/tests/FunctionalTests/TestTdsServer.cs
deleted file mode 100644 (file)
index 6b876b6..0000000
+++ /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 Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.Servers;
-using System.Net;
-using System.Runtime.CompilerServices;
-
-namespace System.Data.SqlClient.Tests
-{
-    internal class TestTdsServer : GenericTDSServer, IDisposable
-    {
-        private TDSServerEndPoint _endpoint = null;
-
-        private SqlConnectionStringBuilder connectionStringBuilder;
-
-        public TestTdsServer(TDSServerArguments args) : base(args) { }
-
-        public TestTdsServer(QueryEngine engine, TDSServerArguments args) : base(args)
-        {
-            this.Engine = engine;
-        }
-
-        public static TestTdsServer StartServerWithQueryEngine(QueryEngine engine, bool enableFedAuth = false, bool enableLog = false, [CallerMemberName] string methodName = "")
-        {
-            TDSServerArguments args = new TDSServerArguments()
-            {
-                Log = enableLog ? Console.Out : null,
-            };
-
-            if (enableFedAuth)
-            {
-                args.FedAuthRequiredPreLoginOption = Microsoft.SqlServer.TDS.PreLogin.TdsPreLoginFedAuthRequiredOption.FedAuthRequired;
-            }
-
-            TestTdsServer server = engine == null ? new TestTdsServer(args) : new TestTdsServer(engine, args);
-            server._endpoint = new TDSServerEndPoint(server) { ServerEndPoint = new IPEndPoint(IPAddress.Any, 0) };
-            server._endpoint.EndpointName = methodName;
-            // The server EventLog should be enabled as it logs the exceptions.
-            server._endpoint.EventLog = Console.Out;
-            server._endpoint.Start();
-
-            int port = server._endpoint.ServerEndPoint.Port;
-            server.connectionStringBuilder = new SqlConnectionStringBuilder() { DataSource = "localhost," + port, ConnectTimeout = 30, Encrypt = false };
-            server.ConnectionString = server.connectionStringBuilder.ConnectionString;
-            return server;
-        }
-
-        public static TestTdsServer StartTestServer(bool enableFedAuth = false, bool enableLog = false, [CallerMemberName] string methodName = "")
-        {
-            return StartServerWithQueryEngine(null, false, false, methodName);
-        }
-
-        public void Dispose() => _endpoint?.Stop();
-
-        public string ConnectionString { get; private set; }
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/Configurations.props b/src/libraries/System.Data.SqlClient/tests/ManualTests/Configurations.props
deleted file mode 100644 (file)
index b6e0d3c..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      $(NetCoreAppCurrent);
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDAsyncTest/DDAsyncTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDAsyncTest/DDAsyncTest.cs
deleted file mode 100644 (file)
index 96d387c..0000000
+++ /dev/null
@@ -1,99 +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.Generic;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DDAsyncTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void OpenConnection_WithAsyncTrue_ThrowsNotSupportedException()
-        {
-            var asyncConnectionString = DataTestUtility.TcpConnStr + ";async=true";
-            Assert.Throws<NotSupportedException>(() => { new SqlConnection(asyncConnectionString); });
-        }
-
-        #region <<ExecuteCommand_WithNewConnection>>
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ExecuteCommand_WithNewConnection_ShouldPerformAsyncByDefault()
-        {
-            var executedProcessList = new List<string>();
-
-            var task1 = ExecuteCommandWithNewConnectionAsync("A", "SELECT top 10 * FROM Orders", executedProcessList);
-            var task2 = ExecuteCommandWithNewConnectionAsync("B", "SELECT top 10 * FROM Products", executedProcessList);
-            //wait all before verifying the results
-            Task.WaitAll(task1, task2);
-
-            //verify whether it executed async
-            Assert.True(DoesProcessExecutedAsync(executedProcessList));
-        }
-
-        private static bool DoesProcessExecutedAsync(IReadOnlyList<string> executedProcessList)
-        {
-            for (var i = 1; i < executedProcessList.Count; i++)
-            {
-                if (executedProcessList[i] != executedProcessList[i - 1])
-                {
-                    return true;
-                }
-            }
-            return false;
-        }
-
-
-        private static async Task ExecuteCommandWithNewConnectionAsync(string processName, string cmdText, ICollection<string> executedProcessList)
-        {
-            var conn = new SqlConnection(DataTestUtility.TcpConnStr);
-
-            await conn.OpenAsync();
-            var cmd = new SqlCommand(cmdText, conn);
-
-            using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
-            {
-                while (await reader.ReadAsync())
-                {
-                    executedProcessList.Add(processName);
-                }
-            }
-        }
-        #endregion
-
-        #region <<ExecuteCommand_WithSharedConnection>>
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ExecuteCommand_WithSharedConnection_ShouldPerformAsyncByDefault()
-        {
-            var executedProcessList = new List<string>();
-
-            //for shared connection we need to add MARS capabilities
-            using (var conn = new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString))
-            {
-                conn.Open();
-                var task1 = ExecuteCommandWithSharedConnectionAsync(conn, "C", "SELECT top 10 * FROM Orders", executedProcessList);
-                var task2 = ExecuteCommandWithSharedConnectionAsync(conn, "D", "SELECT top 10 * FROM Products", executedProcessList);
-                //wait all before verifying the results
-                Task.WaitAll(task1, task2);
-            }
-
-            //verify whether it executed async
-            Assert.True(DoesProcessExecutedAsync(executedProcessList));
-        }
-
-        private static async Task ExecuteCommandWithSharedConnectionAsync(SqlConnection conn, string processName, string cmdText, ICollection<string> executedProcessList)
-        {
-            var cmd = new SqlCommand(cmdText, conn);
-
-            using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
-            {
-                while (await reader.ReadAsync())
-                {
-                    executedProcessList.Add(processName);
-                }
-            }
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/DDDataTypesTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/DDDataTypesTest.cs
deleted file mode 100644 (file)
index 67ba9f1..0000000
+++ /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.Data.SqlTypes;
-using System.Xml;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DDDataTypesTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void XmlTest()
-        {
-            string tempTable = "xml_" + Guid.NewGuid().ToString().Replace('-', '_');
-            string initStr = "create table " + tempTable + " (xml_col XML)";
-            string insertNormStr = "INSERT " + tempTable + " VALUES('<doc>Hello World</doc>')";
-            string insertParamStr = "INSERT " + tempTable + " VALUES(@x)";
-            string queryStr = "select * from " + tempTable;
-
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                conn.Open();
-
-                SqlCommand cmd = conn.CreateCommand();
-
-                cmd.CommandText = initStr;
-                cmd.ExecuteNonQuery();
-
-                try
-                {
-                    cmd.CommandText = insertNormStr;
-                    cmd.ExecuteNonQuery();
-
-                    SqlCommand cmd2 = new SqlCommand(insertParamStr, conn);
-
-                    cmd2.Parameters.Add("@x", SqlDbType.Xml);
-                    XmlReader xr = XmlReader.Create("data.xml");
-                    cmd2.Parameters[0].Value = new SqlXml(xr);
-                    cmd2.ExecuteNonQuery();
-
-                    cmd.CommandText = queryStr;
-
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        int currentValue = 0;
-                        string[] expectedValues =
-                        {
-                            "<doc>Hello World</doc>",
-                            "<NewDataSet><builtinCLRtypes><colsbyte>1</colsbyte><colbyte>2</colbyte><colint16>-20</colint16><coluint16>40</coluint16><colint32>-300</colint32><coluint32>300</coluint32><colint64>-4000</colint64><coluint64>4000</coluint64><coldecimal>50000.01</coldecimal><coldouble>600000.987</coldouble><colsingle>70000.9</colsingle><colstring>string variable</colstring><colboolean>true</colboolean><coltimespan>P10675199DT2H48M5.4775807S</coltimespan><coldatetime>9999-12-30T23:59:59.9999999-08:00</coldatetime><colGuid>00000001-0002-0003-0405-060708010101</colGuid><colbyteArray>AQIDBAUGBwgJCgsMDQ4PEA==</colbyteArray><colUri>http://www.abc.com/</colUri><colobjectsbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"byte\">1</colobjectsbyte><colobjectbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedByte\">2</colobjectbyte><colobjectint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"short\">-20</colobjectint16><colobjectuint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedShort\">40</colobjectuint16><colobjectint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"int\">-300</colobjectint32><colobjectuint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedInt\">300</colobjectuint32><colobjectint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"long\">-4000</colobjectint64><colobjectuint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedLong\">4000</colobjectuint64><colobjectdecimal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"decimal\">50000.01</colobjectdecimal><colobjectdouble xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"double\">600000.987</colobjectdouble><colobjectsingle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"float\">70000.9</colobjectsingle><colobjectstring xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"string\">string variable</colobjectstring><colobjectboolean xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"boolean\">true</colobjectboolean><colobjecttimespan xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"duration\">P10675199DT2H48M5.4775807S</colobjecttimespan><colobjectdatetime xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"dateTime\">9999-12-30T23:59:59.9999999-08:00</colobjectdatetime><colobjectguid xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" msdata:InstanceType=\"System.Guid\">00000001-0002-0003-0405-060708010101</colobjectguid><colobjectbytearray xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"base64Binary\">AQIDBAUGBwgJCgsMDQ4PEA==</colobjectbytearray><colobjectUri xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"anyURI\">http://www.abc.com/</colobjectUri></builtinCLRtypes><builtinCLRtypes><colbyte>2</colbyte><colint16>-20</colint16><colint32>-300</colint32><coluint32>300</coluint32><coluint64>4000</coluint64><coldecimal>50000.01</coldecimal><coldouble>600000.987</coldouble><colsingle>70000.9</colsingle><colboolean>true</colboolean><colobjectsbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"byte\">11</colobjectsbyte><colobjectbyte xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedByte\">22</colobjectbyte><colobjectint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"short\">-200</colobjectint16><colobjectuint16 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedShort\">400</colobjectuint16><colobjectint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"int\">-3000</colobjectint32><colobjectuint32 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedInt\">3000</colobjectuint32><colobjectint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"long\">-40000</colobjectint64><colobjectuint64 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"unsignedLong\">40000</colobjectuint64><colobjectdecimal xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"decimal\">500000.01</colobjectdecimal><colobjectdouble xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"double\">6000000.987</colobjectdouble><colobjectsingle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"float\">700000.9</colobjectsingle><colobjectstring xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"string\">string variable 2</colobjectstring><colobjectboolean xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"boolean\">false</colobjectboolean><colobjecttimespan xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"duration\">-P10675199DT2H48M5.4775808S</colobjecttimespan><colobjectdatetime xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"dateTime\">0001-01-01T00:00:00.0000000-08:00</colobjectdatetime><colobjectguid xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" msdata:InstanceType=\"System.Guid\">00000002-0001-0001-0807-060504030201</colobjectguid><colobjectbytearray xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"base64Binary\">EA8ODQwLCgkIBwYFBAMCAQ==</colobjectbytearray></builtinCLRtypes></NewDataSet>"
-                        };
-
-                        while (reader.Read())
-                        {
-                            Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected");
-
-                            SqlXml sx = reader.GetSqlXml(0);
-                            xr = sx.CreateReader();
-                            xr.Read();
-
-                            DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], xr.ReadOuterXml(), "FAILED: Did not receive expected data");
-                        }
-                    }
-                }
-                finally
-                {
-                    cmd.CommandText = "drop table " + tempTable;
-                    cmd.ExecuteNonQuery();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MaxTypesTest()
-        {
-            string tempTable = "max_" + Guid.NewGuid().ToString().Replace('-', '_');
-            string initStr = "create table " + tempTable + " (col1 varchar(max), col2 nvarchar(max), col3 varbinary(max))";
-
-            string insertNormStr = "INSERT " + tempTable + " VALUES('ASCIASCIASCIASCIASCIASCIThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first row', ";
-            insertNormStr += "N'This is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first row', ";
-            insertNormStr += "0x010100110011000111000111000011110000111100001111000001111100000111110000011111000001111100000111110000011111000001111100000111110000011111)";
-
-            string insertParamStr = "INSERT " + tempTable + " VALUES(@x, @y, @z)";
-            string queryStr = "select * from " + tempTable;
-
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                conn.Open();
-
-                SqlCommand cmd = conn.CreateCommand();
-
-                cmd.CommandText = initStr;
-                cmd.ExecuteNonQuery();
-
-                try
-                {
-                    cmd.CommandText = insertNormStr;
-                    cmd.ExecuteNonQuery();
-
-                    SqlCommand cmd2 = new SqlCommand(insertParamStr, conn);
-
-                    cmd2.Parameters.Add("@x", SqlDbType.VarChar);
-                    cmd2.Parameters.Add("@y", SqlDbType.NVarChar);
-                    cmd2.Parameters.Add("@z", SqlDbType.VarBinary);
-                    cmd2.Parameters[1].Value = "second line, Insert big, Insert Big, This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-                    cmd2.Parameters[1].Value += "This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row";
-
-                    byte[] bytes = new byte[2];
-
-                    for (int i = 0; i < bytes.Length; ++i)
-                    {
-                        bytes[i] = 0xad;
-                    }
-                    cmd2.Parameters[2].Value = bytes;
-                    cmd2.Parameters[0].Value = "This is second row ANSI value";
-                    cmd2.ExecuteNonQuery();
-
-                    cmd.CommandText = queryStr;
-
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        int currentValue = 0;
-                        string[][] expectedValues =
-                        {
-                            new string[]
-                            {
-                                "ASCIASCIASCIASCIASCIASCIThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first row",
-                                "This is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first rowThis is the first row",
-                                "010100110011000111000111000011110000111100001111000001111100000111110000011111000001111100000111110000011111000001111100000111110000011111"
-                            },
-                            new string[]
-                            {
-                                "This is second row ANSI value",
-                                "second line, Insert big, Insert Big, This is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second rowThis is the second row",
-                                "ADAD"
-                            }
-                        };
-
-                        while (reader.Read())
-                        {
-                            Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected");
-
-                            char[] stringResult = reader.GetSqlChars(0).Value;
-                            DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue][0], new string(stringResult, 0, stringResult.Length), "FAILED: Did not receive expected data");
-                            stringResult = reader.GetSqlChars(1).Value;
-                            DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue][1], new string(stringResult, 0, stringResult.Length), "FAILED: Did not receive expected data");
-
-                            byte[] bb = reader.GetSqlBytes(2).Value;
-                            char[] cc = new char[bb.Length * 2];
-                            ConvertBinaryToChar(bb, cc);
-
-                            DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue][2], new string(cc, 0, cc.Length), "FAILED: Did not receive expected data");
-                            currentValue++;
-                        }
-                    }
-                }
-                finally
-                {
-                    cmd.CommandText = "drop table " + tempTable;
-                    cmd.ExecuteNonQuery();
-                }
-            }
-        }
-
-        private static char LocalByteToChar(int b)
-        {
-            char c;
-
-            if ((b & 0xf) < 10)
-            {
-                c = (char)((b & 0xf) + '0');
-            }
-            else
-            {
-                c = (char)((b & 0xf) - 10 + 'A');
-            }
-
-            return c;
-        }
-
-        private static void ConvertBinaryToChar(byte[] bb, char[] cc)
-        {
-            for (int i = 0; i < bb.Length; ++i)
-            {
-                cc[2 * i] = LocalByteToChar((bb[i] >> 4) & 0xf);
-                cc[2 * i + 1] = LocalByteToChar(bb[i] & 0xf);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/data.xml b/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/data.xml
deleted file mode 100644 (file)
index 7f64666..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-<?xml version="1.0" standalone="yes"?>
-<NewDataSet>
-  <builtinCLRtypes>
-    <colsbyte>1</colsbyte>
-    <colbyte>2</colbyte>
-    <colint16>-20</colint16>
-    <coluint16>40</coluint16>
-    <colint32>-300</colint32>
-    <coluint32>300</coluint32>
-    <colint64>-4000</colint64>
-    <coluint64>4000</coluint64>
-    <coldecimal>50000.01</coldecimal>
-    <coldouble>600000.987</coldouble>
-    <colsingle>70000.9</colsingle>
-    <colstring>string variable</colstring>
-    <colboolean>true</colboolean>
-    <coltimespan>P10675199DT2H48M5.4775807S</coltimespan>
-    <coldatetime>9999-12-30T23:59:59.9999999-08:00</coldatetime>
-    <colGuid>00000001-0002-0003-0405-060708010101</colGuid>
-    <colbyteArray>AQIDBAUGBwgJCgsMDQ4PEA==</colbyteArray>
-    <colUri>http://www.abc.com/</colUri>
-    <colobjectsbyte xsi:type="byte" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">1</colobjectsbyte>
-    <colobjectbyte xsi:type="unsignedByte" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">2</colobjectbyte>
-    <colobjectint16 xsi:type="short" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-20</colobjectint16>
-    <colobjectuint16 xsi:type="unsignedShort" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">40</colobjectuint16>
-    <colobjectint32 xsi:type="int" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-300</colobjectint32>
-    <colobjectuint32 xsi:type="unsignedInt" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">300</colobjectuint32>
-    <colobjectint64 xsi:type="long" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-4000</colobjectint64>
-    <colobjectuint64 xsi:type="unsignedLong" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">4000</colobjectuint64>
-    <colobjectdecimal xsi:type="decimal" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">50000.01</colobjectdecimal>
-    <colobjectdouble xsi:type="double" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">600000.987</colobjectdouble>
-    <colobjectsingle xsi:type="float" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">70000.9</colobjectsingle>
-    <colobjectstring xsi:type="string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">string variable</colobjectstring>
-    <colobjectboolean xsi:type="boolean" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">true</colobjectboolean>
-    <colobjecttimespan xsi:type="duration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">P10675199DT2H48M5.4775807S</colobjecttimespan>
-    <colobjectdatetime xsi:type="dateTime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">9999-12-30T23:59:59.9999999-08:00</colobjectdatetime>
-    <colobjectguid msdata:InstanceType="System.Guid" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">00000001-0002-0003-0405-060708010101</colobjectguid>
-    <colobjectbytearray xsi:type="base64Binary" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">AQIDBAUGBwgJCgsMDQ4PEA==</colobjectbytearray>
-    <colobjectUri xsi:type="anyURI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">http://www.abc.com/</colobjectUri>
-  </builtinCLRtypes>
-  <builtinCLRtypes>
-    <colbyte>2</colbyte>
-    <colint16>-20</colint16>
-    <colint32>-300</colint32>
-    <coluint32>300</coluint32>
-    <coluint64>4000</coluint64>
-    <coldecimal>50000.01</coldecimal>
-    <coldouble>600000.987</coldouble>
-    <colsingle>70000.9</colsingle>
-    <colboolean>true</colboolean>
-    <colobjectsbyte xsi:type="byte" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">11</colobjectsbyte>
-    <colobjectbyte xsi:type="unsignedByte" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">22</colobjectbyte>
-    <colobjectint16 xsi:type="short" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-200</colobjectint16>
-    <colobjectuint16 xsi:type="unsignedShort" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">400</colobjectuint16>
-    <colobjectint32 xsi:type="int" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-3000</colobjectint32>
-    <colobjectuint32 xsi:type="unsignedInt" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">3000</colobjectuint32>
-    <colobjectint64 xsi:type="long" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-40000</colobjectint64>
-    <colobjectuint64 xsi:type="unsignedLong" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">40000</colobjectuint64>
-    <colobjectdecimal xsi:type="decimal" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">500000.01</colobjectdecimal>
-    <colobjectdouble xsi:type="double" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">6000000.987</colobjectdouble>
-    <colobjectsingle xsi:type="float" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">700000.9</colobjectsingle>
-    <colobjectstring xsi:type="string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">string variable 2</colobjectstring>
-    <colobjectboolean xsi:type="boolean" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">false</colobjectboolean>
-    <colobjecttimespan xsi:type="duration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-P10675199DT2H48M5.4775808S</colobjecttimespan>
-    <colobjectdatetime xsi:type="dateTime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">0001-01-01T00:00:00.0000000-08:00</colobjectdatetime>
-    <colobjectguid msdata:InstanceType="System.Guid" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">00000002-0001-0001-0807-060504030201</colobjectguid>
-    <colobjectbytearray xsi:type="base64Binary" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">EA8ODQwLCgkIBwYFBAMCAQ==</colobjectbytearray>
-  </builtinCLRtypes>
-</NewDataSet>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDMARSTest/DDMARSTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DDBasics/DDMARSTest/DDMARSTest.cs
deleted file mode 100644 (file)
index 2a82b68..0000000
+++ /dev/null
@@ -1,145 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DDMARSTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestMain()
-        {
-            string connstr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString;
-            string cmdText1 = "select * from Orders; select count(*) from Customers";
-            string cmdText2 = "select * from Customers; select count(*) from Orders";
-
-            using (var conn = new SqlConnection(connstr))
-            {
-                conn.Open();
-
-                using (SqlTransaction tran = conn.BeginTransaction())
-                {
-                    SqlCommand cmd1 = conn.CreateCommand();
-                    cmd1.Transaction = tran;
-                    cmd1.CommandText = cmdText1;
-
-                    using (SqlDataReader reader1 = cmd1.ExecuteReader())
-                    {
-
-                        SqlCommand cmd2 = conn.CreateCommand();
-                        cmd2.Transaction = tran;
-                        cmd2.CommandText = cmdText2;
-
-                        using (SqlDataReader reader2 = cmd2.ExecuteReader())
-                        {
-                            int actualOrderCount = 0;
-                            while (reader1.Read())
-                            {
-                                Assert.True(actualOrderCount <= expectedOrders.Length, "FAILED: Received more results than expected");
-                                DataTestUtility.AssertEqualsWithDescription(expectedOrders[actualOrderCount], reader1.GetValue(0), "FAILED: Received wrong value in order query at row " + actualOrderCount);
-                                actualOrderCount++;
-                            }
-                            reader1.NextResult();
-                            reader1.Read();
-                            int customerCount = (int)reader1.GetValue(0);
-
-                            int actualCustomerCount = 0;
-                            while (reader2.Read())
-                            {
-                                Assert.True(actualCustomerCount <= expectedCustomers.Length, "FAILED: Received more results than expected");
-                                DataTestUtility.AssertEqualsWithDescription(expectedCustomers[actualCustomerCount], reader2.GetValue(0), "FAILED: Received wrong value in customer query at row " + actualCustomerCount);
-                                actualCustomerCount++;
-                            }
-                            reader2.NextResult();
-                            reader2.Read();
-                            int orderCount = (int)reader2.GetValue(0);
-
-                            DataTestUtility.AssertEqualsWithDescription(expectedCustomers.Length, customerCount, "FAILED: Count query returned incorrect Customer count");
-                            DataTestUtility.AssertEqualsWithDescription(expectedOrders.Length, orderCount, "FAILED: Count query returned incorrect Order count");
-                        }
-                    }
-
-                    cmd1.CommandText = "select @@trancount";
-                    int tranCount = (int)cmd1.ExecuteScalar();
-                    Assert.True(tranCount == 1, "FAILED: Expected a transaction count of 1, but actually received " + tranCount);
-
-                    tran.Commit();
-                }
-            }
-        }
-
-        private static readonly int[] expectedOrders =
-        {
-            10248, 10249, 10250, 10251, 10252, 10253, 10254, 10255, 10256, 10257, 10258, 10259, 10260, 10261, 10262, 10263,
-            10264, 10265, 10266, 10267, 10268, 10269, 10270, 10271, 10272, 10273, 10274, 10275, 10276, 10277, 10278, 10279,
-            10280, 10281, 10282, 10283, 10284, 10285, 10286, 10287, 10288, 10289, 10290, 10291, 10292, 10293, 10294, 10295,
-            10296, 10297, 10298, 10299, 10300, 10301, 10302, 10303, 10304, 10305, 10306, 10307, 10308, 10309, 10310, 10311,
-            10312, 10313, 10314, 10315, 10316, 10317, 10318, 10319, 10320, 10321, 10322, 10323, 10324, 10325, 10326, 10327,
-            10328, 10329, 10330, 10331, 10332, 10333, 10334, 10335, 10336, 10337, 10338, 10339, 10340, 10341, 10342, 10343,
-            10344, 10345, 10346, 10347, 10348, 10349, 10350, 10351, 10352, 10353, 10354, 10355, 10356, 10357, 10358, 10359,
-            10360, 10361, 10362, 10363, 10364, 10365, 10366, 10367, 10368, 10369, 10370, 10371, 10372, 10373, 10374, 10375,
-            10376, 10377, 10378, 10379, 10380, 10381, 10382, 10383, 10384, 10385, 10386, 10387, 10388, 10389, 10390, 10391,
-            10392, 10393, 10394, 10395, 10396, 10397, 10398, 10399, 10400, 10401, 10402, 10403, 10404, 10405, 10406, 10407,
-            10408, 10409, 10410, 10411, 10412, 10413, 10414, 10415, 10416, 10417, 10418, 10419, 10420, 10421, 10422, 10423,
-            10424, 10425, 10426, 10427, 10428, 10429, 10430, 10431, 10432, 10433, 10434, 10435, 10436, 10437, 10438, 10439,
-            10440, 10441, 10442, 10443, 10444, 10445, 10446, 10447, 10448, 10449, 10450, 10451, 10452, 10453, 10454, 10455,
-            10456, 10457, 10458, 10459, 10460, 10461, 10462, 10463, 10464, 10465, 10466, 10467, 10468, 10469, 10470, 10471,
-            10472, 10473, 10474, 10475, 10476, 10477, 10478, 10479, 10480, 10481, 10482, 10483, 10484, 10485, 10486, 10487,
-            10488, 10489, 10490, 10491, 10492, 10493, 10494, 10495, 10496, 10497, 10498, 10499, 10500, 10501, 10502, 10503,
-            10504, 10505, 10506, 10507, 10508, 10509, 10510, 10511, 10512, 10513, 10514, 10515, 10516, 10517, 10518, 10519,
-            10520, 10521, 10522, 10523, 10524, 10525, 10526, 10527, 10528, 10529, 10530, 10531, 10532, 10533, 10534, 10535,
-            10536, 10537, 10538, 10539, 10540, 10541, 10542, 10543, 10544, 10545, 10546, 10547, 10548, 10549, 10550, 10551,
-            10552, 10553, 10554, 10555, 10556, 10557, 10558, 10559, 10560, 10561, 10562, 10563, 10564, 10565, 10566, 10567,
-            10568, 10569, 10570, 10571, 10572, 10573, 10574, 10575, 10576, 10577, 10578, 10579, 10580, 10581, 10582, 10583,
-            10584, 10585, 10586, 10587, 10588, 10589, 10590, 10591, 10592, 10593, 10594, 10595, 10596, 10597, 10598, 10599,
-            10600, 10601, 10602, 10603, 10604, 10605, 10606, 10607, 10608, 10609, 10610, 10611, 10612, 10613, 10614, 10615,
-            10616, 10617, 10618, 10619, 10620, 10621, 10622, 10623, 10624, 10625, 10626, 10627, 10628, 10629, 10630, 10631,
-            10632, 10633, 10634, 10635, 10636, 10637, 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647,
-            10648, 10649, 10650, 10651, 10652, 10653, 10654, 10655, 10656, 10657, 10658, 10659, 10660, 10661, 10662, 10663,
-            10664, 10665, 10666, 10667, 10668, 10669, 10670, 10671, 10672, 10673, 10674, 10675, 10676, 10677, 10678, 10679,
-            10680, 10681, 10682, 10683, 10684, 10685, 10686, 10687, 10688, 10689, 10690, 10691, 10692, 10693, 10694, 10695,
-            10696, 10697, 10698, 10699, 10700, 10701, 10702, 10703, 10704, 10705, 10706, 10707, 10708, 10709, 10710, 10711,
-            10712, 10713, 10714, 10715, 10716, 10717, 10718, 10719, 10720, 10721, 10722, 10723, 10724, 10725, 10726, 10727,
-            10728, 10729, 10730, 10731, 10732, 10733, 10734, 10735, 10736, 10737, 10738, 10739, 10740, 10741, 10742, 10743,
-            10744, 10745, 10746, 10747, 10748, 10749, 10750, 10751, 10752, 10753, 10754, 10755, 10756, 10757, 10758, 10759,
-            10760, 10761, 10762, 10763, 10764, 10765, 10766, 10767, 10768, 10769, 10770, 10771, 10772, 10773, 10774, 10775,
-            10776, 10777, 10778, 10779, 10780, 10781, 10782, 10783, 10784, 10785, 10786, 10787, 10788, 10789, 10790, 10791,
-            10792, 10793, 10794, 10795, 10796, 10797, 10798, 10799, 10800, 10801, 10802, 10803, 10804, 10805, 10806, 10807,
-            10808, 10809, 10810, 10811, 10812, 10813, 10814, 10815, 10816, 10817, 10818, 10819, 10820, 10821, 10822, 10823,
-            10824, 10825, 10826, 10827, 10828, 10829, 10830, 10831, 10832, 10833, 10834, 10835, 10836, 10837, 10838, 10839,
-            10840, 10841, 10842, 10843, 10844, 10845, 10846, 10847, 10848, 10849, 10850, 10851, 10852, 10853, 10854, 10855,
-            10856, 10857, 10858, 10859, 10860, 10861, 10862, 10863, 10864, 10865, 10866, 10867, 10868, 10869, 10870, 10871,
-            10872, 10873, 10874, 10875, 10876, 10877, 10878, 10879, 10880, 10881, 10882, 10883, 10884, 10885, 10886, 10887,
-            10888, 10889, 10890, 10891, 10892, 10893, 10894, 10895, 10896, 10897, 10898, 10899, 10900, 10901, 10902, 10903,
-            10904, 10905, 10906, 10907, 10908, 10909, 10910, 10911, 10912, 10913, 10914, 10915, 10916, 10917, 10918, 10919,
-            10920, 10921, 10922, 10923, 10924, 10925, 10926, 10927, 10928, 10929, 10930, 10931, 10932, 10933, 10934, 10935,
-            10936, 10937, 10938, 10939, 10940, 10941, 10942, 10943, 10944, 10945, 10946, 10947, 10948, 10949, 10950, 10951,
-            10952, 10953, 10954, 10955, 10956, 10957, 10958, 10959, 10960, 10961, 10962, 10963, 10964, 10965, 10966, 10967,
-            10968, 10969, 10970, 10971, 10972, 10973, 10974, 10975, 10976, 10977, 10978, 10979, 10980, 10981, 10982, 10983,
-            10984, 10985, 10986, 10987, 10988, 10989, 10990, 10991, 10992, 10993, 10994, 10995, 10996, 10997, 10998, 10999,
-            11000, 11001, 11002, 11003, 11004, 11005, 11006, 11007, 11008, 11009, 11010, 11011, 11012, 11013, 11014, 11015,
-            11016, 11017, 11018, 11019, 11020, 11021, 11022, 11023, 11024, 11025, 11026, 11027, 11028, 11029, 11030, 11031,
-            11032, 11033, 11034, 11035, 11036, 11037, 11038, 11039, 11040, 11041, 11042, 11043, 11044, 11045, 11046, 11047,
-            11048, 11049, 11050, 11051, 11052, 11053, 11054, 11055, 11056, 11057, 11058, 11059, 11060, 11061, 11062, 11063,
-            11064, 11065, 11066, 11067, 11068, 11069, 11070, 11071, 11072, 11073, 11074, 11075, 11076, 11077
-        };
-
-        private static readonly string[] expectedCustomers =
-        {
-            "ALFKI", "ANATR", "ANTON", "AROUT", "BERGS", "BLAUS", "BLONP", "BOLID",
-            "BONAP", "BOTTM", "BSBEV", "CACTU", "CENTC", "CHOPS", "COMMI", "CONSH",
-            "DRACD", "DUMON", "EASTC", "ERNSH", "FAMIA", "FISSA", "FOLIG", "FOLKO",
-            "FRANK", "FRANR", "FRANS", "FURIB", "GALED", "GODOS", "GOURL", "GREAL",
-            "GROSR", "HANAR", "HILAA", "HUNGC", "HUNGO", "ISLAT", "KOENE", "LACOR",
-            "LAMAI", "LAUGB", "LAZYK", "LEHMS", "LETSS", "LILAS", "LINOD", "LONEP",
-            "MAGAA", "MAISD", "MEREP", "MORGK", "NORTS", "OCEAN", "OLDWO", "OTTIK",
-            "PARIS", "PERIC", "PICCO", "PRINI", "QUEDE", "QUEEN", "QUICK", "RANCH",
-            "RATTC", "REGGC", "RICAR", "RICSU", "ROMEY", "SANTG", "SAVEA", "SEVES",
-            "SIMOB", "SPECD", "SPLIR", "SUPRD", "THEBI", "THECR", "TOMSP", "TORTU",
-            "TRADH", "TRAIH", "VAFFE", "VICTE", "VINET", "WANDK", "WARTH", "WELLI",
-            "WHITC", "WILMK", "WOLZA"
-        };
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs
deleted file mode 100644 (file)
index 20dece2..0000000
+++ /dev/null
@@ -1,73 +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.Generic;
-using System.Dynamic;
-using System.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// base class that converts dynamic properties / methods into ResourceManager.GetString(name) calls
-    /// Dynamic properties are generated using the resource name as "assemblyResourceManager.ResourceName". Using the property once can get string
-    /// for this resource localized in the current thread's UI culture.
-    /// Dynamic methods allow similar functionality as properties, except that they allow the user to specific different culture and/or format arguments (if resource is a format string).
-    /// Methods are prefixes with "Get_". For example: Get_ResourceName(CultureInfo.Culture, arg1, arg2). CultureInfo must be the first argument, if present!
-    ///
-    /// see SystemDataResouceManager implementation for usage.
-    /// </summary>
-    public class AssemblyResourceManager : DynamicObject
-    {
-        private System.Reflection.Assembly _resourceAssembly;
-
-        public AssemblyResourceManager(Assembly assembly)
-        {
-            _resourceAssembly = assembly;
-        }
-
-        public override IEnumerable<string> GetDynamicMemberNames()
-        {
-            return new List<string>();
-        }
-
-        /// <summary>
-        /// enables dynamic property: asmResourceManager.ResourceName
-        /// </summary>
-        public override bool TryGetMember(GetMemberBinder binder, out object result)
-        {
-            return TryGetResourceValue(binder.Name, null, out result);
-        }
-
-        /// <summary>
-        /// enables dynamic property: asmResourceManager.ResourceName (params object[] args)
-        /// This also support asmResourceManager.Get_ResourceName for old test as well
-        /// </summary>
-        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
-        {
-            var resourceName = binder.Name;
-            if (resourceName.StartsWith("Get_"))
-                resourceName = resourceName.Remove(0, 4);
-
-            return TryGetResourceValue(resourceName, args, out result);
-        }
-
-
-        private bool TryGetResourceValue(string resourceName, object[] args, out object result)
-        {
-            var type = _resourceAssembly.GetType("System.SR");
-            var info = type.GetProperty(resourceName, BindingFlags.NonPublic | BindingFlags.Static);
-
-            result = null;
-            if (info != null)
-            {
-                result = info.GetValue(null);
-                if (args != null)
-                {
-                    result = string.Format((string)result, args);
-                }
-            }
-            return result != null;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataSourceBuilder.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataSourceBuilder.cs
deleted file mode 100644 (file)
index 76f3cc7..0000000
+++ /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.Text;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class DataSourceBuilder
-    {
-        public DataSourceBuilder(string dataSource)
-        {
-            // Extract port number
-            string[] commaSplit = dataSource.Split(',');
-
-            if (commaSplit.Length == 2)
-            {
-                // If the string cannot be converted to integer that indicates a user error and
-                // we want that exception to bubble up. Hence using Parse instead of TryParse.
-                Port = int.Parse(commaSplit[1].Trim());
-            }
-            else if (commaSplit.Length > 2)
-            {
-                throw new ArgumentException(string.Format("commaSplit of string {0} has length {1}", dataSource, commaSplit.Length));
-            }
-
-            // Extract protocol and server name
-            string ProtocolAndServerName = commaSplit[0].Trim();
-            string[] colonSplit = ProtocolAndServerName.Split(':');
-
-            if (colonSplit.Length == 1)
-            {
-                ServerName = colonSplit[0];
-            }
-            else if (colonSplit.Length == 2)
-            {
-                Protocol = colonSplit[0];
-                ServerName = colonSplit[1];
-            }
-            else
-            {
-                throw new ArgumentException(string.Format("colonSplit of string {0} has length {1}", ProtocolAndServerName, colonSplit.Length));
-            }
-        }
-
-        public string Protocol { get; set; }
-
-        public string ServerName { get; set; }
-
-        public int? Port { get; set; }
-
-        public override string ToString()
-        {
-            StringBuilder b = new StringBuilder();
-
-            if (Protocol != null)
-            {
-                b.Append(Protocol);
-                b.Append(":");
-            }
-
-            b.Append(ServerName);
-
-            if (Port != null)
-            {
-                b.Append(",");
-                b.Append(Port);
-            }
-
-            return b.ToString();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs
deleted file mode 100644 (file)
index e270e2c..0000000
+++ /dev/null
@@ -1,350 +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.Generic;
-using System.Globalization;
-using System.Reflection;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DataTestUtility
-    {
-        public static readonly string NpConnStr = null;
-        public static readonly string TcpConnStr = null;
-
-        public const string UdtTestDbName = "UdtTestDb";
-
-        private static readonly Assembly s_systemDotData = typeof(System.Data.SqlClient.SqlConnection).GetTypeInfo().Assembly;
-        private static readonly Type s_tdsParserStateObjectFactory = s_systemDotData?.GetType("System.Data.SqlClient.TdsParserStateObjectFactory");
-        private static readonly PropertyInfo s_useManagedSNI = s_tdsParserStateObjectFactory?.GetProperty("UseManagedSNI", BindingFlags.Static | BindingFlags.Public);
-
-        private static readonly string[] s_azureSqlServerEndpoints = {".database.windows.net",
-                                                                     ".database.cloudapi.de",
-                                                                     ".database.usgovcloudapi.net",
-                                                                     ".database.chinacloudapi.cn"};
-
-        private static Dictionary<string, bool> databasesAvailable;
-
-        static DataTestUtility()
-        {
-            NpConnStr = Environment.GetEnvironmentVariable("TEST_NP_CONN_STR");
-            TcpConnStr = Environment.GetEnvironmentVariable("TEST_TCP_CONN_STR");
-        }
-
-        public static bool AreConnStringsSetup()
-        {
-            return !string.IsNullOrEmpty(NpConnStr) && !string.IsNullOrEmpty(TcpConnStr);
-        }
-
-        public static bool IsDatabasePresent(string name)
-        {
-            databasesAvailable = databasesAvailable ?? new Dictionary<string, bool>();
-            bool present = false;
-            if (AreConnStringsSetup() && !string.IsNullOrEmpty(name) && !databasesAvailable.TryGetValue(name, out present))
-            {
-                var builder = new SqlConnectionStringBuilder(TcpConnStr);
-                builder.ConnectTimeout = 2;
-                using (var connection = new SqlConnection(builder.ToString()))
-                using (var command = new SqlCommand("SELECT COUNT(*) FROM sys.databases WHERE name=@name", connection))
-                {
-                    connection.Open();
-                    command.Parameters.AddWithValue("name", name);
-                    present = Convert.ToInt32(command.ExecuteScalar()) == 1;
-                }
-                databasesAvailable[name] = present;
-            }
-            return present;
-        }
-
-        public static bool IsUdtTestDatabasePresent() => IsDatabasePresent(UdtTestDbName);
-
-        public static bool IsUsingManagedSNI() => (bool)(s_useManagedSNI?.GetValue(null) ?? false);
-
-        public static bool IsUsingNativeSNI() => !IsUsingManagedSNI();
-
-        public static bool IsUTF8Supported()
-        {
-            bool retval = false;
-            if (AreConnStringsSetup())
-            {
-                using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (SqlCommand command = new SqlCommand())
-                {
-                    command.Connection = connection;
-                    command.CommandText = "SELECT CONNECTIONPROPERTY('SUPPORT_UTF8')";
-                    connection.Open();
-
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        while (reader.Read())
-                        {
-                            // CONNECTIONPROPERTY('SUPPORT_UTF8') returns NULL in SQLServer versions that don't support UTF-8.
-                            retval = !reader.IsDBNull(0);
-                        }
-                    }
-                }
-            }
-            return retval;
-        }
-
-        // the name length will be no more then (16 + prefix.Length + escapeLeft.Length + escapeRight.Length)
-        // some providers does not support names (Oracle supports up to 30)
-        public static string GetUniqueName(string prefix, string escapeLeft, string escapeRight)
-        {
-            string uniqueName = string.Format("{0}{1}_{2}_{3}{4}",
-                escapeLeft,
-                prefix,
-                DateTime.Now.Ticks.ToString("X", CultureInfo.InvariantCulture), // up to 8 characters
-                Guid.NewGuid().ToString().Substring(0, 6), // take the first 6 characters only
-                escapeRight);
-            return uniqueName;
-        }
-
-        // SQL Server supports long names (up to 128 characters), add extra info for troubleshooting
-        public static string GetUniqueNameForSqlServer(string prefix)
-        {
-            string extendedPrefix = string.Format(
-                "{0}_{1}@{2}",
-                prefix,
-                Environment.UserName,
-                Environment.MachineName,
-                DateTime.Now.ToString("yyyy_MM_dd", CultureInfo.InvariantCulture));
-            string name = GetUniqueName(extendedPrefix, "[", "]");
-            if (name.Length > 128)
-            {
-                throw new ArgumentOutOfRangeException("the name is too long - SQL Server names are limited to 128");
-            }
-            return name;
-        }
-
-        public static bool IsLocalDBInstalled() => int.TryParse(Environment.GetEnvironmentVariable("TEST_LOCALDB_INSTALLED"), out int result) ? result == 1 : false;
-
-        public static bool IsIntegratedSecuritySetup() => int.TryParse(Environment.GetEnvironmentVariable("TEST_INTEGRATEDSECURITY_SETUP"), out int result) ? result == 1 : false;
-
-        public static string getAccessToken()
-        {
-            return Environment.GetEnvironmentVariable("TEST_ACCESSTOKEN_SETUP");
-        }
-
-        public static bool IsAccessTokenSetup() => string.IsNullOrEmpty(getAccessToken()) ? false : true;
-
-        public static bool IsFileStreamSetup() => int.TryParse(Environment.GetEnvironmentVariable("TEST_FILESTREAM_SETUP"), out int result) ? result == 1 : false;
-
-        // 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 < s_azureSqlServerEndpoints.Length; i++)
-            {
-                if (dataSource.EndsWith(s_azureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase))
-                {
-                    return true;
-                }
-            }
-            return false;
-        }
-
-        private static bool CheckException<TException>(Exception ex, string exceptionMessage, bool innerExceptionMustBeNull) where TException : Exception
-        {
-            return ((ex != null) && (ex is TException) &&
-                ((string.IsNullOrEmpty(exceptionMessage)) || (ex.Message.Contains(exceptionMessage))) &&
-                ((!innerExceptionMustBeNull) || (ex.InnerException == null)));
-        }
-
-        public static void AssertEqualsWithDescription(object expectedValue, object actualValue, string failMessage)
-        {
-            if (expectedValue == null || actualValue == null)
-            {
-                var msg = string.Format("{0}\nExpected: {1}\nActual: {2}", failMessage, expectedValue, actualValue);
-                Assert.True(expectedValue == actualValue, msg);
-            }
-            else
-            {
-                var msg = string.Format("{0}\nExpected: {1} ({2})\nActual: {3} ({4})", failMessage, expectedValue, expectedValue.GetType(), actualValue, actualValue.GetType());
-                Assert.True(expectedValue.Equals(actualValue), msg);
-            }
-        }
-
-        public static TException AssertThrowsWrapper<TException>(Action actionThatFails, string exceptionMessage = null, bool innerExceptionMustBeNull = false, Func<TException, bool> customExceptionVerifier = null) where TException : Exception
-        {
-            TException ex = Assert.Throws<TException>(actionThatFails);
-            if (exceptionMessage != null)
-            {
-                Assert.True(ex.Message.Contains(exceptionMessage),
-                    string.Format("FAILED: Exception did not contain expected message.\nExpected: {0}\nActual: {1}", exceptionMessage, ex.Message));
-            }
-
-            if (innerExceptionMustBeNull)
-            {
-                Assert.True(ex.InnerException == null, "FAILED: Expected InnerException to be null.");
-            }
-
-            if (customExceptionVerifier != null)
-            {
-                Assert.True(customExceptionVerifier(ex), "FAILED: Custom exception verifier returned false for this exception.");
-            }
-
-            return ex;
-        }
-
-        public static TException AssertThrowsWrapper<TException, TInnerException>(Action actionThatFails, string exceptionMessage = null, string innerExceptionMessage = null, bool innerExceptionMustBeNull = false, Func<TException, bool> customExceptionVerifier = null) where TException : Exception
-        {
-            TException ex = AssertThrowsWrapper<TException>(actionThatFails, exceptionMessage, innerExceptionMustBeNull, customExceptionVerifier);
-
-            if (innerExceptionMessage != null)
-            {
-                Assert.True(ex.InnerException != null, "FAILED: Cannot check innerExceptionMessage because InnerException is null.");
-                Assert.True(ex.InnerException.Message.Contains(innerExceptionMessage),
-                    string.Format("FAILED: Inner Exception did not contain expected message.\nExpected: {0}\nActual: {1}", innerExceptionMessage, ex.InnerException.Message));
-            }
-
-            return ex;
-        }
-
-        public static TException AssertThrowsWrapper<TException, TInnerException, TInnerInnerException>(Action actionThatFails, string exceptionMessage = null, string innerExceptionMessage = null, string innerInnerExceptionMessage = null, bool innerInnerInnerExceptionMustBeNull = false) where TException : Exception where TInnerException : Exception where TInnerInnerException : Exception
-        {
-            TException ex = AssertThrowsWrapper<TException, TInnerException>(actionThatFails, exceptionMessage, innerExceptionMessage);
-            if (innerInnerInnerExceptionMustBeNull)
-            {
-                Assert.True(ex.InnerException != null, "FAILED: Cannot check innerInnerInnerExceptionMustBeNull since InnerException is null");
-                Assert.True(ex.InnerException.InnerException == null, "FAILED: Expected InnerInnerException to be null.");
-            }
-
-            if (innerInnerExceptionMessage != null)
-            {
-                Assert.True(ex.InnerException != null, "FAILED: Cannot check innerInnerExceptionMessage since InnerException is null");
-                Assert.True(ex.InnerException.InnerException != null, "FAILED: Cannot check innerInnerExceptionMessage since InnerInnerException is null");
-                Assert.True(ex.InnerException.InnerException.Message.Contains(innerInnerExceptionMessage),
-                    string.Format("FAILED: Inner Exception did not contain expected message.\nExpected: {0}\nActual: {1}", innerInnerExceptionMessage, ex.InnerException.InnerException.Message));
-            }
-
-            return ex;
-        }
-
-        public static TException ExpectFailure<TException>(Action actionThatFails, string[] exceptionMessages, bool innerExceptionMustBeNull = false, Func<TException, bool> customExceptionVerifier = null) where TException : Exception
-        {
-            try
-            {
-                actionThatFails();
-                Console.WriteLine("ERROR: Did not get expected exception");
-                return null;
-            }
-            catch (Exception ex)
-            {
-                foreach (string exceptionMessage in exceptionMessages)
-                {
-                    if ((CheckException<TException>(ex, exceptionMessage, innerExceptionMustBeNull)) && ((customExceptionVerifier == null) || (customExceptionVerifier(ex as TException))))
-                    {
-                        return (ex as TException);
-                    }
-                }
-                throw;
-            }
-        }
-
-        public static TException ExpectFailure<TException, TInnerException>(Action actionThatFails, string exceptionMessage = null, string innerExceptionMessage = null, bool innerInnerExceptionMustBeNull = false) where TException : Exception where TInnerException : Exception
-        {
-            try
-            {
-                actionThatFails();
-                Console.WriteLine("ERROR: Did not get expected exception");
-                return null;
-            }
-            catch (Exception ex)
-            {
-                if ((CheckException<TException>(ex, exceptionMessage, false)) && (CheckException<TInnerException>(ex.InnerException, innerExceptionMessage, innerInnerExceptionMustBeNull)))
-                {
-                    return (ex as TException);
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        public static TException ExpectFailure<TException, TInnerException, TInnerInnerException>(Action actionThatFails, string exceptionMessage = null, string innerExceptionMessage = null, string innerInnerExceptionMessage = null, bool innerInnerInnerExceptionMustBeNull = false) where TException : Exception where TInnerException : Exception where TInnerInnerException : Exception
-        {
-            try
-            {
-                actionThatFails();
-                Console.WriteLine("ERROR: Did not get expected exception");
-                return null;
-            }
-            catch (Exception ex)
-            {
-                if ((CheckException<TException>(ex, exceptionMessage, false)) && (CheckException<TInnerException>(ex.InnerException, innerExceptionMessage, false)) && (CheckException<TInnerInnerException>(ex.InnerException.InnerException, innerInnerExceptionMessage, innerInnerInnerExceptionMustBeNull)))
-                {
-                    return (ex as TException);
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-        public static void ExpectAsyncFailure<TException>(Func<Task> actionThatFails, string exceptionMessage = null, bool innerExceptionMustBeNull = false) where TException : Exception
-        {
-            ExpectFailure<AggregateException, TException>(() => actionThatFails().Wait(), null, exceptionMessage, innerExceptionMustBeNull);
-        }
-
-        public static void ExpectAsyncFailure<TException, TInnerException>(Func<Task> actionThatFails, string exceptionMessage = null, string innerExceptionMessage = null, bool innerInnerExceptionMustBeNull = false) where TException : Exception where TInnerException : Exception
-        {
-            ExpectFailure<AggregateException, TException, TInnerException>(() => actionThatFails().Wait(), null, exceptionMessage, innerExceptionMessage, innerInnerExceptionMustBeNull);
-        }
-
-        public static string GenerateTableName()
-        {
-            return string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_');
-        }
-
-        public static void RunNonQuery(string connectionString, string sql)
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            using (SqlCommand command = connection.CreateCommand())
-            {
-                connection.Open();
-                command.CommandText = sql;
-                command.ExecuteNonQuery();
-            }
-        }
-
-        public static DataTable RunQuery(string connectionString, string sql)
-        {
-            DataTable result = null;
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                using (SqlCommand command = connection.CreateCommand())
-                {
-                    command.CommandText = sql;
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        result = new DataTable();
-                        result.Load(reader);
-                    }
-                }
-            }
-            return result;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/ProxyServer.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/ProxyServer.cs
deleted file mode 100644 (file)
index 93f0e08..0000000
+++ /dev/null
@@ -1,537 +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.Data.SqlClient;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// This is a simple network listener that redirects traffic
-    /// It is used to simulate network delay
-    /// </summary>
-    public class ProxyServer : IDisposable
-    {
-        private volatile bool _stopRequested;
-        private StringBuilder _eventLog;
-        private static string s_logHeader = "======== ProxyServer Log Start ========\n";
-        private static string s_logTrailer = "======== ProxyServer Log End ========\n";
-
-        /// <summary>
-        /// Gets/Sets the event log for the proxy server
-        /// </summary>
-        internal StringBuilder EventLog
-        {
-            get
-            {
-                if (_eventLog == null)
-                    _eventLog = new StringBuilder();
-                if (_eventLog.Length == 0)
-                    _eventLog.Append(s_logHeader);
-                return _eventLog;
-            }
-            set
-            {
-                _eventLog = value;
-            }
-        }
-
-        /// <summary>
-        /// The list of connections spawned by the server
-        /// </summary>
-        internal IList<ProxyServerConnection> Connections { get; private set; }
-
-        /// <summary>
-        /// Synchronization object on the list
-        /// </summary>
-        internal object SyncRoot { get; private set; }
-
-        /// <summary>
-        /// Gets the local port that is being listened on
-        /// </summary>
-        public int LocalPort { get; private set; }
-
-        /// <summary>
-        /// Gets/Sets the remote end point to connect to
-        /// </summary>
-        public IPEndPoint RemoteEndpoint { get; set; }
-
-        /// <summary>
-        /// Gets/Sets the listener
-        /// </summary>
-        protected TcpListener ListenerSocket { get; set; }
-
-        /// <summary>
-        /// Gets/Sets the listener thread
-        /// </summary>
-        protected Thread ListenerThread { get; set; }
-
-        /// <summary>
-        /// Delay incoming
-        /// </summary>
-        public bool SimulatedInDelay { get; set; }
-
-        /// <summary>
-        /// Delay outgoing
-        /// </summary>
-        public bool SimulatedOutDelay { get; set; }
-
-        /// <summary>
-        /// Simulated delay in milliseconds between message being received and message being sent. This simulates network latency.
-        /// </summary>
-        public int SimulatedNetworkDelay { get; set; }
-
-        /// <summary>
-        /// Simulated delay in milliseconds between each packet being written out. This simulates low bandwidth connection.
-        /// </summary>
-        public int SimulatedPacketDelay { get; set; }
-
-        /// <summary>
-        /// Size of Buffer
-        /// </summary>
-        public int BufferSize { get; set; }
-
-        /// <summary>
-        /// Gets/Sets the flag whether the stop is requested
-        /// </summary>
-        internal bool StopRequested { get { return _stopRequested; } set { _stopRequested = value; } }
-
-        /// <summary>
-        /// Gets a reset event that signals if copying is currently permitted (if it is not signaled, then all copying must wait)
-        /// </summary>
-        internal ManualResetEventSlim PermitCopying { get; private set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public ProxyServer(int simulatedNetworkDelay = 0, int simulatedPacketDelay = 0, bool simulatedInDelay = false, bool simulatedOutDelay = false, int bufferSize = 8192)
-        {
-            SyncRoot = new object();
-            Connections = new List<ProxyServerConnection>();
-            SimulatedNetworkDelay = simulatedNetworkDelay;
-            SimulatedPacketDelay = simulatedPacketDelay;
-            SimulatedInDelay = simulatedInDelay;
-            SimulatedOutDelay = simulatedOutDelay;
-            BufferSize = bufferSize;
-            PermitCopying = new ManualResetEventSlim(true);
-        }
-
-        /// <summary>
-        /// Start the listener thread
-        /// </summary>
-        public void Start()
-        {
-            StopRequested = false;
-
-            Log("Starting the server...");
-
-            // Listen on any port
-            ListenerSocket = new TcpListener(IPAddress.Loopback, 0);
-            ListenerSocket.Start();
-
-            Log("Server is running on {0}...", ListenerSocket.LocalEndpoint);
-
-            LocalPort = ((IPEndPoint)ListenerSocket.LocalEndpoint).Port;
-
-            ListenerThread = new Thread(new ThreadStart(_RequestListener));
-            ListenerThread.Name = "Proxy Server Listener";
-            ListenerThread.Start();
-        }
-
-        /// <summary>
-        /// Stop the listener thread
-        /// </summary>
-        public void Stop()
-        {
-            // Resume copying to allow buffers to flush
-            ResumeCopying();
-
-            // Request the listener thread to stop
-            StopRequested = true;
-
-            // Wait for termination
-            ListenerThread.Join(1000);
-        }
-
-        public void Dispose()
-        {
-            Stop();
-        }
-
-        /// <summary>
-        /// This method is used internally to notify server about the client disconnection
-        /// </summary>
-        internal void NotifyClientDisconnection(ProxyServerConnection connection)
-        {
-            lock (SyncRoot)
-            {
-                // Remove the existing connection from the list
-                Connections.Remove(connection);
-            }
-        }
-
-        /// <summary>
-        /// Processes all incoming requests
-        /// </summary>
-        private void _RequestListener()
-        {
-            try
-            {
-                while (!StopRequested)
-                {
-                    if (ListenerSocket.Pending())
-                    {
-                        try
-                        {
-                            Log("Connection received");
-
-                            // Accept the connection
-                            Task<Socket> connectTask = ListenerSocket.AcceptSocketAsync();
-                            connectTask.Wait();
-                            Socket newConnection = connectTask.Result;
-
-                            // Start a new connection
-                            ProxyServerConnection proxyConnection = new ProxyServerConnection(newConnection, this);
-                            proxyConnection.Start();
-
-                            // Registering new connection
-                            lock (SyncRoot)
-                            {
-                                Connections.Add(proxyConnection);
-                            }
-                        }
-                        catch (Exception ex)
-                        {
-                            Log(ex.ToString());
-                        }
-                    }
-                    else
-                    {
-                        // Pause a bit
-                        Thread.Sleep(10);
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                Log(ex.ToString());
-            }
-
-            Log("Stopping the server...");
-
-            // Stop the server
-            ListenerSocket.Stop();
-            ListenerSocket = null;
-
-            Log("Waiting for client connections to terminate...");
-
-            // Wait for connections
-            int connectionsLeft = short.MaxValue;
-            while (connectionsLeft > 0)
-            {
-                lock (SyncRoot)
-                {
-                    // Check the amount of connections left
-                    connectionsLeft = Connections.Count;
-                }
-
-                // Wait a bit
-                Thread.Sleep(10);
-            }
-
-            Log("Server is stopped");
-        }
-
-
-        /// <summary>
-        /// Write a string to the log
-        /// </summary>
-        internal void Log(string text, params object[] args)
-        {
-            if (EventLog != null)
-            {
-                EventLog.AppendFormat("[{0:O}]: ", DateTime.Now);
-                EventLog.AppendFormat(text, args);
-                EventLog.AppendLine();
-            }
-        }
-
-        /// <summary>
-        /// Return the ProxyServer log
-        /// </summary>
-        /// <returns></returns>
-        public string GetServerEventLog()
-        {
-            EventLog.Append(s_logTrailer);
-            EventLog.AppendLine();
-            return EventLog.ToString();
-        }
-
-        /// <summary>
-        /// Signals to all connections to stop copying between their streams
-        /// </summary>
-        public void PauseCopying()
-        {
-            PermitCopying.Reset();
-        }
-
-        /// <summary>
-        /// Signals to all connections to continue copying between their streams
-        /// </summary>
-        public void ResumeCopying()
-        {
-            PermitCopying.Set();
-        }
-
-        /// <summary>
-        /// Kills all currently open connections
-        /// </summary>
-        /// <param name="softKill">If true will perform a shutdown before closing, otherwise close will happen with lingering disabled</param>
-        public void KillAllConnections(bool softKill = false)
-        {
-            lock (SyncRoot)
-            {
-                foreach (var connection in Connections)
-                {
-                    connection.Kill(softKill);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Creates a proxy server from the server in the given connection string using the default construction parameters and starts the proxy
-        /// </summary>
-        /// <param name="connectionString">Connection string to the server to proxy</param>
-        /// <param name="newConnectionString">Connection string to the proxy server (using the same parameters as <paramref name="connectionString"/>)</param>
-        /// <returns>The created and started proxy server</returns>
-        public static ProxyServer CreateAndStartProxy(string connectionString, out string newConnectionString)
-        {
-            // Build builders
-            SqlConnectionStringBuilder connStringbuilder = new SqlConnectionStringBuilder(connectionString);
-            DataSourceBuilder dataSourceBuilder = new DataSourceBuilder(connStringbuilder.DataSource);
-
-            // Setup proxy
-            Task<System.Net.IPHostEntry> ipEntryTask = Dns.GetHostEntryAsync(dataSourceBuilder.ServerName);
-            ipEntryTask.Wait();
-            System.Net.IPHostEntry serverIpEntry = ipEntryTask.Result;
-
-            ProxyServer proxy = new ProxyServer();
-            proxy.RemoteEndpoint = new IPEndPoint(serverIpEntry.AddressList[0], dataSourceBuilder.Port ?? 1433);
-            proxy.Start();
-
-            // Switch connection over
-            dataSourceBuilder.Protocol = "tcp";
-            dataSourceBuilder.ServerName = "127.0.0.1";
-            dataSourceBuilder.Port = proxy.LocalPort;
-            connStringbuilder.DataSource = dataSourceBuilder.ToString();
-            connStringbuilder.Remove("Network Library");
-
-            newConnectionString = connStringbuilder.ToString();
-            return proxy;
-        }
-    }
-
-    /// <summary>
-    /// This class maintains the tunnel between incoming connection and outgoing connection
-    /// </summary>
-    internal class ProxyServerConnection
-    {
-        /// <summary>
-        /// This is a processing thread
-        /// </summary>
-        protected Thread ProcessorThread { get; set; }
-
-        /// <summary>
-        /// Returns the proxy server this connection belongs to
-        /// </summary>
-        public ProxyServer Server { get; set; }
-
-        /// <summary>
-        /// Incoming connection
-        /// </summary>
-        protected Socket IncomingConnection { get; set; }
-
-        /// <summary>
-        /// Outgoing connection
-        /// </summary>
-        protected Socket OutgoingConnection { get; set; }
-
-        /// <summary>
-        /// Standard constructor
-        /// </summary>
-        public ProxyServerConnection(Socket incomingConnection, ProxyServer server)
-        {
-            IncomingConnection = incomingConnection;
-            Server = server;
-        }
-
-        /// <summary>
-        /// Runs the processing thread
-        /// </summary>
-        public void Start()
-        {
-            ProcessorThread = new Thread(new ThreadStart(_ProcessorHandler));
-
-            IPEndPoint incomingIPEndPoint = IncomingConnection.RemoteEndPoint as IPEndPoint;
-            ProcessorThread.Name = string.Format("Proxy Server Connection {0} Thread", incomingIPEndPoint);
-
-            ProcessorThread.Start();
-        }
-
-        /// <summary>
-        /// Handles the bidirectional data transfers
-        /// </summary>
-        private void _ProcessorHandler()
-        {
-            try
-            {
-                Server.Log("Connecting to {0}...", Server.RemoteEndpoint);
-                Server.Log("Remote end point address family {0}", Server.RemoteEndpoint.AddressFamily);
-
-                // Establish outgoing connection to the proxy
-                OutgoingConnection = new Socket(Server.RemoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
-                Task connectTask = OutgoingConnection.ConnectAsync(Server.RemoteEndpoint.Address, Server.RemoteEndpoint.Port);
-                connectTask.Wait(1000);
-
-                // Writing connection information
-                Server.Log("Connection established");
-
-                // Obtain network streams
-                NetworkStream outStream = new NetworkStream(OutgoingConnection, true);
-                NetworkStream inStream = new NetworkStream(IncomingConnection, true);
-
-                // Ensure copying isn't paused
-                Server.PermitCopying.Wait();
-
-                // Tunnel the traffic between two connections
-                while (IncomingConnection.Connected && OutgoingConnection.Connected && !Server.StopRequested)
-                {
-                    bool DataAvailable = false;
-
-                    // Check incoming buffer
-                    if (inStream.DataAvailable)
-                    {
-                        DataAvailable = true;
-                        CopyData(inStream, "client", outStream, "server", Server.SimulatedInDelay);
-                    }
-
-
-                    // Check outgoing buffer
-                    if (outStream.DataAvailable)
-                    {
-                        DataAvailable = true;
-                        CopyData(outStream, "server", inStream, "client", Server.SimulatedOutDelay);
-                    }
-
-                    // Pause
-                    if (DataAvailable)
-                    {
-                        // Poll the sockets
-                        if ((IncomingConnection.Poll(100, SelectMode.SelectRead) && !inStream.DataAvailable) ||
-                            (OutgoingConnection.Poll(100, SelectMode.SelectRead) && !outStream.DataAvailable))
-                            break;
-
-                        Thread.Sleep(10);
-                    }
-                    else
-                    {
-                        Thread.Sleep(1);
-                    }
-
-                    // Ensure copying isn't paused
-                    Server.PermitCopying.Wait();
-                }
-            }
-            catch (Exception ex)
-            {
-                Server.Log(ex.ToString());
-            }
-
-            try
-            {
-                // Disconnect the client
-                IncomingConnection.Dispose();
-                OutgoingConnection.Dispose();
-            }
-            catch (Exception) { }
-
-            // Logging disconnection message
-            Server.Log("Connection closed");
-
-            // Notify parent
-            Server.NotifyClientDisconnection(this);
-        }
-
-        private void CopyData(NetworkStream readStream, string readStreamName, NetworkStream writeStream, string writeStreamName, bool simulateDelay)
-        {
-            // Note that the latency/bandwidth delay algorithm used here is a simple approximation used for test purposes
-
-            Server.Log("Copying message from {0} to {1}", readStreamName, writeStreamName);
-
-            // Read all available data from readStream
-            var outBytes = new List<Tuple<byte[], int>>();
-            while (readStream.DataAvailable)
-            {
-                byte[] buffer = new byte[Server.BufferSize];
-                int numBytes = readStream.Read(buffer, 0, buffer.Length);
-                outBytes.Add(new Tuple<byte[], int>(buffer, numBytes));
-                Server.Log("\tRead {0} bytes from {1}", numBytes, readStreamName);
-            }
-
-            // Ensure copying isn't paused
-            Server.PermitCopying.Wait();
-
-            // Delay for latency
-            if (simulateDelay)
-            {
-                Server.Log("\tSleeping for {0}", Server.SimulatedNetworkDelay);
-                Thread.Sleep(Server.SimulatedNetworkDelay);
-            }
-
-            // Write all data to writeStream
-            foreach (var b in outBytes)
-            {
-                writeStream.Write(b.Item1, 0, b.Item2);
-                Server.Log("\tWrote {0} bytes to {1}", b.Item2, writeStreamName);
-
-                // Ensure copying isn't paused
-                Server.PermitCopying.Wait();
-
-                // Delay for bandwidth
-                if (simulateDelay)
-                {
-                    Server.Log("\tSleeping for {0}", Server.SimulatedPacketDelay);
-                    Thread.Sleep(Server.SimulatedPacketDelay);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Kills this connection
-        /// </summary>
-        /// <param name="softKill">If true will perform a shutdown before closing, otherwise close will happen with lingering disabled</param>
-        public void Kill(bool softKill)
-        {
-            if (softKill)
-            {
-                // Soft close, do shutdown first
-                IncomingConnection.Shutdown(SocketShutdown.Both);
-            }
-            else
-            {
-                // Hard close - force no lingering
-                IncomingConnection.LingerState = new LingerOption(true, 0);
-            }
-
-            IncomingConnection.Dispose();
-            OutgoingConnection.Dispose();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/SystemDataResourceManager.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/SystemDataResourceManager.cs
deleted file mode 100644 (file)
index 471dbaa..0000000
+++ /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.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// Allows user to get resource messages from system.data.sqlclient.dll using dynamic properties/methods.
-    /// Refer to comments inside AssemblyResourceManager.cs for more details.
-    /// </summary>
-    public class SystemDataResourceManager : AssemblyResourceManager
-    {
-        private static SystemDataResourceManager s_instance = new SystemDataResourceManager();
-        public static dynamic Instance
-        {
-            get
-            {
-                return s_instance;
-            }
-        }
-        private SystemDataResourceManager() : base(typeof(System.Data.SqlClient.SqlConnection).GetTypeInfo().Assembly)
-        {
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.bsl b/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.bsl
deleted file mode 100644 (file)
index 99bde8b..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-MultipleErrorHandling SqlConnection
-**** ExecuteNonQuery *****
-SqlException: Error 1
-Error 2
-Error 3
-Error 4
-Error 5
-0
-1
-3
-4
-5
-6
-7
-8
-9
-10
-11
-**** ExecuteScalar ****
-*** SQL CONNECTION INFO MESSAGE : 0 ****
-**** ExecuteReader ****
-*** SQL CONNECTION INFO MESSAGE : 0 ****
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 1 ****
-SqlException: Error 1
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 3 ****
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 4 ****
-SqlException: Error 2
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 5 ****
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 6 ****
-SqlException: Error 3
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 7 ****
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 8 ****
-SqlException: Error 4
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 9 ****
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 10 ****
-SqlException: Error 5
-NextResult
-*** SQL CONNECTION INFO MESSAGE : 11 ****
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.cs
deleted file mode 100644 (file)
index bb4e2b3..0000000
+++ /dev/null
@@ -1,365 +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.Data.Common;
-using System.Diagnostics;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Text;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class MultipleResultsTest
-    {
-        private StringBuilder _globalBuilder = new StringBuilder();
-        private StringBuilder _outputBuilder;
-        private string[] _outputFilter;
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestMain()
-        {
-            Assert.True(RunTestCoreAndCompareWithBaseline());
-        }
-
-        private void RunTest()
-        {
-            MultipleErrorHandling(new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString));
-        }
-
-        private void MultipleErrorHandling(DbConnection connection)
-        {
-            try
-            {
-                Console.WriteLine("MultipleErrorHandling {0}", connection.GetType().Name);
-                Type expectedException = null;
-                if (connection is SqlConnection)
-                {
-                    ((SqlConnection)connection).InfoMessage += delegate (object sender, SqlInfoMessageEventArgs args)
-                    {
-                        Console.WriteLine("*** SQL CONNECTION INFO MESSAGE : {0} ****", args.Message);
-                    };
-                    expectedException = typeof(SqlException);
-                }
-                connection.Open();
-
-                using (DbCommand command = connection.CreateCommand())
-                {
-                    command.CommandText =
-                        "PRINT N'0';\n" +
-                        "SELECT num = 1, str = 'ABC';\n" +
-                        "PRINT N'1';\n" +
-                        "RAISERROR('Error 1', 15, 1);\n" +
-                        "PRINT N'3';\n" +
-                        "SELECT num = 2, str = 'ABC';\n" +
-                        "PRINT N'4';\n" +
-                        "RAISERROR('Error 2', 15, 1);\n" +
-                        "PRINT N'5';\n" +
-                        "SELECT num = 3, str = 'ABC';\n" +
-                        "PRINT N'6';\n" +
-                        "RAISERROR('Error 3', 15, 1);\n" +
-                        "PRINT N'7';\n" +
-                        "SELECT num = 4, str = 'ABC';\n" +
-                        "PRINT N'8';\n" +
-                        "RAISERROR('Error 4', 15, 1);\n" +
-                        "PRINT N'9';\n" +
-                        "SELECT num = 5, str = 'ABC';\n" +
-                        "PRINT N'10';\n" +
-                        "RAISERROR('Error 5', 15, 1);\n" +
-                        "PRINT N'11';\n";
-
-                    try
-                    {
-                        Console.WriteLine("**** ExecuteNonQuery *****");
-                        command.ExecuteNonQuery();
-                    }
-                    catch (Exception e)
-                    {
-                        PrintException(expectedException, e);
-                    }
-
-                    try
-                    {
-                        Console.WriteLine("**** ExecuteScalar ****");
-                        command.ExecuteScalar();
-                    }
-                    catch (Exception e)
-                    {
-                        PrintException(expectedException, e);
-                    }
-
-                    try
-                    {
-                        Console.WriteLine("**** ExecuteReader ****");
-                        using (DbDataReader reader = command.ExecuteReader())
-                        {
-                            bool moreResults = true;
-                            do
-                            {
-                                try
-                                {
-                                    Console.WriteLine("NextResult");
-                                    moreResults = reader.NextResult();
-                                }
-                                catch (Exception e)
-                                {
-                                    PrintException(expectedException, e);
-                                }
-                            } while (moreResults);
-                        }
-                    }
-                    catch (Exception e)
-                    {
-                        PrintException(null, e);
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                PrintException(null, e);
-            }
-            try
-            {
-                connection.Dispose();
-            }
-            catch (Exception e)
-            {
-                PrintException(null, e);
-            }
-        }
-
-        private bool RunTestCoreAndCompareWithBaseline()
-        {
-            string outputPath = "MultipleResultsTest.out";
-            string baselinePath = "MultipleResultsTest.bsl";
-
-            var fstream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
-            var swriter = new StreamWriter(fstream, Encoding.UTF8);
-            // Convert all string writes of '\n' to '\r\n' so output files can be 'text' not 'binary'
-            var twriter = new CarriageReturnLineFeedReplacer(swriter);
-            Console.SetOut(twriter); // "redirect" Console.Out
-
-            // Run Test
-            RunTest();
-
-            Console.Out.Flush();
-            Console.Out.Dispose();
-
-            // Recover the standard output stream
-            StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
-            standardOutput.AutoFlush = true;
-            Console.SetOut(standardOutput);
-
-            // Compare output file
-            var comparisonResult = FindDiffFromBaseline(baselinePath, outputPath);
-
-            if (string.IsNullOrEmpty(comparisonResult))
-            {
-                return true;
-            }
-
-            Console.WriteLine("Test Failed!");
-            Console.WriteLine("Please compare baseline : {0} with output :{1}", Path.GetFullPath(baselinePath), Path.GetFullPath(outputPath));
-            Console.WriteLine("Comparison Results : ");
-            Console.WriteLine(comparisonResult);
-            return false;
-        }
-
-        private void PrintException(Type expected, Exception e, params string[] values)
-        {
-            try
-            {
-                Debug.Assert(null != e, "PrintException: null exception");
-
-                _globalBuilder.Length = 0;
-                _globalBuilder.Append(e.GetType().Name).Append(": ");
-
-                if (e is COMException)
-                {
-                    _globalBuilder.Append("0x").Append((((COMException)e).HResult).ToString("X8"));
-                    if (expected != e.GetType())
-                    {
-                        _globalBuilder.Append(": ").Append(e.ToString());
-                    }
-                }
-                else
-                {
-                    _globalBuilder.Append(e.Message);
-                }
-                AssemblyFilter(_globalBuilder);
-                Console.WriteLine(_globalBuilder.ToString());
-
-                if (expected != e.GetType())
-                {
-                    Console.WriteLine(e.StackTrace);
-                }
-                if (null != values)
-                {
-                    foreach (string value in values)
-                    {
-                        Console.WriteLine(value);
-                    }
-                }
-                if (null != e.InnerException)
-                {
-                    PrintException(e.InnerException.GetType(), e.InnerException);
-                }
-                Console.Out.Flush();
-            }
-            catch (Exception f)
-            {
-                Console.WriteLine(f);
-            }
-        }
-
-        private string FindDiffFromBaseline(string baselinePath, string outputPath)
-        {
-            var expectedLines = File.ReadAllLines(baselinePath);
-            var outputLines = File.ReadAllLines(outputPath);
-
-            var comparisonSb = new StringBuilder();
-
-            // Start compare results
-            var expectedLength = expectedLines.Length;
-            var outputLength = outputLines.Length;
-            var findDiffLength = Math.Min(expectedLength, outputLength);
-
-            // Find diff for each lines
-            for (var lineNo = 0; lineNo < findDiffLength; lineNo++)
-            {
-                if (!expectedLines[lineNo].Equals(outputLines[lineNo]))
-                {
-                    comparisonSb.AppendFormat("** DIFF at line {0} \n", lineNo);
-                    comparisonSb.AppendFormat("A : {0} \n", outputLines[lineNo]);
-                    comparisonSb.AppendFormat("E : {0} \n", expectedLines[lineNo]);
-                }
-            }
-
-            var startIndex = findDiffLength - 1;
-            if (startIndex < 0) startIndex = 0;
-
-            if (findDiffLength < expectedLength)
-            {
-                comparisonSb.AppendFormat("** MISSING \n");
-                for (var lineNo = startIndex; lineNo < expectedLength; lineNo++)
-                {
-                    comparisonSb.AppendFormat("{0} : {1}", lineNo, expectedLines[lineNo]);
-                }
-            }
-            if (findDiffLength < outputLength)
-            {
-                comparisonSb.AppendFormat("** EXTRA \n");
-                for (var lineNo = startIndex; lineNo < outputLength; lineNo++)
-                {
-                    comparisonSb.AppendFormat("{0} : {1}", lineNo, outputLines[lineNo]);
-                }
-            }
-
-            return comparisonSb.ToString();
-        }
-
-        private string AssemblyFilter(StreamWriter writer)
-        {
-            if (null == _outputBuilder)
-            {
-                _outputBuilder = new StringBuilder();
-            }
-            _outputBuilder.Length = 0;
-
-            byte[] utf8 = ((MemoryStream)writer.BaseStream).ToArray();
-            string value = System.Text.Encoding.UTF8.GetString(utf8, 3, utf8.Length - 3); // skip 0xEF, 0xBB, 0xBF
-            _outputBuilder.Append(value);
-            AssemblyFilter(_outputBuilder);
-            return _outputBuilder.ToString();
-        }
-
-        private void AssemblyFilter(StringBuilder builder)
-        {
-            string[] filter = _outputFilter;
-            if (null == filter)
-            {
-                filter = new string[5];
-                string tmp = typeof(System.Guid).AssemblyQualifiedName;
-                filter[0] = tmp.Substring(tmp.IndexOf(','));
-                filter[1] = filter[0].Replace("mscorlib", "System");
-                filter[2] = filter[0].Replace("mscorlib", "System.Data");
-                filter[3] = filter[0].Replace("mscorlib", "System.Data.OracleClient");
-                filter[4] = filter[0].Replace("mscorlib", "System.Xml");
-                _outputFilter = filter;
-            }
-
-            for (int i = 0; i < filter.Length; ++i)
-            {
-                builder.Replace(filter[i], "");
-            }
-        }
-
-        /// <summary>
-        ///  special wrapper for the text writer to replace single "\n" with "\n"
-        /// </summary>
-        private sealed class CarriageReturnLineFeedReplacer : TextWriter
-        {
-            private TextWriter _output;
-            private int _lineFeedCount;
-            private bool _hasCarriageReturn;
-
-            internal CarriageReturnLineFeedReplacer(TextWriter output)
-            {
-                if (output == null)
-                    throw new ArgumentNullException(nameof(output));
-
-                _output = output;
-            }
-
-            public int LineFeedCount
-            {
-                get { return _lineFeedCount; }
-            }
-
-            public override Encoding Encoding
-            {
-                get { return _output.Encoding; }
-            }
-
-            public override IFormatProvider FormatProvider
-            {
-                get { return _output.FormatProvider; }
-            }
-
-            public override string NewLine
-            {
-                get { return _output.NewLine; }
-                set { _output.NewLine = value; }
-            }
-
-            protected override void Dispose(bool disposing)
-            {
-                if (disposing)
-                {
-                    ((IDisposable)_output).Dispose();
-                }
-                _output = null;
-            }
-
-            public override void Flush()
-            {
-                _output.Flush();
-            }
-
-            public override void Write(char value)
-            {
-                if ('\n' == value)
-                {
-                    _lineFeedCount++;
-                    if (!_hasCarriageReturn)
-                    {   // X'\n'Y -> X'\r\n'Y
-                        _output.Write('\r');
-                    }
-                }
-                _hasCarriageReturn = '\r' == value;
-                _output.Write(value);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ConcurrentLoadContext.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ConcurrentLoadContext.cs
deleted file mode 100644 (file)
index d80c085..0000000
+++ /dev/null
@@ -1,308 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Data.Common;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class ConcurrentLoadContext
-    {
-        public enum Mode
-        {
-            Sync,
-            Async,
-        }
-
-        public sealed class Category
-        {
-            public int Id;
-            public string Description;
-        }
-
-        private readonly DbProviderFactory _providerFactory;
-        private readonly string _connectionString;
-        private readonly string _query;
-        private readonly int _warmupSeconds;
-        private readonly int _executionSeconds;
-        private readonly Mode _mode;
-
-        private Func<Task> _start;
-        private Func<Task> _stop;
-        private Func<Task> _work;
-
-        private int _counter;
-        private int _totalTransactions;
-        private int _threadCount;
-        private int _running;
-        private List<int> _results;
-        private DateTime _startTime;
-        private DateTime _stopTime;
-
-        public ConcurrentLoadContext(DbProviderFactory providerFactory, string connectionString, Mode mode, int warmupSeconds, int executionSeconds, int threadCount)
-        {
-            _providerFactory = providerFactory;
-            _connectionString = connectionString;
-            _threadCount = threadCount;
-            _warmupSeconds = warmupSeconds;
-            _executionSeconds = executionSeconds;
-            _query = "SELECT CategoryID, Description FROM Categories";
-            _results = new List<int>(_executionSeconds);
-            _mode = mode;
-            _start = Start;
-            _stop = Stop;
-            switch (_mode)
-            {
-                case Mode.Sync:
-                    _work = DoWorkSync;
-                    break;
-                case Mode.Async:
-                    _work = DoWorkAsync;
-                    break;
-                default:
-                    throw new ArgumentOutOfRangeException(nameof(mode));
-            }
-        }
-
-        public void IncrementCounter() => Interlocked.Increment(ref _counter);
-
-        public bool IsRunning
-        {
-            get => _running == 1;
-            set => Interlocked.Exchange(ref _running, value ? 1 : 0);
-        }
-
-        public Task DoWorkSync()
-        {
-            while (IsRunning)
-            {
-                var results = new List<Category>();
-
-                using (var connection = _providerFactory.CreateConnection())
-                {
-                    connection.ConnectionString = _connectionString;
-                    connection.Open();
-
-                    using (var command = connection.CreateCommand())
-                    {
-                        command.CommandText = _query;
-                        command.Prepare();
-
-                        using (var reader = command.ExecuteReader())
-                        {
-                            while (reader.Read())
-                            {
-                                results.Add(
-                                    new Category
-                                    {
-                                        Id = reader.GetInt32(0),
-                                        Description = reader.GetString(1)
-                                    });
-                            }
-                        }
-                    }
-                }
-
-                CheckResults(results);
-
-                IncrementCounter();
-            }
-
-            return Task.CompletedTask;
-        }
-
-        public Task DoWorkSyncCaching()
-        {
-            using (var connection = _providerFactory.CreateConnection())
-            {
-                connection.ConnectionString = _connectionString;
-                connection.Open();
-
-                using (var command = connection.CreateCommand())
-                {
-                    command.CommandText = _query;
-                    command.Prepare();
-
-                    while (IsRunning)
-                    {
-                        var results = new List<Category>();
-
-                        using (var reader = command.ExecuteReader())
-                        {
-                            while (reader.Read())
-                            {
-                                results.Add(
-                                    new Category
-                                    {
-                                        Id = reader.GetInt32(0),
-                                        Description = reader.GetString(1)
-                                    });
-                            }
-                        }
-
-                        CheckResults(results);
-
-                        IncrementCounter();
-                    }
-                }
-            }
-
-            return Task.CompletedTask;
-        }
-
-        public async Task DoWorkAsync()
-        {
-            while (IsRunning)
-            {
-                var results = new List<Category>();
-
-                using (var connection = _providerFactory.CreateConnection())
-                {
-                    connection.ConnectionString = _connectionString;
-
-                    await connection.OpenAsync();
-
-                    using (var command = connection.CreateCommand())
-                    {
-                        command.CommandText = _query;
-                        command.Prepare();
-
-                        using (var reader = await command.ExecuteReaderAsync())
-                        {
-                            while (await reader.ReadAsync())
-                            {
-                                results.Add(
-                                    new Category
-                                    {
-                                        Id = reader.GetInt32(0),
-                                        Description = reader.GetString(1)
-                                    });
-                            }
-                        }
-                    }
-                }
-
-                CheckResults(results);
-
-                IncrementCounter();
-            }
-        }
-
-        public async Task DoWorkAsyncCaching()
-        {
-            using (var connection = _providerFactory.CreateConnection())
-            {
-                connection.ConnectionString = _connectionString;
-
-                await connection.OpenAsync();
-
-                using (var command = connection.CreateCommand())
-                {
-                    command.CommandText = _query;
-                    command.Prepare();
-
-                    while (IsRunning)
-                    {
-                        var results = new List<Category>();
-
-                        using (var reader = await command.ExecuteReaderAsync())
-                        {
-                            while (await reader.ReadAsync())
-                            {
-                                results.Add(
-                                    new Category
-                                    {
-                                        Id = reader.GetInt32(0),
-                                        Description = reader.GetString(1)
-                                    });
-                            }
-                        }
-
-                        CheckResults(results);
-
-                        IncrementCounter();
-                    }
-                }
-            }
-        }
-
-        public async Task<(int transactionPerSecond, double average, double stdDeviation)> Run()
-        {
-            IsRunning = true;
-
-            await Task.WhenAll(CreateTasks());
-
-            _results.Sort();
-            _results.RemoveAt(0);
-            _results.RemoveAt(_results.Count - 1);
-
-            (double avg, double stdDev) = CalculateStdDev(_results);
-
-            int totalTps = (int)(_totalTransactions / (_stopTime - _startTime).TotalSeconds);
-
-            return (totalTps, avg, stdDev);
-        }
-
-        private async Task Start()
-        {
-            await Task.Delay(TimeSpan.FromSeconds(_warmupSeconds));
-
-            Interlocked.Exchange(ref _counter, 0);
-
-            _startTime = DateTime.UtcNow;
-            var lastDisplay = _startTime;
-
-            while (IsRunning)
-            {
-                await Task.Delay(200);
-
-                DateTime now = DateTime.UtcNow;
-                int tps = (int)(_counter / (now - lastDisplay).TotalSeconds);
-
-                _results.Add(tps);
-
-                lastDisplay = now;
-                _totalTransactions += Interlocked.Exchange(ref _counter, 0);
-            }
-        }
-
-        private async Task Stop()
-        {
-            await Task.Delay(TimeSpan.FromSeconds(_warmupSeconds + _executionSeconds));
-            Interlocked.Exchange(ref _running, 0);
-            _stopTime = DateTime.UtcNow;
-        }
-
-        private IEnumerable<Task> CreateTasks()
-        {
-            yield return Task.Run(_start);
-
-            yield return Task.Run(_stop);
-
-            foreach (var task in Enumerable.Range(0, _threadCount)
-                .Select(_ => Task.Factory.StartNew(_work, TaskCreationOptions.LongRunning).Unwrap()))
-            {
-                yield return task;
-            }
-        }
-
-        private static void CheckResults(ICollection<Category> results)
-        {
-            Assert.NotNull(results);
-            Assert.Equal(8, results.Count);
-        }
-
-        private static (double, double) CalculateStdDev(ICollection<int> values)
-        {
-            double avg = values.Average();
-            double sum = values.Sum(d => Math.Pow(d - avg, 2));
-
-            return (avg, Math.Sqrt(sum / values.Count));
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ReaderTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ReaderTest.cs
deleted file mode 100644 (file)
index e21df22..0000000
+++ /dev/null
@@ -1,305 +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.Data.Common;
-using System.IO;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ReaderTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestMain()
-        {
-            string connectionString = DataTestUtility.TcpConnStr;
-
-            string tempTable = DataTestUtility.GetUniqueName("T", "[", "]");
-            string tempKey = DataTestUtility.GetUniqueName("K", "[", "]");
-
-            DbProviderFactory provider = SqlClientFactory.Instance;
-            try
-            {
-                using (DbConnection con = provider.CreateConnection())
-                {
-                    con.ConnectionString = connectionString;
-                    con.Open();
-
-                    using (DbCommand cmd = provider.CreateCommand())
-                    {
-                        cmd.Connection = con;
-                        DbTransaction tx;
-
-                        #region <<Create temp table>>
-                        cmd.CommandText = "SELECT LastName, FirstName, Title, Address, City, Region, PostalCode, Country into " + tempTable + " from Employees where EmployeeID=0";
-                        cmd.ExecuteNonQuery();
-
-                        #endregion
-
-                        tx = con.BeginTransaction();
-                        cmd.Transaction = tx;
-
-                        cmd.CommandText = "insert into " + tempTable + "(LastName, FirstName, Title, Address, City, Region, PostalCode, Country) values ('Doe', 'Jane' , 'Ms.', 'One Microsoft Way', 'Redmond', 'WA', '98052', 'USA')";
-                        cmd.ExecuteNonQuery();
-                        cmd.CommandText = "insert into " + tempTable + "(LastName, FirstName, Title, Address, City, Region, PostalCode, Country) values ('Doe', 'John' , 'Mr.', NULL, NULL, NULL, NULL, NULL)";
-                        cmd.ExecuteNonQuery();
-
-                        tx.Commit();
-
-                        cmd.Transaction = null;
-                        string parameterName = "@p1";
-                        DbParameter p1 = cmd.CreateParameter();
-                        p1.ParameterName = parameterName;
-                        p1.Value = "Doe";
-                        cmd.Parameters.Add(p1);
-
-                        cmd.CommandText = "select * from " + tempTable + " where LastName = " + parameterName;
-
-                        // Test GetValue + IsDBNull
-                        using (DbDataReader rdr = cmd.ExecuteReader())
-                        {
-                            StringBuilder actualResult = new StringBuilder();
-                            int currentValue = 0;
-                            string[] expectedValues =
-                            {
-                                "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA",
-                                "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)"
-                            };
-
-                            while (rdr.Read())
-                            {
-                                Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected");
-
-                                for (int i = 0; i < rdr.FieldCount; i++)
-                                {
-                                    if (i > 0)
-                                    {
-                                        actualResult.Append(",");
-                                    }
-                                    if (rdr.IsDBNull(i))
-                                    {
-                                        actualResult.Append("(NULL)");
-                                    }
-                                    else
-                                    {
-                                        actualResult.Append(rdr.GetValue(i));
-                                    }
-                                }
-
-                                DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data");
-                                actualResult.Clear();
-                            }
-                        }
-
-                        // Test GetFieldValue<T> + IsDBNull
-                        using (DbDataReader rdr = cmd.ExecuteReader())
-                        {
-                            StringBuilder actualResult = new StringBuilder();
-                            int currentValue = 0;
-                            string[] expectedValues =
-                            {
-                                "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA",
-                                "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)"
-                            };
-
-                            while (rdr.Read())
-                            {
-                                Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected");
-
-                                for (int i = 0; i < rdr.FieldCount; i++)
-                                {
-                                    if (i > 0)
-                                    {
-                                        actualResult.Append(",");
-                                    }
-                                    if (rdr.IsDBNull(i))
-                                    {
-                                        actualResult.Append("(NULL)");
-                                    }
-                                    else
-                                    {
-                                        if (rdr.GetFieldType(i) == typeof(bool))
-                                        {
-                                            actualResult.Append(rdr.GetFieldValue<bool>(i));
-                                        }
-                                        else if (rdr.GetFieldType(i) == typeof(decimal))
-                                        {
-                                            actualResult.Append(rdr.GetFieldValue<decimal>(i));
-                                        }
-                                        else if (rdr.GetFieldType(i) == typeof(int))
-                                        {
-                                            actualResult.Append(rdr.GetFieldValue<int>(i));
-                                        }
-                                        else
-                                        {
-                                            actualResult.Append(rdr.GetFieldValue<string>(i));
-                                        }
-                                    }
-                                }
-
-                                DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data");
-                                actualResult.Clear();
-                            }
-                        }
-
-                        // Test GetFieldValueAsync<T> + IsDBNullAsync
-                        using (DbDataReader rdr = cmd.ExecuteReaderAsync().Result)
-                        {
-                            StringBuilder actualResult = new StringBuilder();
-                            int currentValue = 0;
-                            string[] expectedValues =
-                            {
-                                "Doe,Jane,Ms.,One Microsoft Way,Redmond,WA,98052,USA",
-                                "Doe,John,Mr.,(NULL),(NULL),(NULL),(NULL),(NULL)"
-                            };
-
-                            while (rdr.ReadAsync().Result)
-                            {
-                                Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected");
-
-                                for (int i = 0; i < rdr.FieldCount; i++)
-                                {
-                                    if (i > 0)
-                                    {
-                                        actualResult.Append(",");
-                                    }
-                                    if (rdr.IsDBNullAsync(i).Result)
-                                    {
-                                        actualResult.Append("(NULL)");
-                                    }
-                                    else
-                                    {
-                                        if (rdr.GetFieldType(i) == typeof(bool))
-                                        {
-                                            actualResult.Append(rdr.GetFieldValueAsync<bool>(i).Result);
-                                        }
-                                        else if (rdr.GetFieldType(i) == typeof(decimal))
-                                        {
-                                            actualResult.Append(rdr.GetFieldValueAsync<decimal>(i).Result);
-                                        }
-                                        else if (rdr.GetFieldType(i) == typeof(int))
-                                        {
-                                            actualResult.Append(rdr.GetFieldValue<int>(i));
-                                        }
-                                        else
-                                        {
-                                            actualResult.Append(rdr.GetFieldValueAsync<string>(i).Result);
-                                        }
-                                    }
-                                }
-
-                                DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data");
-                                actualResult.Clear();
-                            }
-                        }
-                    }
-
-                    // GetStream
-                    byte[] correctBytes = { 0x12, 0x34, 0x56, 0x78 };
-                    string queryString;
-                    string correctBytesAsString = "0x12345678";
-                    queryString = string.Format("SELECT CAST({0} AS BINARY(20)), CAST({0} AS IMAGE), CAST({0} AS VARBINARY(20))", correctBytesAsString);
-                    using (var command = provider.CreateCommand())
-                    {
-                        command.CommandText = queryString;
-                        command.Connection = con;
-                        using (var reader = command.ExecuteReader())
-                        {
-                            reader.Read();
-                            for (int i = 0; i < reader.FieldCount; i++)
-                            {
-                                byte[] buffer = new byte[256];
-                                Stream stream = reader.GetStream(i);
-                                int bytesRead = stream.Read(buffer, 0, buffer.Length);
-                                for (int j = 0; j < correctBytes.Length; j++)
-                                {
-                                    Assert.True(correctBytes[j] == buffer[j], "ERROR: Bytes do not match");
-                                }
-                            }
-                        }
-                    }
-
-                    // GetTextReader
-                    string[] correctStrings = { "Hello World", "\uFF8A\uFF9B\uFF70\uFF9C\uFF70\uFF99\uFF84\uFF9E" };
-                    string[] collations = { "Latin1_General_CI_AS", "Japanese_CI_AS" };
-
-                    for (int j = 0; j < collations.Length; j++)
-                    {
-                        string substring = string.Format("(N'{0}' COLLATE {1})", correctStrings[j], collations[j]);
-                        queryString = string.Format("SELECT CAST({0} AS CHAR(20)), CAST({0} AS NCHAR(20)), CAST({0} AS NTEXT), CAST({0} AS NVARCHAR(20)), CAST({0} AS TEXT), CAST({0} AS VARCHAR(20))", substring);
-                        using (var command = provider.CreateCommand())
-                        {
-                            command.CommandText = queryString;
-                            command.Connection = con;
-                            using (var reader = command.ExecuteReader())
-                            {
-                                reader.Read();
-                                for (int i = 0; i < reader.FieldCount; i++)
-                                {
-                                    char[] buffer = new char[256];
-                                    TextReader textReader = reader.GetTextReader(i);
-                                    int charsRead = textReader.Read(buffer, 0, buffer.Length);
-                                    string stringRead = new string(buffer, 0, charsRead);
-
-                                    Assert.True(stringRead == (string)reader.GetValue(i), "ERROR: Strings to not match");
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                using (DbConnection con = provider.CreateConnection())
-                {
-                    con.ConnectionString = connectionString;
-                    con.Open();
-
-                    using (DbCommand cmd = provider.CreateCommand())
-                    {
-                        cmd.Connection = con;
-                        cmd.CommandText = "drop table " + tempTable;
-                        cmd.ExecuteNonQuery();
-                    }
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public static async Task TestConcurrentLoadSync()
-        {
-            ConcurrentLoadContext context = new ConcurrentLoadContext(
-                providerFactory: SqlClientFactory.Instance,
-                connectionString: DataTestUtility.TcpConnStr,
-                mode: ConcurrentLoadContext.Mode.Sync,
-                warmupSeconds: 1,
-                executionSeconds: 60,
-                threadCount: Environment.ProcessorCount * 4
-            );
-            var (transactionPerSecond, average, stdDeviation) = await context.Run();
-            Assert.InRange(transactionPerSecond, 1, int.MaxValue);
-            Assert.True(average > 0);
-            Assert.True(stdDeviation != 0);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public static async Task TestConcurrentLoadAsync()
-        {
-            ConcurrentLoadContext context = new ConcurrentLoadContext(
-                providerFactory: SqlClientFactory.Instance,
-                connectionString: DataTestUtility.TcpConnStr,
-                mode: ConcurrentLoadContext.Mode.Async,
-                warmupSeconds: 1,
-                executionSeconds: 60,
-                threadCount: Environment.ProcessorCount * 4
-            );
-            var (transactionPerSecond, average, stdDeviation) = await context.Run();
-            Assert.InRange(transactionPerSecond, 1, int.MaxValue);
-            Assert.True(average > 0);
-            Assert.True(stdDeviation != 0);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/README.md b/src/libraries/System.Data.SqlClient/tests/ManualTests/README.md
deleted file mode 100644 (file)
index a61572b..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-# SqlClient Manual Tests
-
-These tests require dedicated test servers, so they're designed to be run manually using a custom set of connection strings. 
-
-## Prerequisites
-
-- Libraries building. You need to be able to do a successful [build](https://github.com/dotnet/runtime/tree/master/docs/workflow/building/libraries) and [run the standard tests](https://github.com/dotnet/runtime/blob/master/docs/workflow/testing/libraries/testing.md).
-
-  **N.B.** if you want to run the EFCore tests later you will need to build -allconfigurations to generate the NuGet packages, build -allconfigurations works only on windows.
-
-- an [MS SQL Server](https://www.microsoft.com/en-us/sql-server/sql-server-editions-express) (any edition) 2012 or later that you can connect to with tcp and named pipes, 
-
-  **N.B**. if you want to run the EFCore tests it should be a dedicated instance because they create a lot of databases.
-
-- The  [Northwind Sample Database](https://msdn.microsoft.com/en-us/library/mt710790.aspx)
-
-- The [UDT Test Database](https://github.com/dotnet/runtime/tree/master/src/libraries/System.Data.SqlClient/tests/ManualTests/createUdtTestDb_corefx.sql) 
-
-- TCP and Named Pipe [connection strings](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx) to your instance with Northwind set as the initial catalog
-
-
-
-## Running All Tests
-
-1. set the environment variables needed for the tests you want. At the minimum you need to set
-    `TEST_NP_CONN_STR` and `TEST_TCP_CONN_STR` to the connection strings. 
-
-2. Optionally you may also want to setup other environment variables to test specific optional features such as [TEST_LOCALDB_INSTALLED](https://github.com/dotnet/runtime/blob/be980b71efadc622b5720a36867696758e59e71c/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs#L123) or [TEST_INTEGRATEDSECURITY_SETUP](https://github.com/dotnet/runtime/blob/be980b71efadc622b5720a36867696758e59e71c/src/libraries/System.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs#L125). Other scenarios lke azure tests may need configuration so if you see those being skipped and you want to run them invesigate the skipped test code to identify how to configure it.
-
-3. run `dotnet msbuild .\src\System.Data.SqlClient\tests\ManualTests\System.Data.SqlClient.ManualTesting.Tests.csproj /t:Rebuild` to build the debug version with all the assertions and run the tests.
-
-4. If you need to re-run the test suite without having changed the build (e.g. if you've changed the exnvironment variables) you can use `dotnet msbuild .\src\System.Data.SqlClient\tests\ManualTests\System.Data.SqlClient.ManualTesting.Tests.csproj /t:Test`
-
-  ​    
-
-## Running A Specific Test
-
-Once you have all tests running you may need to debug a single failing test. To do this navigate into the manual tests project directory `cd src\System.Data.SqlClient\tests\ManualTests` then run dotnet msbuild and specify the name of the test you want to execute, like this:
- `dotnet msbuild /t:RebuildAndTest /p:XunitMethodName=System.Data.SqlClient.ManualTesting.Tests.DDDataTypesTest.MaxTypesTest`
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/RunTests.cmd b/src/libraries/System.Data.SqlClient/tests/ManualTests/RunTests.cmd
deleted file mode 100644 (file)
index 74f304f..0000000
+++ /dev/null
@@ -1,10 +0,0 @@
-@echo off
-IF "%1"=="/?" (
-ECHO Usage: "%0" [TestClass]
-) ELSE IF "%1"=="" (
-echo Running all tests.
-msbuild /t:BuildAndTest
-) ELSE (
-echo Running SqlClient test suite "%1".
-msbuild /t:BuildAndTest "/p:XunitOptions=-class System.Data.SqlClient.ManualTesting.Tests.%1"
-)
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs
deleted file mode 100644 (file)
index d76838a..0000000
+++ /dev/null
@@ -1,1811 +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.Data.SqlTypes;
-using System.Globalization;
-using System.Text;
-using System.Reflection;
-using System.Collections;
-using System.Collections.Generic;
-using System.Diagnostics;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class AdapterTest
-    {
-        private char[] _appendNewLineIndentBuffer = new char[0];
-
-        // data value and server consts
-        private const string MagicName = "Magic";
-        // Use a union statement so that Identity columns don't carry over
-        private const string _createTableQuery = "select * into {0} from Employees where EmployeeID < 3 union all (select * from Employees where 1 = 0)";
-        private string _tempTable;
-        private string _tempKey;
-
-        // data type
-        private decimal _c_numeric_val;
-        private long _c_bigint_val;
-        private byte[] _c_unique_val;
-        private Guid _c_guid_val;
-        private byte[] _c_varbinary_val;
-        private byte[] _c_binary_val;
-        private decimal _c_money_val;
-        private decimal _c_smallmoney_val;
-        private DateTime _c_datetime_val;
-        private DateTime _c_smalldatetime_val;
-        private string _c_nvarchar_val;
-        private string _c_nchar_val;
-        private string _c_varchar_val;
-        private string _c_char_val;
-        private int _c_int_val;
-        private short _c_smallint_val;
-        private byte _c_tinyint_val;
-        private bool _c_bit_val;
-        private double _c_float_val;
-        private float _c_real_val;
-
-        private object[] _values;
-
-        public AdapterTest()
-        {
-            // create random name for temp tables
-            _tempTable = Environment.MachineName + "_" + Guid.NewGuid().ToString();
-            _tempTable = _tempTable.Replace('-', '_');
-
-            _tempKey = "employee_id_key_" + Environment.TickCount.ToString() + Guid.NewGuid().ToString();
-            _tempKey = _tempKey.Replace('-', '_');
-
-            InitDataValues();
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void SimpleFillTest()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM Employees", conn))
-            {
-                DataSet employeesSet = new DataSet();
-                DataTestUtility.AssertEqualsWithDescription(0, employeesSet.Tables.Count, "Unexpected tables count before fill.");
-                adapter.Fill(employeesSet, "Employees");
-
-                DataTestUtility.AssertEqualsWithDescription(1, employeesSet.Tables.Count, "Unexpected tables count after fill.");
-                DataTestUtility.AssertEqualsWithDescription("Employees", employeesSet.Tables[0].TableName, "Unexpected table name.");
-
-                DataTestUtility.AssertEqualsWithDescription(9, employeesSet.Tables["Employees"].Columns.Count, "Unexpected columns count.");
-                employeesSet.Tables["Employees"].Columns.Remove("LastName");
-                employeesSet.Tables["Employees"].Columns.Remove("FirstName");
-                employeesSet.Tables["Employees"].Columns.Remove("Title");
-                DataTestUtility.AssertEqualsWithDescription(6, employeesSet.Tables["Employees"].Columns.Count, "Unexpected columns count after column removal.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void PrepUnprepTest()
-        {
-            // share the connection
-            using (SqlCommand cmd = new SqlCommand("select * from shippers", new SqlConnection(DataTestUtility.TcpConnStr)))
-            using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
-            {
-                cmd.Connection.Open();
-
-                DataSet dataSet = new DataSet();
-                sqlAdapter.TableMappings.Add("Table", "shippers");
-
-                cmd.CommandText = "Select * from shippers";
-                sqlAdapter.SelectCommand = cmd;
-                sqlAdapter.Fill(dataSet);
-
-                DataTestUtility.AssertEqualsWithDescription(
-                    3, dataSet.Tables[0].Rows.Count,
-                    "Exec1: Unexpected number of shipper rows.");
-
-                dataSet.Reset();
-                sqlAdapter.Fill(dataSet);
-
-                DataTestUtility.AssertEqualsWithDescription(
-                    3, dataSet.Tables[0].Rows.Count,
-                    "Exec2: Unexpected number of shipper rows.");
-
-                dataSet.Reset();
-                cmd.CommandText = "select * from shippers where shipperId < 3";
-                sqlAdapter.Fill(dataSet);
-
-                DataTestUtility.AssertEqualsWithDescription(
-                    2, dataSet.Tables[0].Rows.Count,
-                    "Exec3: Unexpected number of shipper rows.");
-
-                dataSet.Reset();
-
-                sqlAdapter.Fill(dataSet);
-                DataTestUtility.AssertEqualsWithDescription(
-                    2, dataSet.Tables[0].Rows.Count,
-                    "Exec4: Unexpected number of shipper rows.");
-
-                cmd.CommandText = "select * from shippers";
-                cmd.Prepare();
-
-                int i = 0;
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTestUtility.AssertEqualsWithDescription(3, reader.FieldCount, "Unexpected FieldCount.");
-
-                    while (reader.Read())
-                    {
-                        i++;
-                    }
-                }
-                DataTestUtility.AssertEqualsWithDescription(3, i, "Unexpected read count.");
-
-                cmd.CommandText = "select * from orders where orderid < @p1";
-                cmd.Parameters.AddWithValue("@p1", 10250);
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTestUtility.AssertEqualsWithDescription(14, reader.FieldCount, "Unexpected FieldCount.");
-
-                    i = 0;
-                    while (reader.Read())
-                    {
-                        i++;
-                    }
-                }
-                DataTestUtility.AssertEqualsWithDescription(2, i, "Unexpected read count.");
-
-                cmd.Parameters["@p1"].Value = 10249;
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTestUtility.AssertEqualsWithDescription(14, reader.FieldCount, "Unexpected FieldCount.");
-
-                    i = 0;
-                    while (reader.Read())
-                    {
-                        i++;
-                    }
-                }
-                DataTestUtility.AssertEqualsWithDescription(1, i, "Unexpected read count.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void SqlVariantTest()
-        {
-            try
-            {
-                ExecuteNonQueryCommand("CREATE TABLE shiloh_types (c0_bigint bigint, c1_variant sql_variant)");
-
-                // good test for null values and unicode strings
-                using (SqlCommand cmd = new SqlCommand(null, new SqlConnection(DataTestUtility.TcpConnStr)))
-                using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
-                {
-                    cmd.Connection.Open();
-
-                    // the ORDER BY clause tests that we correctly ignore the ORDER token
-                    cmd.CommandText = "select * from shiloh_types";
-                    sqlAdapter.SelectCommand = cmd;
-                    sqlAdapter.TableMappings.Add("Shiloh_Types", "rowset");
-
-                    // insert
-                    sqlAdapter.InsertCommand = new SqlCommand()
-                    {
-                        CommandText = "INSERT INTO Shiloh_Types(c0_bigint, c1_variant) " +
-                        "VALUES (@bigint, @variant)"
-                    };
-                    SqlParameter p = sqlAdapter.InsertCommand.Parameters.Add(new SqlParameter("@bigint", SqlDbType.BigInt));
-                    p.SourceColumn = "c0_bigint";
-                    p = sqlAdapter.InsertCommand.Parameters.Add(new SqlParameter("@variant", SqlDbType.Variant));
-                    p.SourceColumn = "c1_variant";
-                    sqlAdapter.InsertCommand.Connection = cmd.Connection;
-
-                    DataSet dataSet = new DataSet();
-                    sqlAdapter.FillSchema(dataSet, SchemaType.Mapped, "Shiloh_Types");
-
-                    DataRow datarow = null;
-                    for (int i = 0; i < _values.Length; i++)
-                    {
-                        // add each variant type
-                        datarow = dataSet.Tables[0].NewRow();
-                        datarow.ItemArray = new object[] { 1, _values[i] };
-                        datarow.Table.Rows.Add(datarow);
-                    }
-
-                    sqlAdapter.Update(dataSet, "Shiloh_Types");
-
-                    // now reload and make sure we got the values we wrote out
-                    dataSet.Reset();
-                    sqlAdapter.Fill(dataSet, "Shiloh_Types");
-
-                    DataColumnCollection cols = dataSet.Tables[0].Columns;
-                    DataRowCollection rows = dataSet.Tables[0].Rows;
-
-                    Assert.True(rows.Count == _values.Length, "FAILED:  SqlVariant didn't update all the rows!");
-
-                    for (int i = 0; i < rows.Count; i++)
-                    {
-                        DataRow row = rows[i];
-                        object value = row[1];
-
-                        if (_values[i].GetType() == typeof(byte[]) || _values[i].GetType() == typeof(Guid))
-                        {
-                            byte[] bsrc;
-                            byte[] bdst;
-
-                            if (_values[i].GetType() == typeof(Guid))
-                            {
-                                bsrc = ((Guid)value).ToByteArray();
-                                bdst = ((Guid)(_values[i])).ToByteArray();
-                            }
-                            else
-                            {
-                                bsrc = (byte[])value;
-                                bdst = (byte[])_values[i];
-                            }
-
-                            Assert.True(ByteArraysEqual(bsrc, bdst), "FAILED: Byte arrays are unequal");
-                        }
-                        else if (_values[i].GetType() == typeof(bool))
-                        {
-                            Assert.True(Convert.ToBoolean(value) == (bool)_values[i], "FAILED:  " + DBConvertToString(value) + " is not equal to " + DBConvertToString(_values[i]));
-                        }
-                        else
-                        {
-                            Assert.True(value.Equals(_values[i]), "FAILED:  " + DBConvertToString(value) + " is not equal to " + DBConvertToString(_values[i]));
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                ExecuteNonQueryCommand("DROP TABLE shiloh_types");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void ParameterTest_AllTypes()
-        {
-            string spCreateAllTypes =
-                "CREATE PROCEDURE sp_alltypes " +
-                "@Cnumeric numeric(10,2) OUTPUT, " +
-                "@Cunique uniqueidentifier OUTPUT, " +
-                "@Cnvarchar nvarchar(10) OUTPUT, " +
-                "@Cnchar nchar(10) OUTPUT, " +
-                "@Cbit bit OUTPUT, " +
-                "@Ctinyint tinyint OUTPUT, " +
-                "@Cvarbinary varbinary(16) OUTPUT, " +
-                "@Cbinary binary(16) OUTPUT, " +
-                "@Cchar char(10) OUTPUT, " +
-                "@Cmoney money OUTPUT, " +
-                "@Csmallmoney smallmoney OUTPUT, " +
-                "@Cint int OUTPUT, " +
-                "@Csmallint smallint OUTPUT, " +
-                "@Cfloat float OUTPUT, " +
-                "@Creal real OUTPUT, " +
-                "@Cdatetime datetime OUTPUT, " +
-                "@Csmalldatetime smalldatetime OUTPUT, " +
-                "@Cvarchar varchar(10) OUTPUT " +
-                "AS SELECT " +
-                "@Cnumeric=@Cnumeric, " +
-                "@Cunique=@Cunique, " +
-                "@Cnvarchar=@Cnvarchar, " +
-                "@Cnchar=@Cnchar, " +
-                "@Cbit=@Cbit, " +
-                "@Ctinyint=@Ctinyint, " +
-                "@Cvarbinary=@Cvarbinary, " +
-                "@Cbinary=@Cbinary, " +
-                "@Cchar=@Cchar, " +
-                "@Cmoney=@Cmoney, " +
-                "@Csmallmoney=@Csmallmoney, " +
-                "@Cint=@Cint, " +
-                "@Csmallint=@Csmallint, " +
-                "@Cfloat=@Cfloat, " +
-                "@Creal=@Creal, " +
-                "@Cdatetime=@Cdatetime, " +
-                "@Csmalldatetime=@Csmalldatetime, " +
-                "@Cvarchar=@Cvarchar " +
-                "RETURN(42)";
-
-            string spDropAllTypes = "DROP PROCEDURE sp_alltypes";
-            bool dropSP = false;
-
-            try
-            {
-                ExecuteNonQueryCommand(spCreateAllTypes);
-                dropSP = true;
-
-                using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (SqlCommand cmd = new SqlCommand("sp_allTypes", conn))
-                using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
-                {
-                    conn.Open();
-
-                    SqlParameter param = cmd.Parameters.Add(new SqlParameter("@Cnumeric", SqlDbType.Decimal));
-                    param.Precision = 10;
-                    param.Scale = 2;
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[0].Value = _c_numeric_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Cunique", SqlDbType.UniqueIdentifier));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[1].Value = _c_guid_val;
-
-                    cmd.Parameters.Add(new SqlParameter("@Cnvarchar", SqlDbType.NVarChar, 10));
-                    cmd.Parameters[2].Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[2].Value = _c_nvarchar_val;
-
-                    cmd.Parameters.Add(new SqlParameter("@Cnchar", SqlDbType.NChar, 10));
-                    cmd.Parameters[3].Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[3].Value = _c_nchar_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Cbit", SqlDbType.Bit));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[4].Value = _c_bit_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Ctinyint", SqlDbType.TinyInt));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[5].Value = _c_tinyint_val;
-
-                    cmd.Parameters.Add(new SqlParameter("@Cvarbinary", SqlDbType.VarBinary, 16));
-                    cmd.Parameters[6].Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[6].Value = _c_varbinary_val;
-
-                    cmd.Parameters.Add(new SqlParameter("@Cbinary", SqlDbType.Binary, 16));
-                    cmd.Parameters[7].Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[7].Value = _c_binary_val;
-
-                    cmd.Parameters.Add(new SqlParameter("@Cchar", SqlDbType.Char, 10));
-                    cmd.Parameters[8].Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[8].Value = _c_char_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Cmoney", SqlDbType.Money));
-                    param.Direction = ParameterDirection.InputOutput;
-                    param.Scale = 4;
-                    cmd.Parameters[9].Value = _c_money_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Csmallmoney", SqlDbType.SmallMoney));
-                    param.Direction = ParameterDirection.InputOutput;
-                    param.Scale = 4;
-                    cmd.Parameters[10].Value = _c_smallmoney_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Cint", SqlDbType.Int));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[11].Value = _c_int_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Csmallint", SqlDbType.SmallInt));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[12].Value = _c_smallint_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Cfloat", SqlDbType.Float));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[13].Value = _c_float_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Creal", SqlDbType.Real));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[14].Value = _c_real_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Cdatetime", SqlDbType.DateTime));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[15].Value = _c_datetime_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Csmalldatetime", SqlDbType.SmallDateTime));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[16].Value = _c_smalldatetime_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@Cvarchar", SqlDbType.VarChar, 10));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[17].Value = _c_varchar_val;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@return", SqlDbType.Int));
-                    param.Direction = ParameterDirection.ReturnValue;
-                    cmd.Parameters[18].Value = 17; // will be overwritten
-
-                    cmd.CommandType = CommandType.StoredProcedure;
-                    cmd.ExecuteNonQuery();
-
-                    string[] expectedStringValues =
-                    {
-                        "@Cnumeric : Decimal<42424242.42>",
-                        null,
-                        "@Cnvarchar : String:10<1234567890>",
-                        "@Cnchar : String:10<1234567890>",
-                        "@Cbit : Boolean<True>",
-                        "@Ctinyint : Byte<255>",
-                        null,
-                        null,
-                        "@Cchar : String:10<1234567890>",
-                        null,
-                        null,
-                        "@Cint : Int32<-1>",
-                        "@Csmallint : Int16<-1>",
-                        "@Cfloat : Double<12345678.2>",
-                        "@Creal : Single<12345.1>",
-                        null,
-                        null,
-                        "@Cvarchar : String:10<1234567890>",
-                        "@return : Int32<42>"
-                    };
-
-                    for (int i = 0; i < cmd.Parameters.Count; i++)
-                    {
-                        param = cmd.Parameters[i];
-                        switch (param.SqlDbType)
-                        {
-                            case SqlDbType.Binary:
-                                Assert.True(ByteArraysEqual(_c_binary_val, (byte[])param.Value), "FAILED: sp_alltypes, Binary parameter");
-                                break;
-                            case SqlDbType.VarBinary:
-                                Assert.True(ByteArraysEqual(_c_varbinary_val, (byte[])param.Value), "FAILED: sp_alltypes, VarBinary parameter");
-                                break;
-                            case SqlDbType.UniqueIdentifier:
-                                DataTestUtility.AssertEqualsWithDescription(_c_guid_val, (Guid)param.Value, "FAILED: sp_alltypes, UniqueIdentifier parameter");
-                                break;
-                            case SqlDbType.DateTime:
-                                Assert.True(0 == DateTime.Compare((DateTime)param.Value, _c_datetime_val), "FAILED: sp_alltypes, DateTime parameter");
-                                break;
-                            case SqlDbType.SmallDateTime:
-                                Assert.True(0 == DateTime.Compare((DateTime)param.Value, _c_smalldatetime_val), "FAILED: sp_alltypes, SmallDateTime parameter");
-                                break;
-                            case SqlDbType.Money:
-                                Assert.True(
-                                    0 == decimal.Compare((decimal)param.Value, _c_money_val),
-                                    string.Format("FAILED: sp_alltypes, Money parameter. Expected: {0}. Actual: {1}.", _c_money_val, (decimal)param.Value));
-                                break;
-                            case SqlDbType.SmallMoney:
-                                Assert.True(
-                                    0 == decimal.Compare((decimal)param.Value, _c_smallmoney_val),
-                                    string.Format("FAILED: sp_alltypes, SmallMoney parameter. Expected: {0}. Actual: {1}.", _c_smallmoney_val, (decimal)param.Value));
-                                break;
-                            default:
-                                string actualValue = param.ParameterName + " : " + DBConvertToString(cmd.Parameters[i].Value);
-                                DataTestUtility.AssertEqualsWithDescription(actualValue, expectedStringValues[i], "Unexpected parameter value.");
-                                break;
-                        }
-                    }
-                }
-            }
-            finally
-            {
-                if (dropSP)
-                {
-                    ExecuteNonQueryCommand(spDropAllTypes);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void ParameterTest_InOut()
-        {
-            // input, output
-            string spCreateInOut =
-                "CREATE PROCEDURE sp_test @in int, @inout int OUTPUT, @out nvarchar(8) OUTPUT " +
-                "AS SELECT @inout = (@in + @inout), @out = 'Success!' " +
-                "SELECT * From shippers where ShipperID = @in " +
-                "RETURN(42)";
-
-            string spDropInOut = "DROP PROCEDURE sp_test";
-            bool dropSP = false;
-
-            try
-            {
-                ExecuteNonQueryCommand(spCreateInOut);
-                dropSP = true;
-
-                using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (SqlCommand cmd = new SqlCommand("sp_test", conn))
-                using (SqlDataAdapter sqlAdapter = new SqlDataAdapter())
-                {
-                    conn.Open();
-
-                    cmd.CommandType = CommandType.StoredProcedure;
-                    cmd.Parameters.Add(new SqlParameter("@in", SqlDbType.Int));
-                    cmd.Parameters[0].Value = 2;
-
-                    SqlParameter param = cmd.Parameters.Add(new SqlParameter("@inout", SqlDbType.Int));
-                    param.Direction = ParameterDirection.InputOutput;
-                    cmd.Parameters[1].Value = 1998;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@out", SqlDbType.NVarChar, 8));
-                    param.Direction = ParameterDirection.Output;
-
-                    param = cmd.Parameters.Add(new SqlParameter("@ret", SqlDbType.Int));
-                    param.Direction = ParameterDirection.ReturnValue;
-
-                    DataSet dataSet = new DataSet();
-                    sqlAdapter.TableMappings.Add("Table", "shipper");
-                    sqlAdapter.SelectCommand = cmd;
-                    sqlAdapter.Fill(dataSet);
-
-                    // check our ouput and return value params
-                    Assert.True(VerifyOutputParams(cmd.Parameters), "FAILED: InputOutput parameter test with returned rows and bound return value!");
-
-                    Assert.True(1 == dataSet.Tables[0].Rows.Count, "FAILED:  Expected 1 row to be loaded in the dataSet!");
-
-                    DataRow row = dataSet.Tables[0].Rows[0];
-                    Assert.True((int)row["ShipperId"] == 2, "FAILED:  ShipperId column should be 2, not " + DBConvertToString(row["ShipperId"]));
-
-                    // remember to reset params
-                    cmd.Parameters[0].Value = 2;
-                    cmd.Parameters[1].Value = 1998;
-                    cmd.Parameters[2].Value = Convert.DBNull;
-                    cmd.Parameters[3].Value = Convert.DBNull;
-
-                    // now exec the same thing without a data set
-                    cmd.ExecuteNonQuery();
-
-                    // check our ouput and return value params
-                    Assert.True(VerifyOutputParams(cmd.Parameters), "FAILED: InputOutput parameter test with no returned rows and bound return value!");
-
-                    // now unbind the return value
-                    cmd.Parameters.RemoveAt(3);
-
-                    // remember to reset input params
-                    cmd.Parameters[0].Value = 1; // use 1, just for the heck of it
-                    cmd.Parameters[1].Value = 1999;
-                    cmd.Parameters[2].Value = Convert.DBNull;
-
-                    dataSet.Reset();
-
-                    sqlAdapter.Fill(dataSet);
-
-                    // verify the ouptut parameter
-                    Assert.True(
-                        ((int)cmd.Parameters[1].Value == 2000) &&
-                        (0 == string.Compare(cmd.Parameters[2].Value.ToString(), "Success!", false, CultureInfo.InvariantCulture)),
-                        "FAILED:  unbound return value case, output param is not correct!");
-
-                    Assert.True(1 == dataSet.Tables[0].Rows.Count, "FAILED:  Expected 1 row to be loaded in the dataSet!");
-
-                    row = dataSet.Tables[0].Rows[0];
-                    Assert.True((int)row["ShipperId"] == 1, "FAILED:  ShipperId column should be 1, not " + DBConvertToString(row["ShipperId"]));
-                }
-            }
-            finally
-            {
-                if (dropSP)
-                {
-                    ExecuteNonQueryCommand(spDropInOut);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UpdateTest()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            using (SqlDataAdapter adapter = new SqlDataAdapter())
-            using (SqlDataAdapter adapterVerify = new SqlDataAdapter())
-            {
-                conn.Open();
-
-                cmd.CommandText = string.Format(_createTableQuery, _tempTable);
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)";
-                cmd.ExecuteNonQuery();
-
-                try
-                {
-                    PrepareUpdateCommands(adapter, conn, _tempTable);
-
-                    adapter.SelectCommand = new SqlCommand(string.Format("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country from {0} where EmployeeID < 3", _tempTable), conn);
-                    adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn);
-
-                    adapter.TableMappings.Add(_tempTable, "rowset");
-                    adapterVerify.TableMappings.Add(_tempTable, "rowset");
-
-                    DataSet dataSet = new DataSet();
-                    VerifyFillSchemaResult(adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable), new string[] { "rowset" });
-
-                    // FillSchema
-                    dataSet.Tables["rowset"].PrimaryKey = new DataColumn[] { dataSet.Tables["rowset"].Columns["EmployeeID"] };
-                    adapter.Fill(dataSet, _tempTable);
-
-                    // Fill from Database
-                    Assert.True(dataSet.Tables[0].Rows.Count == 2, "FAILED:  Fill after FillSchema should populate the dataSet with two rows!");
-
-                    dataSet.AcceptChanges();
-
-                    // Verify that set is empty
-                    DataSet dataSetVerify = new DataSet();
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    // Insert
-                    DataRow datarow = dataSet.Tables["rowset"].NewRow();
-                    datarow.ItemArray = new object[] { "11", "The Original", MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" };
-                    datarow.Table.Rows.Add(datarow);
-
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set has one 'Magic' entry
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    dataSet.AcceptChanges();
-
-                    // Update
-                    datarow = dataSet.Tables["rowset"].Rows.Find("11");
-                    datarow.BeginEdit();
-                    datarow.ItemArray = new object[] { "11", "The New and Improved", MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" };
-                    datarow.EndEdit();
-
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set has updated 'Magic' entry
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    dataSet.AcceptChanges();
-
-                    // Delete
-                    dataSet.Tables["rowset"].Rows.Find("11").Delete();
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set is empty
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    dataSet.AcceptChanges();
-                }
-                finally
-                {
-                    ExecuteNonQueryCommand("DROP TABLE " + _tempTable);
-                }
-            }
-        }
-
-        // 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))]
-        public void BulkUpdateTest()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            using (SqlDataAdapter adapter = new SqlDataAdapter())
-            using (SqlDataAdapter adapterVerify = new SqlDataAdapter())
-            {
-                conn.Open();
-
-                cmd.CommandText = string.Format(_createTableQuery, _tempTable);
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)";
-                cmd.ExecuteNonQuery();
-
-                try
-                {
-                    PrepareUpdateCommands(adapter, conn, _tempTable);
-
-                    adapter.SelectCommand = new SqlCommand("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM " + _tempTable + " WHERE EmployeeID < 3", conn);
-                    adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn);
-
-                    adapter.TableMappings.Add(_tempTable, "rowset");
-                    adapterVerify.TableMappings.Add(_tempTable, "rowset");
-
-                    DataSet dataSet = new DataSet();
-                    adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable);
-
-                    dataSet.Tables["rowset"].PrimaryKey = new DataColumn[] { dataSet.Tables["rowset"].Columns["EmployeeID"] };
-                    adapter.Fill(dataSet, _tempTable);
-                    dataSet.AcceptChanges();
-
-                    // Verify that set is empty
-                    DataSet dataSetVerify = new DataSet();
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    // Bulk Insert  (10 records)
-                    DataRow datarow = null;
-                    const int cOps = 5;
-                    for (int i = 0; i < cOps * 2; i++)
-                    {
-                        datarow = dataSet.Tables["rowset"].NewRow();
-                        string sid = "99999000" + i.ToString();
-                        datarow.ItemArray = new object[] { sid, "Bulk Insert" + i.ToString(), MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" };
-                        datarow.Table.Rows.Add(datarow);
-                    }
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set has 10 'Magic' entries
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 10, _tempTable);
-                    dataSet.AcceptChanges();
-
-                    // Bulk Update (first 5)
-                    for (int i = 0; i < cOps; i++)
-                    {
-                        string sid = "99999000" + i.ToString();
-                        datarow = dataSet.Tables["rowset"].Rows.Find(sid);
-                        datarow.BeginEdit();
-                        datarow.ItemArray = new object[] { sid, "Bulk Update" + i.ToString(), MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" };
-                        datarow.EndEdit();
-                    }
-
-                    // Bulk Delete (last 5)
-                    for (int i = cOps; i < cOps * 2; i++)
-                    {
-                        string sid = "99999000" + i.ToString();
-                        dataSet.Tables["rowset"].Rows.Find(sid).Delete();
-                    }
-
-                    // now update the dataSet with the insert and delete changes
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set has 5 'Magic' updated entries
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 5, _tempTable);
-                    dataSet.AcceptChanges();
-
-                    // clean up the remaining 5 rows
-                    for (int i = 0; i < cOps; i++)
-                    {
-                        string sid = "99999000" + i.ToString();
-                        dataSet.Tables["rowset"].Rows.Find(sid).Delete();
-                    }
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set has no entries
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-                    dataSet.AcceptChanges();
-                }
-                finally
-                {
-                    ExecuteNonQueryCommand("DROP TABLE " + _tempTable);
-                }
-            }
-        }
-
-        // Makes sure that we can refresh an identity column in the dataSet
-        // for a newly inserted row
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UpdateRefreshTest()
-        {
-            string createIdentTable =
-                "CREATE TABLE ident(id int IDENTITY," +
-                "LastName nvarchar(50) NULL," +
-                "Firstname nvarchar(50) NULL)";
-
-            string spCreateInsert =
-                "CREATE PROCEDURE sp_insert" + _tempTable +
-                "(@FirstName nvarchar(50), @LastName nvarchar(50), @id int OUTPUT) " +
-                "AS INSERT INTO " + _tempTable + " (FirstName, LastName) " +
-                "VALUES (@FirstName, @LastName); " +
-                "SELECT @id=@@IDENTITY";
-
-            string spDropInsert = "DROP PROCEDURE sp_insert" + _tempTable;
-            bool dropSP = false;
-
-            using (SqlDataAdapter adapter = new SqlDataAdapter())
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = new SqlCommand(null, conn))
-            using (SqlCommand temp = new SqlCommand("SELECT id, LastName, FirstName into " + _tempTable + " from ident", conn))
-            using (SqlCommand tableClean = new SqlCommand("", conn))
-            {
-                ExecuteNonQueryCommand(createIdentTable);
-                try
-                {
-                    adapter.InsertCommand = new SqlCommand()
-                    {
-                        CommandText = "sp_insert" + _tempTable,
-                        CommandType = CommandType.StoredProcedure
-                    };
-                    adapter.InsertCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName"));
-                    adapter.InsertCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 50, "LastName"));
-                    SqlParameter param = adapter.InsertCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
-                    param.SourceColumn = "id";
-                    param.Direction = ParameterDirection.Output;
-
-                    adapter.InsertCommand.Parameters.Add(new SqlParameter("@badapple", SqlDbType.NVarChar, 50, "LastName"));
-                    adapter.RowUpdating += new SqlRowUpdatingEventHandler(RowUpdating_UpdateRefreshTest);
-                    adapter.RowUpdated += new SqlRowUpdatedEventHandler(RowUpdated_UpdateRefreshTest);
-
-                    adapter.InsertCommand.Connection = conn;
-                    conn.Open();
-
-                    temp.ExecuteNonQuery();
-
-                    // start clean
-                    tableClean.CommandText = "delete " + _tempTable;
-                    tableClean.ExecuteNonQuery();
-                    tableClean.CommandText = spCreateInsert;
-                    tableClean.ExecuteNonQuery();
-
-                    dropSP = true;
-
-                    DataSet ds = new DataSet();
-                    adapter.TableMappings.Add("Table", _tempTable);
-                    cmd.CommandText = "select * from " + _tempTable;
-                    adapter.SelectCommand = cmd;
-                    adapter.Fill(ds, "Table");
-
-                    // Insert
-                    DataRow row1 = ds.Tables[_tempTable].NewRow();
-                    row1.ItemArray = new object[] { 0, "Bond", "James" };
-                    row1.Table.Rows.Add(row1);
-
-                    DataRow row2 = ds.Tables[_tempTable].NewRow();
-                    row2.ItemArray = new object[] { 0, "Lee", "Bruce" };
-                    row2.Table.Rows.Add(row2);
-
-                    Assert.True((int)row1["id"] == 0 && (int)row2["id"] == 0, "FAILED:  UpdateRefresh should not have values for identity columns");
-
-                    adapter.Update(ds, "Table");
-
-                    // should have values now
-                    int i1 = (int)row1["id"];
-                    int i2 = (int)row2["id"];
-
-                    Assert.True(
-                        (i1 != 0) && (i2 != 0) && (i2 == (i1 + 1)),
-                        string.Format("FAILED:  UpdateRefresh, i2 should equal (i1 + 1). i1: {0}. i2: {1}.", i1, i2));
-                }
-                finally
-                {
-                    if (dropSP)
-                    {
-                        ExecuteNonQueryCommand(spDropInsert);
-                        ExecuteNonQueryCommand("DROP TABLE " + _tempTable);
-                    }
-                    ExecuteNonQueryCommand("DROP TABLE ident");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UpdateNullTest()
-        {
-            string createTable = "CREATE TABLE varbin(cvarbin VARBINARY(7000), cimage IMAGE)";
-
-            string createSP =
-                "CREATE PROCEDURE sp_insertvarbin (@val_cvarbin VARBINARY(7000), @val_cimage IMAGE)" +
-                "AS INSERT INTO varbin (cvarbin, cimage)" +
-                "VALUES (@val_cvarbin, @val_cimage)";
-            bool dropSP = false;
-
-            try
-            {
-                ExecuteNonQueryCommand(createTable);
-                ExecuteNonQueryCommand(createSP);
-                dropSP = true;
-
-                using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (SqlCommand cmdInsert = new SqlCommand("sp_insertvarbin", conn))
-                using (SqlCommand cmdSelect = new SqlCommand("select * from varbin", conn))
-                using (SqlCommand tableClean = new SqlCommand("delete varbin", conn))
-                using (SqlDataAdapter adapter = new SqlDataAdapter())
-                {
-                    conn.Open();
-
-                    cmdInsert.CommandType = CommandType.StoredProcedure;
-                    SqlParameter p1 = cmdInsert.Parameters.Add(new SqlParameter("@val_cvarbin", SqlDbType.VarBinary, 7000));
-                    SqlParameter p2 = cmdInsert.Parameters.Add(new SqlParameter("@val_cimage", SqlDbType.Image, 8000));
-
-                    tableClean.ExecuteNonQuery();
-                    p1.Value = Convert.DBNull;
-                    p2.Value = Convert.DBNull;
-                    int rowsAffected = cmdInsert.ExecuteNonQuery();
-                    DataTestUtility.AssertEqualsWithDescription(1, rowsAffected, "Unexpected number of rows inserted.");
-
-                    DataSet ds = new DataSet();
-                    adapter.SelectCommand = cmdSelect;
-                    adapter.Fill(ds, "goofy");
-                    // should have 1 row in table (with two null entries)
-                    DataTestUtility.AssertEqualsWithDescription(1, ds.Tables[0].Rows.Count, "Unexpected rows count.");
-                    DataTestUtility.AssertEqualsWithDescription(DBNull.Value, ds.Tables[0].Rows[0][0], "Unexpected value.");
-                    DataTestUtility.AssertEqualsWithDescription(DBNull.Value, ds.Tables[0].Rows[0][1], "Unexpected value.");
-                }
-            }
-            finally
-            {
-                if (dropSP)
-                {
-                    ExecuteNonQueryCommand("DROP PROCEDURE sp_insertvarbin");
-                }
-                ExecuteNonQueryCommand("DROP TABLE varbin");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UpdateOffsetTest()
-        {
-            string createTable = "CREATE TABLE varbin(cvarbin VARBINARY(7000), cimage IMAGE)";
-
-            string createSP =
-                "CREATE PROCEDURE sp_insertvarbin (@val_cvarbin VARBINARY(7000), @val_cimage IMAGE)" +
-                "AS INSERT INTO varbin (cvarbin, cimage)" +
-                "VALUES (@val_cvarbin, @val_cimage)";
-            bool dropSP = false;
-
-            try
-            {
-                ExecuteNonQueryCommand(createTable);
-                ExecuteNonQueryCommand(createSP);
-                dropSP = true;
-
-                using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (SqlCommand cmdInsert = new SqlCommand("sp_insertvarbin", conn))
-                using (SqlCommand cmdSelect = new SqlCommand("select * from varbin", conn))
-                using (SqlCommand tableClean = new SqlCommand("delete varbin", conn))
-                using (SqlDataAdapter adapter = new SqlDataAdapter())
-                {
-                    conn.Open();
-
-                    cmdInsert.CommandType = CommandType.StoredProcedure;
-                    SqlParameter p1 = cmdInsert.Parameters.Add(new SqlParameter("@val_cvarbin", SqlDbType.VarBinary, 7000));
-                    SqlParameter p2 = cmdInsert.Parameters.Add(new SqlParameter("@val_cimage", SqlDbType.Image, 7000));
-
-                    tableClean.ExecuteNonQuery();
-
-                    byte[] b = new byte[7];
-                    b[0] = 0x01;
-                    b[1] = 0x02;
-                    b[2] = 0x03;
-                    b[3] = 0x04;
-                    b[4] = 0x05;
-                    b[5] = 0x06;
-                    b[6] = 0x07;
-                    p1.Value = b;
-                    p1.Size = 4;
-
-                    p2.Value = b;
-                    p2.Size = 3;
-                    p2.Offset = 4;
-                    int rowsAffected = cmdInsert.ExecuteNonQuery();
-
-                    DataSet ds = new DataSet();
-                    adapter.SelectCommand = cmdSelect;
-                    adapter.Fill(ds, "goofy");
-
-                    byte[] expectedBytes1 = { 0x01, 0x02, 0x03, 0x04 };
-                    byte[] val = (byte[])(ds.Tables[0].Rows[0][0]);
-                    Assert.True(ByteArraysEqual(expectedBytes1, val), "FAILED: Test 1: Unequal byte arrays.");
-
-                    byte[] expectedBytes2 = { 0x05, 0x06, 0x07 };
-                    val = (byte[])(ds.Tables[0].Rows[0][1]);
-                    Assert.True(ByteArraysEqual(expectedBytes2, val), "FAILED: Test 2: Unequal byte arrays.");
-                }
-            }
-            finally
-            {
-                if (dropSP)
-                {
-                    ExecuteNonQueryCommand("DROP PROCEDURE sp_insertvarbin");
-                }
-                ExecuteNonQueryCommand("DROP TABLE varbin");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void SelectAllTest()
-        {
-            // Test exceptions
-            using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(new SqlCommand("select * from orders", new SqlConnection(DataTestUtility.TcpConnStr))))
-            {
-                DataSet dataset = new DataSet();
-                sqlAdapter.TableMappings.Add("Table", "orders");
-                sqlAdapter.Fill(dataset);
-            }
-        }
-
-        // AutoGen test
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void AutoGenUpdateTest()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            using (SqlDataAdapter adapter = new SqlDataAdapter())
-            using (SqlDataAdapter adapterVerify = new SqlDataAdapter())
-            {
-                conn.Open();
-
-                cmd.CommandText = string.Format(_createTableQuery, _tempTable);
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)";
-                cmd.ExecuteNonQuery();
-
-                try
-                {
-                    adapter.SelectCommand = new SqlCommand(string.Format("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country from {0} where EmployeeID < 3", _tempTable), conn);
-                    adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn);
-
-                    adapter.TableMappings.Add(_tempTable, "rowset");
-                    adapterVerify.TableMappings.Add(_tempTable, "rowset");
-
-                    // FillSchema
-                    DataSet dataSet = new DataSet();
-                    VerifyFillSchemaResult(adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable), new string[] { "rowset" });
-
-                    adapter.Fill(dataSet, _tempTable);
-
-                    // Fill from Database
-                    Assert.True(dataSet.Tables[0].Rows.Count == 2, "FAILED:  Fill after FillSchema should populate the dataSet with two rows!");
-
-                    // Verify that set is empty
-                    DataSet dataSetVerify = new DataSet();
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
-
-                    // Insert
-                    DataRow datarow = dataSet.Tables["rowset"].NewRow();
-                    datarow.ItemArray = new object[] { "11", "The Original", MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" };
-                    datarow.Table.Rows.Add(datarow);
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set has one 'Magic' entry
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    // Update
-                    datarow = dataSet.Tables["rowset"].Rows.Find("11");
-                    datarow.BeginEdit();
-                    datarow.ItemArray = new object[] { "11", "The New and Improved", MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" };
-                    datarow.EndEdit();
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set has updated 'Magic' entry
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    // Delete
-                    dataSet.Tables["rowset"].Rows.Find("11").Delete();
-                    adapter.Update(dataSet, _tempTable);
-
-                    // Verify that set is empty
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-                }
-                finally
-                {
-                    ExecuteNonQueryCommand("DROP TABLE " + _tempTable);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void AutoGenErrorTest()
-        {
-            string createIdentTable =
-                "CREATE TABLE ident(id int IDENTITY," +
-                "LastName nvarchar(50) NULL," +
-                "Firstname nvarchar(50) NULL)";
-
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (SqlCommand cmd = new SqlCommand("SELECT * into " + _tempTable + " from ident", conn))
-                using (SqlDataAdapter adapter = new SqlDataAdapter())
-                {
-                    ExecuteNonQueryCommand(createIdentTable);
-
-                    conn.Open();
-                    adapter.SelectCommand = new SqlCommand("select * from " + _tempTable, conn);
-
-                    cmd.ExecuteNonQuery();
-
-                    // start clean
-                    DataSet ds = new DataSet();
-                    adapter.Fill(ds, _tempTable);
-
-                    // Insert
-                    DataRow row1 = ds.Tables[_tempTable].NewRow();
-                    row1.ItemArray = new object[] { 0, "Bond", "James" };
-                    row1.Table.Rows.Add(row1);
-
-                    // table has no key so we should get an error here when we try to autogen the delete command (note that all three
-                    // update command types are generated here despite the fact that we are just doing an insert)
-                    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
-                    adapter.Update(ds, _tempTable);
-                }
-            }
-            finally
-            {
-                ExecuteNonQueryCommand("DROP TABLE ident");
-            }
-        }
-
-        // 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))]
-        public void AutoGenBulkUpdateTest()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            using (SqlDataAdapter adapter = new SqlDataAdapter())
-            using (SqlDataAdapter adapterVerify = new SqlDataAdapter())
-            {
-                conn.Open();
-
-                cmd.CommandText = string.Format(_createTableQuery, _tempTable);
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = "alter table " + _tempTable + " add constraint " + _tempKey + " primary key (EmployeeID)";
-                cmd.ExecuteNonQuery();
-
-                try
-                {
-                    adapter.SelectCommand = new SqlCommand("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country FROM " + _tempTable + " WHERE EmployeeID < 3", conn);
-                    adapterVerify.SelectCommand = new SqlCommand("SELECT LastName, FirstName FROM " + _tempTable + " where FirstName='" + MagicName + "'", conn);
-
-                    adapter.TableMappings.Add(_tempTable, "rowset");
-                    adapterVerify.TableMappings.Add(_tempTable, "rowset");
-
-                    DataSet dataSet = new DataSet();
-                    adapter.FillSchema(dataSet, SchemaType.Mapped, _tempTable);
-
-                    dataSet.Tables["rowset"].PrimaryKey = new DataColumn[] { dataSet.Tables["rowset"].Columns["EmployeeID"] };
-                    adapter.Fill(dataSet, _tempTable);
-
-                    // Verify that set is empty
-                    DataSet dataSetVerify = new DataSet();
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-
-                    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
-
-                    // Bulk Insert  (10 records)
-                    DataRow datarow = null;
-                    const int cOps = 5;
-                    for (int i = 0; i < cOps * 2; i++)
-                    {
-                        datarow = dataSet.Tables["rowset"].NewRow();
-                        string sid = "99999000" + i.ToString();
-                        datarow.ItemArray = new object[] { sid, "Bulk Insert" + i.ToString(), MagicName, "Engineer", "One Microsoft Way", "Redmond", "WA", "98052", "USA" };
-                        datarow.Table.Rows.Add(datarow);
-                    }
-                    adapter.Update(dataSet, _tempTable);
-                    // Verify that set has 10 'Magic' entries
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 10, _tempTable);
-                    dataSet.AcceptChanges();
-
-                    // Bulk Update (first 5)
-                    for (int i = 0; i < cOps; i++)
-                    {
-                        string sid = "99999000" + i.ToString();
-                        datarow = dataSet.Tables["rowset"].Rows.Find(sid);
-                        datarow.BeginEdit();
-                        datarow.ItemArray = new object[] { sid, "Bulk Update" + i.ToString(), MagicName, "reenignE", "Yaw Tfosorcim Eno", "Dnomder", "WA", "52098", "ASU" };
-                        datarow.EndEdit();
-                    }
-
-                    // Bulk Delete (last 5)
-                    for (int i = cOps; i < cOps * 2; i++)
-                    {
-                        string sid = "99999000" + i.ToString();
-                        dataSet.Tables["rowset"].Rows.Find(sid).Delete();
-                    }
-
-                    // now update the dataSet with the insert and delete changes
-                    adapter.Update(dataSet, _tempTable);
-                    // Verify that set has 5 'Magic' updated entries
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 5, _tempTable);
-
-                    // clean up the remaining 5 rows
-                    for (int i = 0; i < cOps; i++)
-                    {
-                        string sid = "99999000" + i.ToString();
-                        dataSet.Tables["rowset"].Rows.Find(sid).Delete();
-                    }
-                    adapter.Update(dataSet, _tempTable);
-                    // Verify that set has no entries
-                    VerifyUpdateRow(adapterVerify, dataSetVerify, 0, _tempTable);
-                }
-                finally
-                {
-                    ExecuteNonQueryCommand("DROP TABLE " + _tempTable);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestDeriveParameters()
-        {
-            string spEmployeeSales =
-            "create procedure [dbo].[Test_EmployeeSalesByCountry] " +
-            "@Beginning_Date DateTime, @Ending_Date DateTime AS " +
-            "SELECT Employees.Country, Employees.LastName, Employees.FirstName, Orders.ShippedDate, Orders.OrderID, \"Order Subtotals\".Subtotal AS SaleAmount " +
-            "FROM Employees INNER JOIN " +
-                "(Orders INNER JOIN \"Order Subtotals\" ON Orders.OrderID = \"Order Subtotals\".OrderID) " +
-                "ON Employees.EmployeeID = Orders.EmployeeID " +
-            "WHERE Orders.ShippedDate Between @Beginning_Date And @Ending_Date";
-            string dropSpEmployeeSales = "drop procedure [dbo].[Test_EmployeeSalesByCountry]";
-
-            string expectedParamResults =
-                "\"@RETURN_VALUE\" AS Int32 OF Int FOR Current \"\" " +
-                "0, 0, 0, ReturnValue, DEFAULT; " +
-                "\"@Beginning_Date\" AS DateTime OF DateTime FOR Current \"\" " +
-                "0, 0, 0, Input, DEFAULT; " +
-                "\"@Ending_Date\" AS DateTime OF DateTime FOR Current \"\" " +
-                "0, 0, 0, Input, DEFAULT; ";
-
-            try
-            {
-                ExecuteNonQueryCommand(spEmployeeSales);
-
-                using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (SqlCommand cmd = new SqlCommand("Test_EmployeeSalesByCountry", connection))
-                {
-                    string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DeriveParametersNotSupported, "SqlCommand", cmd.CommandType);
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(
-                        () => SqlCommandBuilder.DeriveParameters(cmd),
-                        errorMessage);
-
-                    errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_OpenConnectionRequired, "DeriveParameters", "");
-                    cmd.CommandType = CommandType.StoredProcedure;
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(
-                        () => SqlCommandBuilder.DeriveParameters(cmd),
-                        errorMessage);
-
-                    connection.Open();
-
-                    SqlCommandBuilder.DeriveParameters(cmd);
-                    CheckParameters(cmd, expectedParamResults);
-
-                    cmd.CommandText = "Test_EmployeeSalesBy";
-                    errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NoStoredProcedureExists, cmd.CommandText);
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(
-                        () => SqlCommandBuilder.DeriveParameters(cmd),
-                        errorMessage);
-
-                    cmd.CommandText = "Test_EmployeeSalesByCountry";
-                    SqlCommandBuilder.DeriveParameters(cmd);
-                    CheckParameters(cmd, expectedParamResults);
-                }
-            }
-            finally
-            {
-                ExecuteNonQueryCommand(dropSpEmployeeSales);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestReadOnlyColumnMetadata()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                using (SqlCommand command = connection.CreateCommand())
-                {
-                    command.CommandText = "Create table #t (ID int identity(1,1), sText varchar(12), sMemo as (convert(varchar,ID) + ' ' + sText))";
-                    command.ExecuteNonQuery();
-                }
-                using (SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from #t", connection))
-                {
-                    using (SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter))
-                    {
-                        using (SqlCommand cmd = commandBuilder.GetInsertCommand())
-                        {
-                            DataTestUtility.AssertEqualsWithDescription("INSERT INTO [#t] ([sText]) VALUES (@p1)", cmd.CommandText, "Unexpected insert command.");
-                        }
-                    }
-
-                    using (DataTable dataTable = new DataTable())
-                    {
-                        dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
-                        Dictionary<string, bool> expAutoIncrement = new Dictionary<string, bool>()
-                        {
-                            {"ID", true},
-                            {"sText", false},
-                            {"sMemo", false}
-                        };
-                        Dictionary<string, bool> expReadOnly = new Dictionary<string, bool>()
-                        {
-                            {"ID", true},
-                            {"sText", false},
-                            {"sMemo", true}
-                        };
-                        foreach (DataColumn dataColumn in dataTable.Columns)
-                        {
-                            DataTestUtility.AssertEqualsWithDescription(dataColumn.AutoIncrement, expAutoIncrement[dataColumn.ColumnName], "Unexpected AutoIncrement metadata.");
-                            DataTestUtility.AssertEqualsWithDescription(dataColumn.ReadOnly, expReadOnly[dataColumn.ColumnName], "Unexpected ReadOnly metadata.");
-                        }
-                    }
-                }
-            }
-        }
-
-        #region Utility_Methods
-        private void CheckParameters(SqlCommand cmd, string expectedResults)
-        {
-            Debug.Assert(null != cmd, "DumpParameters: null SqlCommand");
-
-            string actualResults = "";
-            StringBuilder builder = new StringBuilder();
-            foreach (SqlParameter p in cmd.Parameters)
-            {
-                byte precision = p.Precision;
-                byte scale = p.Scale;
-                builder.Append("\"" + p.ParameterName + "\" AS " + p.DbType.ToString("G") + " OF " + p.SqlDbType.ToString("G") + " FOR " + p.SourceVersion.ToString("G") + " \"" + p.SourceColumn + "\" ");
-                builder.Append(p.Size.ToString() + ", " + precision.ToString() + ", " + scale.ToString() + ", " + p.Direction.ToString("G") + ", " + DBConvertToString(p.Value) + "; ");
-            }
-            actualResults = builder.ToString();
-
-            DataTestUtility.AssertEqualsWithDescription(expectedResults, actualResults, "Unexpected Parameter results.");
-        }
-
-        private bool ByteArraysEqual(byte[] expectedBytes, byte[] actualBytes)
-        {
-            DataTestUtility.AssertEqualsWithDescription(
-                expectedBytes.Length, actualBytes.Length,
-                "Unexpected array length.");
-
-            for (int i = 0; i < expectedBytes.Length; i++)
-            {
-                DataTestUtility.AssertEqualsWithDescription(
-                    expectedBytes[i], actualBytes[i],
-                    "Unexpected byte value.");
-            }
-
-            return true;
-        }
-
-        private void InitDataValues()
-        {
-            _c_numeric_val = new decimal(42424242.42);
-            _c_unique_val = new byte[16];
-            _c_unique_val[0] = 0xba;
-            _c_unique_val[1] = 0xad;
-            _c_unique_val[2] = 0xf0;
-            _c_unique_val[3] = 0x0d;
-            _c_unique_val[4] = 0xba;
-            _c_unique_val[5] = 0xad;
-            _c_unique_val[6] = 0xf0;
-            _c_unique_val[7] = 0x0d;
-            _c_unique_val[8] = 0xba;
-            _c_unique_val[9] = 0xad;
-            _c_unique_val[10] = 0xf0;
-            _c_unique_val[11] = 0x0d;
-            _c_unique_val[12] = 0xba;
-            _c_unique_val[13] = 0xad;
-            _c_unique_val[14] = 0xf0;
-            _c_unique_val[15] = 0x0d;
-            _c_guid_val = new Guid(_c_unique_val);
-            _c_varbinary_val = _c_unique_val;
-            _c_binary_val = _c_unique_val;
-            _c_money_val = new decimal((double)123456789.99);
-            _c_smallmoney_val = new decimal((double)-6543.21);
-            _c_datetime_val = new DateTime(1971, 7, 20, 23, 59, 59);
-            _c_smalldatetime_val = new DateTime(1971, 7, 20, 23, 59, 0);
-            _c_nvarchar_val = "1234567890";
-            _c_nchar_val = _c_nvarchar_val;
-            _c_varchar_val = _c_nvarchar_val;
-            _c_char_val = _c_nvarchar_val;
-            _c_int_val = unchecked((int)0xffffffff);
-            _c_smallint_val = unchecked((short)0xffff);
-            _c_tinyint_val = 0xff;
-            _c_bigint_val = 0x11ffffff;
-            _c_bit_val = true;
-            _c_float_val = (double)12345678.2;
-            _c_real_val = (float)12345.1;
-
-            _values = new object[18];
-            _values[0] = _c_numeric_val;
-            _values[1] = _c_smalldatetime_val;
-            _values[2] = _c_guid_val;
-            _values[3] = _c_varbinary_val;
-            _values[4] = _c_binary_val;
-            _values[5] = _c_money_val;
-            _values[6] = _c_smallmoney_val;
-            _values[7] = _c_nvarchar_val;
-            _values[8] = _c_varchar_val;
-            _values[9] = _c_char_val;
-            _values[10] = _c_int_val;
-            _values[11] = _c_smallint_val;
-            _values[12] = _c_tinyint_val;
-            _values[13] = _c_bigint_val;
-            _values[14] = _c_bit_val;
-            _values[15] = _c_float_val;
-            _values[16] = _c_real_val;
-            _values[17] = _c_datetime_val;
-        }
-
-        private void VerifyFillSchemaResult(DataTable[] tables, string[] expectedTableNames)
-        {
-            DataTestUtility.AssertEqualsWithDescription(expectedTableNames.Length, tables.Length, "Unequal number of tables.");
-            for (int i = 0; i < tables.Length; i++)
-            {
-                DataTestUtility.AssertEqualsWithDescription(expectedTableNames[i], tables[i].TableName, "Unexpected DataTable TableName.");
-            }
-        }
-
-        // Prepares the Insert, Update, and Delete command to test updating against Northwind.Employees
-        private void PrepareUpdateCommands(SqlDataAdapter adapter, SqlConnection conn, string table)
-        {
-            // insert
-            adapter.InsertCommand = new SqlCommand()
-            {
-                CommandText = "INSERT INTO " + table + "(EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country) " +
-                "VALUES (@EmployeeID, @LastName, @FirstName, @Title, @Address, @City, @Region, @PostalCode, @Country)"
-            };
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 0, "EmployeeID"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20, "LastName"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10, "FirstName"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, 30, "Title"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 60, "Address"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 15, "City"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@Region", SqlDbType.NVarChar, 15, "Region"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10, "PostalCode"));
-            adapter.InsertCommand.Parameters.Add(new SqlParameter("@Country", SqlDbType.NVarChar, 15, "Country"));
-
-            adapter.InsertCommand.Connection = conn;
-
-            // update
-            adapter.UpdateCommand = new SqlCommand()
-            {
-                CommandText = "UPDATE " + table + " SET " +
-                "EmployeeID = @EmployeeID, LastName = @LastName, FirstName = @FirstName, Title = @Title, Address = @Address, City = @City, Region = @Region, " +
-                "PostalCode = @PostalCode, Country = @Country WHERE (EmployeeID = @OldEmployeeID)"
-            };
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 0, "EmployeeID"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20, "LastName"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10, "FirstName"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Title", SqlDbType.NVarChar, 30, "Title"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 60, "Address"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 15, "City"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Region", SqlDbType.NVarChar, 15, "Region"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10, "PostalCode"));
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@Country", SqlDbType.NVarChar, 15, "Country"));
-
-            adapter.UpdateCommand.Parameters.Add(new SqlParameter("@OldEmployeeID", SqlDbType.Int, 0, "EmployeeID")).SourceVersion = DataRowVersion.Original;
-            adapter.UpdateCommand.Connection = conn;
-
-            //
-            // delete
-            //
-            adapter.DeleteCommand = new SqlCommand()
-            {
-                CommandText = "DELETE FROM " + table + " WHERE (EmployeeID = @EmployeeID)"
-            };
-            adapter.DeleteCommand.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 0, "EmployeeID"));
-            adapter.DeleteCommand.Connection = conn;
-        }
-
-        private void RowUpdating_UpdateRefreshTest(object sender, SqlRowUpdatingEventArgs e)
-        {
-            // make sure that we always get a cloned command back (which means that it should always have the badapple parameter!)
-            e.Command = (SqlCommand)((ICloneable)e.Command).Clone();
-            DataTestUtility.AssertEqualsWithDescription("sp_insert", e.Command.CommandText.Substring(0, 9), "Unexpected command name.");
-            e.Command.Parameters.RemoveAt("@badapple");
-        }
-
-        private void RowUpdated_UpdateRefreshTest(object sender, SqlRowUpdatedEventArgs e)
-        {
-            DataTestUtility.AssertEqualsWithDescription("sp_insert", e.Command.CommandText.Substring(0, 9), "Unexpected command name.");
-        }
-
-        private void VerifyUpdateRow(SqlDataAdapter sa, DataSet ds, int cRows, string table)
-        {
-            ds.Reset();
-            sa.Fill(ds, table);
-
-            // don't dump out all the data, just get the row count
-            if (cRows > 0)
-            {
-                Assert.True(ds.Tables[0].Rows.Count == cRows, "FAILED:  expected " + cRows.ToString() + " rows but got " + ds.Tables[0].Rows.Count.ToString());
-            }
-
-            ds.Reset();
-        }
-
-        private bool VerifyOutputParams(SqlParameterCollection sqlParameters)
-        {
-            return
-                (int)sqlParameters[1].Value == 2000 &&
-                (0 == string.Compare((string)sqlParameters[2].Value, "Success!", false, CultureInfo.InvariantCulture)) &&
-                (int)sqlParameters[3].Value == 42;
-        }
-
-        private string DBConvertToString(object value)
-        {
-            StringBuilder builder = new StringBuilder();
-            WriteObject(builder, value, CultureInfo.InvariantCulture, null, 0, int.MaxValue);
-            return builder.ToString();
-        }
-
-        private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cultureInfo, Hashtable used, int indent, int recursionLimit)
-        {
-            if (0 > --recursionLimit)
-            {
-                return;
-            }
-            if (null == value)
-            {
-                textBuilder.Append("DEFAULT");
-            }
-            else if (Convert.IsDBNull(value))
-            {
-                textBuilder.Append("ISNULL");
-            }
-            else
-            {
-                Type valuetype = value.GetType();
-
-                if ((null != used) && (!valuetype.IsPrimitive))
-                {
-                    if (used.Contains(value))
-                    {
-                        textBuilder.Append('#');
-                        textBuilder.Append(((int)used[value]).ToString(cultureInfo));
-                        return;
-                    }
-                    else
-                    {
-                        textBuilder.Append('#');
-                        textBuilder.Append(used.Count.ToString(cultureInfo));
-                        used.Add(value, used.Count);
-                    }
-                }
-                if ((value is string) || (value is SqlString))
-                {
-                    if (value is SqlString)
-                    {
-                        value = ((SqlString)value).Value;
-                    }
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append(":");
-                    textBuilder.Append(((string)value).Length);
-                    textBuilder.Append("<");
-                    textBuilder.Append((string)value);
-                    textBuilder.Append(">");
-                }
-                else if ((value is DateTime) || (value is SqlDateTime))
-                {
-                    if (value is SqlDateTime)
-                    {
-                        value = ((SqlDateTime)value).Value;
-                    }
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append("<");
-                    textBuilder.Append(((DateTime)value).ToString("s", cultureInfo));
-                    textBuilder.Append(">");
-                }
-                else if ((value is float) || (value is SqlSingle))
-                {
-                    if (value is SqlSingle)
-                    {
-                        value = ((SqlSingle)value).Value;
-                    }
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append("<");
-                    textBuilder.Append(((float)value).ToString(cultureInfo));
-                    textBuilder.Append(">");
-                }
-                else if ((value is double) || (value is SqlDouble))
-                {
-                    if (value is SqlDouble)
-                    {
-                        value = ((SqlDouble)value).Value;
-                    }
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append("<");
-                    textBuilder.Append(((double)value).ToString(cultureInfo));
-                    textBuilder.Append(">");
-                }
-                else if ((value is decimal) || (value is SqlDecimal) || (value is SqlMoney))
-                {
-                    if (value is SqlDecimal)
-                    {
-                        value = ((SqlDecimal)value).Value;
-                    }
-                    else if (value is SqlMoney)
-                    {
-                        value = ((SqlMoney)value).Value;
-                    }
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append("<");
-                    textBuilder.Append(((decimal)value).ToString(cultureInfo));
-                    textBuilder.Append(">");
-                }
-                else if (value is INullable && ((INullable)value).IsNull)
-                {
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append(" ISNULL");
-                }
-                else if (valuetype.IsArray)
-                {
-                    textBuilder.Append(valuetype.Name);
-                    Array array = (Array)value;
-
-                    if (1 < array.Rank)
-                    {
-                        textBuilder.Append("{");
-                    }
-
-                    for (int i = 0; i < array.Rank; ++i)
-                    {
-                        int count = array.GetUpperBound(i);
-
-                        textBuilder.Append(' ');
-                        textBuilder.Append(count - array.GetLowerBound(i) + 1);
-                        textBuilder.Append("{ ");
-                        for (int k = array.GetLowerBound(i); k <= count; ++k)
-                        {
-                            AppendNewLineIndent(textBuilder, indent + 1);
-                            textBuilder.Append(',');
-                            WriteObject(textBuilder, array.GetValue(k), cultureInfo, used, 0, recursionLimit);
-                            textBuilder.Append(' ');
-                        }
-                        AppendNewLineIndent(textBuilder, indent);
-                        textBuilder.Append("}");
-                    }
-                    if (1 < array.Rank)
-                    {
-                        textBuilder.Append('}');
-                    }
-                }
-                else if (value is ICollection)
-                {
-                    textBuilder.Append(valuetype.Name);
-                    ICollection collection = (ICollection)value;
-                    object[] newvalue = new object[collection.Count];
-                    collection.CopyTo(newvalue, 0);
-
-                    textBuilder.Append(' ');
-                    textBuilder.Append(newvalue.Length);
-                    textBuilder.Append('{');
-                    for (int k = 0; k < newvalue.Length; ++k)
-                    {
-                        AppendNewLineIndent(textBuilder, indent + 1);
-                        textBuilder.Append(',');
-                        WriteObject(textBuilder, newvalue[k], cultureInfo, used, indent + 1, recursionLimit);
-                    }
-                    AppendNewLineIndent(textBuilder, indent);
-                    textBuilder.Append('}');
-                }
-                else if (value is Type)
-                {
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append('<');
-                    textBuilder.Append((value as Type).FullName);
-                    textBuilder.Append('>');
-                }
-                else if (valuetype.IsEnum)
-                {
-                    textBuilder.Append(valuetype.Name);
-                    textBuilder.Append('<');
-                    textBuilder.Append(Enum.GetName(valuetype, value));
-                    textBuilder.Append('>');
-                }
-                else
-                {
-                    string fullName = valuetype.FullName;
-                    if ("System.ComponentModel.ExtendedPropertyDescriptor" == fullName)
-                    {
-                        textBuilder.Append(fullName);
-                    }
-                    else
-                    {
-                        FieldInfo[] fields = valuetype.GetFields(BindingFlags.Instance | BindingFlags.Public);
-                        PropertyInfo[] properties = valuetype.GetProperties(BindingFlags.Instance | BindingFlags.Public);
-
-                        bool hasinfo = false;
-                        if ((null != fields) && (0 < fields.Length))
-                        {
-                            textBuilder.Append(fullName);
-                            fullName = null;
-
-                            Array.Sort(fields, FieldInfoCompare.s_default);
-                            for (int i = 0; i < fields.Length; ++i)
-                            {
-                                FieldInfo field = fields[i];
-
-                                AppendNewLineIndent(textBuilder, indent + 1);
-                                textBuilder.Append(field.Name);
-                                textBuilder.Append('=');
-                                object newvalue = field.GetValue(value);
-                                WriteObject(textBuilder, newvalue, cultureInfo, used, indent + 1, recursionLimit);
-                            }
-                            hasinfo = true;
-                        }
-                        if ((null != properties) && (0 < properties.Length))
-                        {
-                            if (null != fullName)
-                            {
-                                textBuilder.Append(fullName);
-                                fullName = null;
-                            }
-
-                            Array.Sort(properties, PropertyInfoCompare.s_default);
-                            for (int i = 0; i < properties.Length; ++i)
-                            {
-                                PropertyInfo property = properties[i];
-                                if (property.CanRead)
-                                {
-                                    ParameterInfo[] parameters = property.GetIndexParameters();
-                                    if ((null == parameters) || (0 == parameters.Length))
-                                    {
-                                        AppendNewLineIndent(textBuilder, indent + 1);
-                                        textBuilder.Append(property.Name);
-                                        textBuilder.Append('=');
-                                        object newvalue = null;
-                                        bool haveValue = false;
-                                        try
-                                        {
-                                            newvalue = property.GetValue(value, BindingFlags.Public | BindingFlags.GetProperty, null, null, CultureInfo.InvariantCulture);
-                                            haveValue = true;
-                                        }
-                                        catch (TargetInvocationException e)
-                                        {
-                                            textBuilder.Append(e.InnerException.GetType().Name);
-                                            textBuilder.Append(": ");
-                                            textBuilder.Append(e.InnerException.Message);
-                                        }
-                                        if (haveValue)
-                                        {
-                                            WriteObject(textBuilder, newvalue, cultureInfo, used, indent + 1, recursionLimit);
-                                        }
-                                    }
-                                }
-                            }
-                            hasinfo = true;
-                        }
-                        if (!hasinfo)
-                        {
-                            textBuilder.Append(valuetype.Name);
-                            textBuilder.Append('<');
-                            MethodInfo method = valuetype.GetMethod("ToString", new Type[] { typeof(IFormatProvider) });
-                            if (null != method)
-                            {
-                                textBuilder.Append((string)method.Invoke(value, new object[] { cultureInfo }));
-                            }
-                            else
-                            {
-                                string text = value.ToString();
-                                textBuilder.Append(text);
-                            }
-                            textBuilder.Append('>');
-                        }
-                    }
-                }
-            }
-        }
-
-        private void ExecuteNonQueryCommand(string cmdText)
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                conn.Open();
-                cmd.CommandText = cmdText;
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private void AppendNewLineIndent(StringBuilder textBuilder, int indent)
-        {
-            textBuilder.Append(Environment.NewLine);
-            char[] buf = _appendNewLineIndentBuffer;
-            if (buf.Length < indent * 4)
-            {
-                buf = new char[indent * 4];
-                for (int i = 0; i < buf.Length; ++i)
-                {
-                    buf[i] = ' ';
-                }
-                _appendNewLineIndentBuffer = buf;
-            }
-            textBuilder.Append(buf, 0, indent * 4);
-        }
-
-        private class PropertyInfoCompare : IComparer
-        {
-            internal static PropertyInfoCompare s_default = new PropertyInfoCompare();
-
-            private PropertyInfoCompare()
-            {
-            }
-
-            public int Compare(object x, object y)
-            {
-                string propertyInfoName1 = ((PropertyInfo)x).Name;
-                string propertyInfoName2 = ((PropertyInfo)y).Name;
-
-                return CultureInfo.InvariantCulture.CompareInfo.Compare(propertyInfoName1, propertyInfoName2, CompareOptions.IgnoreCase);
-            }
-        }
-
-        private class FieldInfoCompare : IComparer
-        {
-            internal static FieldInfoCompare s_default = new FieldInfoCompare();
-
-            private FieldInfoCompare()
-            {
-            }
-
-            public int Compare(object x, object y)
-            {
-                string fieldInfoName1 = ((FieldInfo)x).Name;
-                string fieldInfoName2 = ((FieldInfo)y).Name;
-
-                return CultureInfo.InvariantCulture.CompareInfo.Compare(fieldInfoName1, fieldInfoName2, CompareOptions.IgnoreCase);
-            }
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncTest.cs
deleted file mode 100644 (file)
index 19f2a59..0000000
+++ /dev/null
@@ -1,105 +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.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class AsyncTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestReadAsyncTimeConsumed()
-        {
-            const string sql = "SET NOCOUNT ON"
-                            + " SELECT 'a'"
-                            + " DECLARE @t DATETIME = SYSDATETIME()"
-                            + " WHILE DATEDIFF(s, @t, SYSDATETIME()) < 20 BEGIN"
-                            + "   SELECT 2 x INTO #y"
-                            + "   DROP TABLE #y"
-                            + " END"
-                            + " SELECT 'b'";
-            Task<double> t = RunReadAsync(sql);
-            double elapsedSync = RunReadSync(sql);
-            t.Wait();
-            double elapsedAsync = t.Result;
-            Assert.True(elapsedAsync < elapsedSync, "Asynchronous operation should be finished quicker than synchronous one");
-            int limit = 100;
-            Assert.True(elapsedAsync < limit, $"Asynchronous operation should be finished within {limit}ms");
-        }
-
-        private static async Task<double> RunReadAsync(string sql)
-        {
-            double maxElapsedTimeMillisecond = 0;
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                await connection.OpenAsync();
-                using (SqlCommand command = connection.CreateCommand())
-                {
-                    command.CommandText = sql;
-                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
-                    {
-                        Task<bool> t;
-                        Stopwatch stopwatch = new Stopwatch();
-                        do
-                        {
-                            do
-                            {
-                                stopwatch.Start();
-                                t = reader.ReadAsync();
-                                stopwatch.Stop();
-                                double elased = stopwatch.Elapsed.TotalMilliseconds;
-                                if (maxElapsedTimeMillisecond < elased)
-                                {
-                                    maxElapsedTimeMillisecond = elased;
-                                }
-                            }
-                            while (await t);
-                        }
-                        while (reader.NextResult());
-                    }
-                }
-            }
-
-            return maxElapsedTimeMillisecond;
-        }
-
-        private static double RunReadSync(string sql)
-        {
-            double maxElapsedTimeMillisecond = 0;
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                using (SqlCommand command = connection.CreateCommand())
-                {
-                    command.CommandText = sql;
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        bool result;
-                        Stopwatch stopwatch = new Stopwatch();
-                        do
-                        {
-                            do
-                            {
-                                stopwatch.Start();
-                                result = reader.Read();
-                                stopwatch.Stop();
-                                double elased = stopwatch.Elapsed.TotalMilliseconds;
-                                if (maxElapsedTimeMillisecond < elased)
-                                {
-                                    maxElapsedTimeMillisecond = elased;
-                                }
-                            }
-                            while (result);
-                        }
-                        while (reader.NextResult());
-                    }
-                }
-            }
-
-            return maxElapsedTimeMillisecond;
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecAsyncTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecAsyncTest.cs
deleted file mode 100644 (file)
index 73d87b0..0000000
+++ /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 Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class BeginExecAsyncTest
-    {
-        private static string GenerateCommandText()
-        {
-            int suffix = (new Random()).Next(5000);
-
-            string commandText =
-                $"CREATE TABLE #Shippers{suffix}(" +
-                    $"[ShipperID][int] NULL," +
-                    $"[CompanyName] [nvarchar] (40) NOT NULL," +
-                    $"[Phone] [nvarchar] (24) NULL )" +
-                $"INSERT INTO #Shippers{suffix}" +
-                        $"([CompanyName]  " +
-                        $",[Phone])" +
-                    $"VALUES " +
-                        $"('Acme Inc.' " +
-                        $",'555-1212'); " +
-                $"WAITFOR DELAY '0:0:3'; " +
-                $"DELETE FROM #Shippers{suffix} WHERE ShipperID > 3;";
-
-            return commandText;
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ExecuteTest()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                try
-                {
-                    SqlCommand command = new SqlCommand(GenerateCommandText(), connection);
-                    connection.Open();
-
-                    IAsyncResult result = command.BeginExecuteNonQuery();
-                    while (!result.IsCompleted)
-                    {
-                        System.Threading.Thread.Sleep(100);
-                    }
-
-                    Assert.True(command.EndExecuteNonQuery(result) > 0, "FAILED: BeginExecuteNonQuery did not complete successfully.");
-                }
-                catch (SqlException ex)
-                {
-                    Console.WriteLine("Error ({0}): {1}", ex.Number, ex.Message);
-                    Assert.Null(ex);
-                }
-                catch (InvalidOperationException ex)
-                {
-                    Console.WriteLine("Error: {0}", ex.Message);
-                    Assert.Null(ex);
-                }
-                catch (Exception ex)
-                {
-                    // You might want to pass these errors
-                    // back out to the caller.
-                    Console.WriteLine("Error: {0}", ex.Message);
-                    Assert.Null(ex);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void FailureTest()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                bool caughtException = false;
-                SqlCommand command = new SqlCommand(GenerateCommandText(), connection);
-                connection.Open();
-
-                //Try to execute a synchronous query on same command
-                IAsyncResult result = command.BeginExecuteNonQuery();
-                try
-                {
-                    command.ExecuteNonQuery();
-                }
-                catch (Exception ex)
-                {
-                    Assert.True(ex is InvalidOperationException, "FAILED: Thrown exception for BeginExecuteNonQuery was not an InvalidOperationException");
-                    caughtException = true;
-                }
-
-                Assert.True(caughtException, "FAILED: No exception thrown after trying second BeginExecuteNonQuery.");
-                caughtException = false;
-
-                while (!result.IsCompleted)
-                {
-                    System.Threading.Thread.Sleep(100);
-                }
-
-                Assert.True(result.IsCompleted, "FAILED: ExecuteNonQueryAsync Task did not complete successfully.");
-                Assert.True(command.EndExecuteNonQuery(result) > 0, "FAILED: No rows affected");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecReaderAsyncTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecReaderAsyncTest.cs
deleted file mode 100644 (file)
index c4db9a3..0000000
+++ /dev/null
@@ -1,83 +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;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class BeginExecReaderAsyncTest
-    {
-        private static string GenerateCommandText()
-        {
-            int suffix = (new Random()).Next(5000);
-            string companyName = "M Inc.";
-            string phone = "777-1111";
-
-            string commandText =
-                $"CREATE TABLE #Shippers{suffix}(" +
-                $"[ShipperID][int] NULL," +
-                $"[CompanyName] [nvarchar] (40) NOT NULL," +
-                $"[Phone] [nvarchar] (24) NULL )" +
-                $"INSERT INTO #Shippers{suffix}" +
-                $"([CompanyName]  " +
-                $",[Phone])" +
-                $"VALUES " +
-                $"('{companyName}' " +
-                $",'{phone}'); " +
-                $"WAITFOR DELAY '0:0:3'; " +
-                $"select s.ShipperID, s.CompanyName, s.Phone " +
-                $"from #Shippers{suffix} s; ";
-
-            return commandText;
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ExecuteTest()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                SqlCommand command = new SqlCommand(GenerateCommandText(), connection);
-                connection.Open();
-
-                IAsyncResult result = command.BeginExecuteReader();
-                while (!result.IsCompleted)
-                {
-                    System.Threading.Thread.Sleep(100);
-                }
-                SqlDataReader reader = command.EndExecuteReader(result);
-                Assert.True(reader.HasRows, $"FAILED: Reader has no rows");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void BeginExecuteReaderWithCallback()
-        {
-            object state = new object();
-            bool callbackExecutedFlag = false;
-
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand command = new SqlCommand(GenerateCommandText(), connection))
-            {
-                connection.Open();
-
-                Tuple<object, SqlCommand> stateAndCommand = new Tuple<object, SqlCommand>(state, command);
-
-                IAsyncResult result = command.BeginExecuteReader(ar =>
-                {
-                    Tuple<object, SqlCommand> asyncArgs = ar.AsyncState as Tuple<object, SqlCommand>;
-                    Assert.NotNull(asyncArgs);
-
-                    SqlDataReader reader = asyncArgs.Item2.EndExecuteReader(ar);
-                    callbackExecutedFlag = true;
-                    Assert.True(reader.HasRows, $"FAILED: Reader has no rows");
-                    Assert.Equal(state, asyncArgs.Item1);
-                }, stateAndCommand);
-
-                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
-
-                Assert.True(callbackExecutedFlag, $"FAILED: Callback did not executed");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/XmlReaderAsyncTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/XmlReaderAsyncTest.cs
deleted file mode 100644 (file)
index 3d56442..0000000
+++ /dev/null
@@ -1,66 +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;
-using System.Xml;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class XmlReaderAsyncTest
-    {
-        private static string commandText =
-            "SELECT * from dbo.Customers FOR XML AUTO, XMLDATA;";
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ExecuteTest()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                SqlCommand command = new SqlCommand(commandText, connection);
-                connection.Open();
-
-                IAsyncResult result = command.BeginExecuteXmlReader();
-                while (!result.IsCompleted)
-                {
-                    System.Threading.Thread.Sleep(100);
-                }
-
-                XmlReader reader = command.EndExecuteXmlReader(result);
-
-                reader.ReadToDescendant("dbo.Customers");
-                Assert.Equal("ALFKI", reader["CustomerID"]);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ExceptionTest()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                SqlCommand command = new SqlCommand(commandText, connection);
-                connection.Open();
-
-                //Try to execute a synchronous query on same command
-                IAsyncResult result = command.BeginExecuteXmlReader();
-
-                Assert.Throws<InvalidOperationException>( delegate { command.ExecuteXmlReader(); });
-
-                while (!result.IsCompleted)
-                {
-                    System.Threading.Thread.Sleep(100);
-                }
-
-                XmlReader reader = command.EndExecuteXmlReader(result);
-
-                reader.ReadToDescendant("dbo.Customers");
-                Assert.Equal("ALFKI", reader["CustomerID"]);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/CommandCancelTest/CommandCancelTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/CommandCancelTest/CommandCancelTest.cs
deleted file mode 100644 (file)
index d61f4f6..0000000
+++ /dev/null
@@ -1,283 +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.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class CommandCancelTest
-    {
-        // Shrink the packet size - this should make timeouts more likely
-        private static readonly string s_connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { PacketSize = 512 }).ConnectionString;
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void PlainCancelTest()
-        {
-            PlainCancel(s_connStr);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void PlainMARSCancelTest()
-        {
-            PlainCancel((new SqlConnectionStringBuilder(s_connStr) { MultipleActiveResultSets = true }).ConnectionString);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void PlainCancelTestAsync()
-        {
-            PlainCancelAsync(s_connStr);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void PlainMARSCancelTestAsync()
-        {
-            PlainCancelAsync((new SqlConnectionStringBuilder(s_connStr) { MultipleActiveResultSets = true }).ConnectionString);
-        }
-
-        private static void PlainCancel(string connString)
-        {
-            using (SqlConnection conn = new SqlConnection(connString))
-            using (SqlCommand cmd = new SqlCommand("select * from dbo.Orders; waitfor delay '00:00:10'; select * from dbo.Orders", conn))
-            {
-                conn.Open();
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    cmd.Cancel();
-                    DataTestUtility.AssertThrowsWrapper<SqlException>(
-                        () =>
-                        {
-                            do
-                            {
-                                while (reader.Read())
-                                {
-                                }
-                            }
-                            while (reader.NextResult());
-                        },
-                        "A severe error occurred on the current command.  The results, if any, should be discarded.");
-                }
-            }
-        }
-
-        private static void PlainCancelAsync(string connString)
-        {
-            using (SqlConnection conn = new SqlConnection(connString))
-            using (SqlCommand cmd = new SqlCommand("select * from dbo.Orders; waitfor delay '00:00:10'; select * from dbo.Orders", conn))
-            {
-                conn.Open();
-                Task<SqlDataReader> readerTask = cmd.ExecuteReaderAsync();
-                DataTestUtility.AssertThrowsWrapper<SqlException>(
-                    () =>
-                    {
-                        readerTask.Wait(2000);
-                        SqlDataReader reader = readerTask.Result;
-                        cmd.Cancel();
-                        do
-                        {
-                            while (reader.Read())
-                            {
-                            }
-                        }
-                        while (reader.NextResult());
-                    },
-                    "A severe error occurred on the current command.  The results, if any, should be discarded.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MultiThreadedCancel_NonAsync()
-        {
-            MultiThreadedCancel(s_connStr, false);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MultiThreadedCancel_Async()
-        {
-            MultiThreadedCancel(s_connStr, true);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TimeoutCancel()
-        {
-            TimeoutCancel(s_connStr);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void CancelAndDisposePreparedCommand()
-        {
-            CancelAndDisposePreparedCommand(s_connStr);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TimeOutDuringRead()
-        {
-            TimeOutDuringRead(s_connStr);
-        }
-
-        private static void MultiThreadedCancel(string constr, bool async)
-        {
-            using (SqlConnection con = new SqlConnection(constr))
-            {
-                con.Open();
-                var command = con.CreateCommand();
-                command.CommandText = "select * from orders; waitfor delay '00:00:08'; select * from customers";
-
-                Barrier threadsReady = new Barrier(2);
-                object state = new Tuple<bool, SqlCommand, Barrier>(async, command, threadsReady);
-
-                Task[] tasks = new Task[2];
-                tasks[0] = new Task(ExecuteCommandCancelExpected, state);
-                tasks[1] = new Task(CancelSharedCommand, state);
-                tasks[0].Start();
-                tasks[1].Start();
-
-                Task.WaitAll(tasks, 15 * 1000);
-
-                CommandCancelTest.VerifyConnection(command);
-            }
-        }
-
-        private static void TimeoutCancel(string constr)
-        {
-            using (SqlConnection con = new SqlConnection(constr))
-            {
-                con.Open();
-                SqlCommand cmd = con.CreateCommand();
-                cmd.CommandTimeout = 1;
-                cmd.CommandText = "WAITFOR DELAY '00:00:30';select * from Customers";
-
-                string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
-                DataTestUtility.ExpectFailure<SqlException>(() => cmd.ExecuteReader(), new string[] { errorMessage });
-
-                VerifyConnection(cmd);
-            }
-        }
-
-        //InvalidOperationException from connection.Dispose if that connection has prepared command cancelled during reading of data
-        private static void CancelAndDisposePreparedCommand(string constr)
-        {
-            int expectedValue = 1;
-            using (var connection = new SqlConnection(constr))
-            {
-                try
-                {
-                    // Generate a query with a large number of results.
-                    using (var command = new SqlCommand("select @P from sysobjects a cross join sysobjects b cross join sysobjects c cross join sysobjects d cross join sysobjects e cross join sysobjects f", connection))
-                    {
-                        command.Parameters.Add(new SqlParameter("@P", SqlDbType.Int) { Value = expectedValue });
-                        connection.Open();
-                        // Prepare the query.
-                        // Currently this does nothing until command.ExecuteReader is called.
-                        // Ideally this should call sp_prepare up-front.
-                        command.Prepare();
-                        using (var reader = command.ExecuteReader(CommandBehavior.SingleResult))
-                        {
-                            if (reader.Read())
-                            {
-                                int actualValue = reader.GetInt32(0);
-                                Assert.True(actualValue == expectedValue, string.Format("Got incorrect value. Expected: {0}, Actual: {1}", expectedValue, actualValue));
-                            }
-                            // Abandon reading the results.
-                            command.Cancel();
-                        }
-                    }
-                }
-                finally
-                {
-                    connection.Dispose(); // before the fix, InvalidOperationException happened here
-                }
-            }
-        }
-
-        private static void VerifyConnection(SqlCommand cmd)
-        {
-            Assert.True(cmd.Connection.State == ConnectionState.Open, "FAILURE: - unexpected non-open state after Execute!");
-
-            cmd.CommandText = "select 'ABC'"; // Verify Connection
-            string value = (string)cmd.ExecuteScalar();
-            Assert.True(value == "ABC", "FAILURE: upon validation execute on connection: '" + value + "'");
-        }
-
-        private static void ExecuteCommandCancelExpected(object state)
-        {
-            var stateTuple = (Tuple<bool, SqlCommand, Barrier>)state;
-            bool async = stateTuple.Item1;
-            SqlCommand command = stateTuple.Item2;
-            Barrier threadsReady = stateTuple.Item3;
-
-            string errorMessage = SystemDataResourceManager.Instance.SQL_OperationCancelled;
-            string errorMessageSevereFailure = SystemDataResourceManager.Instance.SQL_SevereError;
-
-            DataTestUtility.ExpectFailure<SqlException>(() =>
-            {
-                threadsReady.SignalAndWait();
-                using (SqlDataReader r = command.ExecuteReader())
-                {
-                    do
-                    {
-                        while (r.Read())
-                        {
-                        }
-                    } while (r.NextResult());
-                }
-            }, new string[] { errorMessage, errorMessageSevereFailure });
-
-        }
-
-        private static void CancelSharedCommand(object state)
-        {
-            var stateTuple = (Tuple<bool, SqlCommand, Barrier>)state;
-
-            // sleep 1 seconds before cancel to ensure ExecuteReader starts and ensure it does not end before Cancel is called (command is running WAITFOR 8 seconds)
-            stateTuple.Item3.SignalAndWait();
-            Thread.Sleep(TimeSpan.FromSeconds(1));
-            stateTuple.Item2.Cancel();
-        }
-
-        private static void TimeOutDuringRead(string constr)
-        {
-            // Create the proxy
-            ProxyServer proxy = ProxyServer.CreateAndStartProxy(constr, out constr);
-            proxy.SimulatedPacketDelay = 100;
-            proxy.SimulatedOutDelay = true;
-
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(constr))
-                {
-                    // Start the command
-                    conn.Open();
-                    SqlCommand cmd = new SqlCommand("SELECT @p", conn);
-                    cmd.Parameters.AddWithValue("p", new byte[20000]);
-                    SqlDataReader reader = cmd.ExecuteReader();
-                    reader.Read();
-
-                    // Tweak the timeout to 1ms, stop the proxy from proxying and then try GetValue (which should timeout)
-                    reader.SetDefaultTimeout(1);
-                    proxy.PauseCopying();
-                    string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
-                    Exception exception = Assert.Throws<SqlException>(() => reader.GetValue(0));
-                    Assert.Contains(errorMessage, exception.Message);
-
-                    // Return everything to normal and close
-                    proxy.ResumeCopying();
-                    reader.SetDefaultTimeout(30000);
-                    reader.Dispose();
-                }
-
-                proxy.Stop();
-            }
-            catch
-            {
-                // In case of error, stop the proxy and dump its logs (hopefully this will help with debugging
-                proxy.Stop();
-                Console.WriteLine(proxy.GetServerEventLog());
-                Assert.True(false, "Error while reading through proxy");
-                throw;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/AsyncDebugScope.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/AsyncDebugScope.cs
deleted file mode 100644 (file)
index eecfa67..0000000
+++ /dev/null
@@ -1,105 +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.Data.SqlClient.ManualTesting.Tests.SystemDataInternals;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class AsyncDebugScope : IDisposable
-    {
-        public bool ForceAllPends
-        {
-            get { return TdsParserStateObjectHelper.ForceAllPends; }
-            set { TdsParserStateObjectHelper.ForceAllPends = value; }
-        }
-
-        public bool SkipSendAttention
-        {
-            get { return TdsParserStateObjectHelper.SkipSendAttention; }
-            set { TdsParserStateObjectHelper.SkipSendAttention = value; }
-        }
-
-        public bool ForceSyncOverAsyncAfterFirstPend
-        {
-            get { return TdsParserStateObjectHelper.ForceSyncOverAsyncAfterFirstPend; }
-            set { TdsParserStateObjectHelper.ForceSyncOverAsyncAfterFirstPend = value; }
-        }
-
-        public bool ForcePendingReadsToWaitForUser
-        {
-            get { return TdsParserStateObjectHelper.ForcePendingReadsToWaitForUser; }
-            set { TdsParserStateObjectHelper.ForcePendingReadsToWaitForUser = value; }
-        }
-
-        public bool FailAsyncPends
-        {
-            get { return TdsParserStateObjectHelper.FailAsyncPends; }
-            set { TdsParserStateObjectHelper.FailAsyncPends = value; }
-        }
-
-        public int ForceAsyncWriteDelay
-        {
-            get { return CommandHelper.ForceAsyncWriteDelay; }
-            set { CommandHelper.ForceAsyncWriteDelay = value; }
-        }
-
-        public void Dispose()
-        {
-            TdsParserStateObjectHelper.FailAsyncPends = false;
-            TdsParserStateObjectHelper.ForceAllPends = false;
-            TdsParserStateObjectHelper.ForcePendingReadsToWaitForUser = false;
-            TdsParserStateObjectHelper.ForceSyncOverAsyncAfterFirstPend = false;
-            TdsParserStateObjectHelper.SkipSendAttention = false;
-            CommandHelper.ForceAsyncWriteDelay = 0;
-        }
-    }
-
-    public class PendAsyncReadsScope : IDisposable
-    {
-        private SqlCommand _command = null;
-        private SqlDataReader _reader = null;
-        private int? _errorCode = null;
-
-        public PendAsyncReadsScope(SqlCommand command, int? errorCode = null)
-        {
-            _command = command;
-            _errorCode = errorCode;
-            TdsParserStateObjectHelper.ForcePendingReadsToWaitForUser = true;
-        }
-
-        public PendAsyncReadsScope(SqlDataReader reader, int? errorCode = null)
-        {
-            _reader = reader;
-            _errorCode = errorCode;
-            TdsParserStateObjectHelper.ForcePendingReadsToWaitForUser = true;
-        }
-
-        public void Dispose()
-        {
-            if (_reader != null)
-            {
-                if (_errorCode.HasValue)
-                {
-                    _reader.CompletePendingReadWithFailure(_errorCode.Value, true);
-                }
-                else
-                {
-                    _reader.CompletePendingReadWithSuccess(true);
-                }
-            }
-
-            if (_command != null)
-            {
-                if (_errorCode.HasValue)
-                {
-                    _command.CompletePendingReadWithFailure(_errorCode.Value, true);
-                }
-                else
-                {
-                    _command.CompletePendingReadWithSuccess(true);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/ConnectionPoolWrapper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/ConnectionPoolWrapper.cs
deleted file mode 100644 (file)
index 2d51ba7..0000000
+++ /dev/null
@@ -1,128 +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.Linq;
-using System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class ConnectionPoolWrapper
-    {
-        private object _connectionPool = null;
-
-        /// <summary>
-        /// Finds the connection pool for the given connection
-        /// NOTE: This only works for connections that are currently open
-        /// </summary>
-        /// <param name="connection"></param>
-        public ConnectionPoolWrapper(SqlConnection connection)
-        {
-            if (connection == null)
-                throw new ArgumentNullException(nameof(connection));
-
-            _connectionPool = ConnectionHelper.GetConnectionPool(connection.GetInternalConnection());
-            ConnectionString = connection.ConnectionString;
-
-            if (_connectionPool == null)
-                throw new ArgumentException("Provided connection does not have a connection pool", "connection");
-        }
-
-        /// <summary>
-        /// Finds the connection pool for the given connection string
-        /// NOTE: There is currently no support for SSPI and multiple identities (single identity is ok)
-        /// </summary>
-        /// <param name="connectionString"></param>
-        public ConnectionPoolWrapper(string connectionString)
-        {
-            if (connectionString == null)
-                throw new ArgumentNullException(nameof(connectionString));
-
-            ConnectionString = connectionString;
-            _connectionPool = ConnectionPoolHelper.ConnectionPoolFromString(connectionString);
-            if (_connectionPool == null)
-                throw new ArgumentException("No pool exists for the provided connection string", "connectionString");
-        }
-
-        /// <summary>
-        /// Finds the connection pool for the given internal connection
-        /// </summary>
-        /// <param name="internalConnection"></param>
-        internal ConnectionPoolWrapper(object internalConnection, string connectionString)
-        {
-            _connectionPool = ConnectionHelper.GetConnectionPool(internalConnection);
-            ConnectionString = connectionString;
-
-            if (_connectionPool == null)
-                throw new ArgumentException("Provided internal connection does not have a connection pool", "internalConnection");
-        }
-
-        private ConnectionPoolWrapper()
-        { }
-
-        /// <summary>
-        /// The number of connections in this connection pool (free + non-free; including transaction pools)
-        /// </summary>
-        public int ConnectionCount
-        { get { return ConnectionPoolHelper.CountConnectionsInPool(_connectionPool); } }
-
-        /// <summary>
-        /// Counts the number of free connection in the pool (excluding any transaction pools)
-        /// </summary>
-        public int FreeConnectionCount
-        { get { return ConnectionPoolHelper.CountFreeConnections(_connectionPool); } }
-
-        /// <summary>
-        /// The connection string associated with this connection pool
-        /// </summary>
-        public string ConnectionString { get; private set; }
-
-        /// <summary>
-        /// Creates a list of all connection pools
-        /// </summary>
-        /// <returns></returns>
-        public static ConnectionPoolWrapper[] AllConnectionPools()
-        {
-            return (from t in ConnectionPoolHelper.AllConnectionPools()
-                    select new ConnectionPoolWrapper() { _connectionPool = t.Item1 }).ToArray();
-        }
-
-
-        /// <summary>
-        /// Invokes the cleanup timer code
-        /// </summary>
-        public void Cleanup()
-        {
-            ConnectionPoolHelper.CleanConnectionPool(_connectionPool);
-        }
-
-        /// <summary>
-        /// Checks if the SqlConnection specified has an internal connection that belongs to this pool
-        /// </summary>
-        /// <param name="connection"></param>
-        /// <returns></returns>
-        public bool ContainsConnection(SqlConnection connection)
-        {
-            if (connection == null)
-                throw new ArgumentNullException(nameof(connection));
-
-            return (_connectionPool == ConnectionHelper.GetConnectionPool(connection.GetInternalConnection()));
-        }
-
-        /// <summary>
-        /// Checks if this wrapper wraps the same pool as another wrapper
-        /// </summary>
-        /// <param name="obj">Wrapper to check against</param>
-        /// <returns>True if <paramref name="obj"/> is a ConnectionPoolWrapper that points to the same pool as this wrapper, otherwise false</returns>
-        public override bool Equals(object obj)
-        {
-            var objAsPool = obj as ConnectionPoolWrapper;
-            return ((objAsPool != null) && (objAsPool._connectionPool == _connectionPool));
-        }
-
-        public override int GetHashCode()
-        {
-            return _connectionPool.GetHashCode();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/InternalConnectionWrapper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/InternalConnectionWrapper.cs
deleted file mode 100644 (file)
index 7e1ba0d..0000000
+++ /dev/null
@@ -1,196 +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.Generic;
-using System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals;
-using System.Threading;
-using System.Runtime.InteropServices;
-using System.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class InternalConnectionWrapper
-    {
-        private static Dictionary<string, string> s_killByTSqlConnectionStrings = new Dictionary<string, string>();
-        private static ReaderWriterLockSlim s_killByTSqlConnectionStringsLock = new ReaderWriterLockSlim();
-
-        private object _internalConnection = null;
-        private object _spid = null;
-
-        /// <summary>
-        /// Gets the internal connection associated with the given SqlConnection
-        /// </summary>
-        /// <param name="connection">Live outer connection to grab the inner connection from</param>
-        /// <param name="supportKillByTSql">If true then we will query the server for this connection's SPID details (to be used in the KillConnectionByTSql method)</param>
-        public InternalConnectionWrapper(SqlConnection connection, bool supportKillByTSql = false)
-        {
-            if (connection == null)
-                throw new ArgumentNullException(nameof(connection));
-
-            _internalConnection = connection.GetInternalConnection();
-            ConnectionString = connection.ConnectionString;
-
-            if (supportKillByTSql)
-            {
-                // Save the SPID for later use
-                using (SqlCommand command = new SqlCommand("SELECT @@SPID", connection))
-                {
-                    _spid = command.ExecuteScalar();
-                }
-            }
-        }
-
-        /// <summary>
-        /// Gets the connection pool this internal connection is in
-        /// </summary>
-        public ConnectionPoolWrapper ConnectionPool
-        { get { return new ConnectionPoolWrapper(_internalConnection, ConnectionString); } }
-
-        /// <summary>
-        /// Is this internal connection associated with the given SqlConnection
-        /// </summary>
-        /// <param name="connection"></param>
-        /// <returns></returns>
-        public bool IsInternalConnectionOf(SqlConnection connection)
-        {
-            if (connection == null)
-                throw new ArgumentNullException(nameof(connection));
-
-            return (_internalConnection == connection.GetInternalConnection());
-        }
-
-
-        /// <summary>
-        /// The connection string used to create this connection
-        /// </summary>
-        public string ConnectionString { get; private set; }
-
-        /// <summary>
-        /// True if the connection is still alive, otherwise false
-        /// NOTE: Do NOT use this on a connection that is currently in use (There is a Debug.Assert and it will always return true)
-        /// NOTE: If the connection is dead, it will be marked as 'broken'
-        /// </summary>
-        public bool IsConnectionAlive()
-        {
-            return ConnectionHelper.IsConnectionAlive(_internalConnection);
-        }
-
-        /// <summary>
-        /// Will attempt to kill the connection
-        /// </summary>
-        public void KillConnection()
-        {
-            object tdsParser = ConnectionHelper.GetParser(_internalConnection);
-            object stateObject = TdsParserHelper.GetStateObject(tdsParser);
-            object sessionHandle = TdsParserStateObjectHelper.GetSessionHandle(stateObject);
-
-            Assembly systemDotData = Assembly.Load(new AssemblyName(typeof(SqlConnection).GetTypeInfo().Assembly.FullName));
-            Type sniHandleType = systemDotData.GetType("System.Data.SqlClient.SNI.SNIHandle");
-            MethodInfo killConn = sniHandleType.GetMethod("KillConnection");
-
-            if (killConn != null)
-            {
-                killConn.Invoke(sessionHandle, null);
-            }
-            else
-            {
-                throw new InvalidOperationException("Error: Could not find SNI KillConnection test hook. This operation is only supported in debug builds.");
-            }
-            // Ensure kill occurs outside of check connection window
-            Thread.Sleep(100);
-        }
-
-        /// <summary>
-        /// Requests that the server kills this connection
-        /// NOTE: InternalConnectionWrapper must be created with SupportKillByTSql enabled
-        /// </summary>
-        public void KillConnectionByTSql()
-        {
-            if (_spid != null)
-            {
-                using (SqlConnection connection = new SqlConnection(GetKillByTSqlConnectionString()))
-                {
-                    connection.Open();
-                    using (SqlCommand command = new SqlCommand(string.Format("KILL {0}", _spid), connection))
-                    {
-                        command.ExecuteNonQuery();
-                    }
-                }
-                // Ensure kill occurs outside of check connection window
-                Thread.Sleep(100);
-            }
-            else
-            {
-                throw new InvalidOperationException("Kill by TSql not enabled on this InternalConnectionWrapper");
-            }
-        }
-
-        /// <summary>
-        /// Gets a connection string that can be used to send a command to the server to kill this connection
-        /// </summary>
-        /// <returns>A connection string</returns>
-        private string GetKillByTSqlConnectionString()
-        {
-            string killConnectionString = null;
-            bool containsConnectionString = true;
-
-            try
-            {
-                s_killByTSqlConnectionStringsLock.EnterReadLock();
-                containsConnectionString = s_killByTSqlConnectionStrings.TryGetValue(ConnectionString, out killConnectionString);
-            }
-            finally
-            {
-                s_killByTSqlConnectionStringsLock.ExitReadLock();
-            }
-            if (!containsConnectionString)
-            {
-                killConnectionString = CreateKillByTSqlConnectionString(ConnectionString);
-
-                try
-                {
-                    s_killByTSqlConnectionStringsLock.EnterWriteLock();
-                    s_killByTSqlConnectionStrings.TryAdd(ConnectionString, killConnectionString);
-                }
-                finally
-                {
-                    s_killByTSqlConnectionStringsLock.ExitWriteLock();
-                }
-            }
-
-            return killConnectionString;
-        }
-
-        /// <summary>
-        /// Converts a connection string for a format which is appropriate to kill another connection with (i.e. non-pooled, no transactions)
-        /// </summary>
-        /// <param name="connectionString">Base connection string to convert</param>
-        /// <returns>The converted connection string</returns>
-        private static string CreateKillByTSqlConnectionString(string connectionString)
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
-            // Avoid tampering with the connection pool
-            builder.Pooling = false;
-            return builder.ConnectionString;
-        }
-
-        // override object.Equals
-        public override bool Equals(object obj)
-        {
-            bool areEquals = false;
-
-            InternalConnectionWrapper objAsWrapper = obj as InternalConnectionWrapper;
-            if ((objAsWrapper != null) && (objAsWrapper._internalConnection == _internalConnection))
-                areEquals = true;
-
-            return areEquals;
-        }
-
-        // override object.GetHashCode
-        public override int GetHashCode()
-        {
-            return _internalConnection.GetHashCode();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataExtensions.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataExtensions.cs
deleted file mode 100644 (file)
index b7db251..0000000
+++ /dev/null
@@ -1,51 +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.Data.SqlClient.ManualTesting.Tests.SystemDataInternals;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class SystemDataExtensions
-    {
-        public static void CompletePendingReadWithSuccess(this SqlDataReader reader, bool resetForcePendingReadsToWait)
-        {
-            DataReaderHelper.CompletePendingReadWithSuccess(reader, resetForcePendingReadsToWait);
-        }
-
-        public static void CompletePendingReadWithFailure(this SqlDataReader reader, int errorCode, bool resetForcePendingReadsToWait)
-        {
-            DataReaderHelper.CompletePendingReadWithFailure(reader, errorCode, resetForcePendingReadsToWait);
-        }
-
-        public static void CompletePendingReadWithSuccess(this SqlCommand command, bool resetForcePendingReadsToWait)
-        {
-            CommandHelper.CompletePendingReadWithSuccess(command, resetForcePendingReadsToWait);
-        }
-
-        public static void CompletePendingReadWithFailure(this SqlCommand command, int errorCode, bool resetForcePendingReadsToWait)
-        {
-            CommandHelper.CompletePendingReadWithFailure(command, errorCode, resetForcePendingReadsToWait);
-        }
-
-        public static void SetDefaultTimeout(this SqlDataReader reader, long milliseconds)
-        {
-            DataReaderHelper.SetDefaultTimeout(reader, milliseconds);
-        }
-
-        public static T GetSchemaEntry<T>(this SqlDataReader reader, int row, string schemaEntry)
-        {
-            return DataReaderHelper.GetSchemaEntry<T>(reader, row, schemaEntry);
-        }
-
-        public static object[] GetMetaEntries(this SqlDataReader reader)
-        {
-            return DataReaderHelper.GetMetaEntries(reader);
-        }
-
-        public static bool IsLong(this SqlDataReader reader, int row)
-        {
-            return DataReaderHelper.IsLong(reader, row);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/CommandHelper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/CommandHelper.cs
deleted file mode 100644 (file)
index 0e773f5..0000000
+++ /dev/null
@@ -1,34 +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.Data.SqlClient;
-using System.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals
-{
-    internal static class CommandHelper
-    {
-        private static Type s_sqlCommand = typeof(SqlCommand);
-        private static MethodInfo s_completePendingReadWithSuccess = s_sqlCommand.GetMethod("CompletePendingReadWithSuccess", BindingFlags.NonPublic | BindingFlags.Instance);
-        private static MethodInfo s_completePendingReadWithFailure = s_sqlCommand.GetMethod("CompletePendingReadWithFailure", BindingFlags.NonPublic | BindingFlags.Instance);
-        private static PropertyInfo s_debugForceAsyncWriteDelay = s_sqlCommand.GetProperty("DebugForceAsyncWriteDelay", BindingFlags.NonPublic | BindingFlags.Static);
-
-        internal static void CompletePendingReadWithSuccess(SqlCommand command, bool resetForcePendingReadsToWait)
-        {
-            s_completePendingReadWithSuccess.Invoke(command, new object[] { resetForcePendingReadsToWait });
-        }
-
-        internal static void CompletePendingReadWithFailure(SqlCommand command, int errorCode, bool resetForcePendingReadsToWait)
-        {
-            s_completePendingReadWithFailure.Invoke(command, new object[] { errorCode, resetForcePendingReadsToWait });
-        }
-
-        internal static int ForceAsyncWriteDelay
-        {
-            get { return (int)s_debugForceAsyncWriteDelay.GetValue(null); }
-            set { s_debugForceAsyncWriteDelay.SetValue(null, value); }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/ConnectionHelper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/ConnectionHelper.cs
deleted file mode 100644 (file)
index 28399f6..0000000
+++ /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.Reflection;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals
-{
-    internal static class ConnectionHelper
-    {
-        private static Assembly s_systemDotData = Assembly.Load(new AssemblyName(typeof(SqlConnection).GetTypeInfo().Assembly.FullName));
-        private static Type s_sqlConnection = s_systemDotData.GetType("System.Data.SqlClient.SqlConnection");
-        private static Type s_sqlInternalConnection = s_systemDotData.GetType("System.Data.SqlClient.SqlInternalConnection");
-        private static Type s_sqlInternalConnectionTds = s_systemDotData.GetType("System.Data.SqlClient.SqlInternalConnectionTds");
-        private static Type s_dbConnectionInternal = s_systemDotData.GetType("System.Data.ProviderBase.DbConnectionInternal");
-        private static PropertyInfo s_sqlConnectionInternalConnection = s_sqlConnection.GetProperty("InnerConnection", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static PropertyInfo s_dbConnectionInternalPool = s_dbConnectionInternal.GetProperty("Pool", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static MethodInfo s_dbConnectionInternalIsConnectionAlive = s_dbConnectionInternal.GetMethod("IsConnectionAlive", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static FieldInfo s_sqlInternalConnectionTdsParser = s_sqlInternalConnectionTds.GetField("_parser", BindingFlags.Instance | BindingFlags.NonPublic);
-
-        public static object GetConnectionPool(object internalConnection)
-        {
-            VerifyObjectIsInternalConnection(internalConnection);
-            return s_dbConnectionInternalPool.GetValue(internalConnection, null);
-        }
-
-        public static object GetInternalConnection(this SqlConnection connection)
-        {
-            object internalConnection = s_sqlConnectionInternalConnection.GetValue(connection, null);
-            Debug.Assert(((internalConnection != null) && (s_dbConnectionInternal.IsInstanceOfType(internalConnection))), "Connection provided has an invalid internal connection");
-            return internalConnection;
-        }
-
-
-        public static bool IsConnectionAlive(object internalConnection)
-        {
-            VerifyObjectIsInternalConnection(internalConnection);
-            return (bool)s_dbConnectionInternalIsConnectionAlive.Invoke(internalConnection, new object[] { false });
-        }
-
-        private static void VerifyObjectIsInternalConnection(object internalConnection)
-        {
-            if (internalConnection == null)
-                throw new ArgumentNullException(nameof(internalConnection));
-            if (!s_dbConnectionInternal.IsInstanceOfType(internalConnection))
-                throw new ArgumentException("Object provided was not a DbConnectionInternal", "internalConnection");
-        }
-
-        public static object GetParser(object internalConnection)
-        {
-            VerifyObjectIsInternalConnection(internalConnection);
-            return s_sqlInternalConnectionTdsParser.GetValue(internalConnection);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/ConnectionPoolHelper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/ConnectionPoolHelper.cs
deleted file mode 100644 (file)
index abb6d36..0000000
+++ /dev/null
@@ -1,134 +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.Concurrent;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals
-{
-    internal static class ConnectionPoolHelper
-    {
-        private static Assembly s_systemDotData = Assembly.Load(new AssemblyName(typeof(SqlConnection).GetTypeInfo().Assembly.FullName));
-        private static Type s_dbConnectionPool = s_systemDotData.GetType("System.Data.ProviderBase.DbConnectionPool");
-        private static Type s_dbConnectionPoolGroup = s_systemDotData.GetType("System.Data.ProviderBase.DbConnectionPoolGroup");
-        private static Type s_dbConnectionPoolIdentity = s_systemDotData.GetType("System.Data.ProviderBase.DbConnectionPoolIdentity");
-        private static Type s_dbConnectionFactory = s_systemDotData.GetType("System.Data.ProviderBase.DbConnectionFactory");
-        private static Type s_sqlConnectionFactory = s_systemDotData.GetType("System.Data.SqlClient.SqlConnectionFactory");
-        private static Type s_dbConnectionPoolKey = s_systemDotData.GetType("System.Data.Common.DbConnectionPoolKey");
-        private static Type s_dictStringPoolGroup = typeof(Dictionary<,>).MakeGenericType(s_dbConnectionPoolKey, s_dbConnectionPoolGroup);
-        private static Type s_dictPoolIdentityPool = typeof(ConcurrentDictionary<,>).MakeGenericType(s_dbConnectionPoolIdentity, s_dbConnectionPool);
-        private static PropertyInfo s_dbConnectionPoolCount = s_dbConnectionPool.GetProperty("Count", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static PropertyInfo s_dictStringPoolGroupGetKeys = s_dictStringPoolGroup.GetProperty("Keys");
-        private static PropertyInfo s_dictPoolIdentityPoolValues = s_dictPoolIdentityPool.GetProperty("Values");
-        private static FieldInfo s_dbConnectionFactoryPoolGroupList = s_dbConnectionFactory.GetField("_connectionPoolGroups", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static FieldInfo s_dbConnectionPoolGroupPoolCollection = s_dbConnectionPoolGroup.GetField("_poolCollection", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static FieldInfo s_sqlConnectionFactorySingleton = s_sqlConnectionFactory.GetField("SingletonInstance", BindingFlags.Static | BindingFlags.Public);
-        private static FieldInfo s_dbConnectionPoolStackOld = s_dbConnectionPool.GetField("_stackOld", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static FieldInfo s_dbConnectionPoolStackNew = s_dbConnectionPool.GetField("_stackNew", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static MethodInfo s_dbConnectionPoolCleanup = s_dbConnectionPool.GetMethod("CleanupCallback", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static MethodInfo s_dictStringPoolGroupTryGetValue = s_dictStringPoolGroup.GetMethod("TryGetValue");
-
-        public static int CountFreeConnections(object pool)
-        {
-            VerifyObjectIsPool(pool);
-
-            ICollection oldStack = (ICollection)s_dbConnectionPoolStackOld.GetValue(pool);
-            ICollection newStack = (ICollection)s_dbConnectionPoolStackNew.GetValue(pool);
-
-            return (oldStack.Count + newStack.Count);
-        }
-
-        /// <summary>
-        /// Finds all connection pools
-        /// </summary>
-        /// <returns></returns>
-        public static List<Tuple<object, object>> AllConnectionPools()
-        {
-            List<Tuple<object, object>> connectionPools = new List<Tuple<object, object>>();
-            object factorySingleton = s_sqlConnectionFactorySingleton.GetValue(null);
-            object AllPoolGroups = s_dbConnectionFactoryPoolGroupList.GetValue(factorySingleton);
-            ICollection connectionPoolKeys = (ICollection)s_dictStringPoolGroupGetKeys.GetValue(AllPoolGroups, null);
-            foreach (var item in connectionPoolKeys)
-            {
-                object[] args = new object[] { item, null };
-                s_dictStringPoolGroupTryGetValue.Invoke(AllPoolGroups, args);
-                if (args[1] != null)
-                {
-                    object poolCollection = s_dbConnectionPoolGroupPoolCollection.GetValue(args[1]);
-                    IEnumerable poolList = (IEnumerable)(s_dictPoolIdentityPoolValues.GetValue(poolCollection));
-                    foreach (object pool in poolList)
-                    {
-                        connectionPools.Add(new Tuple<object, object>(pool, item));
-                    }
-                }
-            }
-
-            return connectionPools;
-        }
-
-        /// <summary>
-        /// Finds a connection pool based on a connection string
-        /// </summary>
-        /// <param name="connectionString"></param>
-        /// <returns></returns>
-        public static object ConnectionPoolFromString(string connectionString)
-        {
-            if (connectionString == null)
-                throw new ArgumentNullException(nameof(connectionString));
-
-            object pool = null;
-            object factorySingleton = s_sqlConnectionFactorySingleton.GetValue(null);
-            object AllPoolGroups = s_dbConnectionFactoryPoolGroupList.GetValue(factorySingleton);
-            object[] args = new object[] { connectionString, null };
-            bool found = (bool)s_dictStringPoolGroupTryGetValue.Invoke(AllPoolGroups, args);
-            if ((found) && (args[1] != null))
-            {
-                ICollection poolList = (ICollection)s_dictPoolIdentityPoolValues.GetValue(args[1]);
-                if (poolList.Count == 1)
-                {
-                    poolList.Cast<object>().First();
-                }
-                else if (poolList.Count > 1)
-                {
-                    throw new NotSupportedException("Using multiple identities with SSPI is not supported");
-                }
-            }
-
-            return pool;
-        }
-
-        /// <summary>
-        /// Causes the cleanup timer code in the connection pool to be invoked
-        /// </summary>
-        /// <param name="obj">A connection pool object</param>
-        internal static void CleanConnectionPool(object pool)
-        {
-            VerifyObjectIsPool(pool);
-            s_dbConnectionPoolCleanup.Invoke(pool, new object[] { null });
-        }
-
-        /// <summary>
-        /// Counts the number of connections in a connection pool
-        /// </summary>
-        /// <param name="pool">Pool to count connections in</param>
-        /// <returns></returns>
-        internal static int CountConnectionsInPool(object pool)
-        {
-            VerifyObjectIsPool(pool);
-            return (int)s_dbConnectionPoolCount.GetValue(pool, null);
-        }
-
-
-        private static void VerifyObjectIsPool(object pool)
-        {
-            if (pool == null)
-                throw new ArgumentNullException(nameof(pool));
-            if (!s_dbConnectionPool.IsInstanceOfType(pool))
-                throw new ArgumentException("Object provided was not a DbConnectionPool", "pool");
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/DataReaderHelper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/DataReaderHelper.cs
deleted file mode 100644 (file)
index 77a491c..0000000
+++ /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.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals
-{
-    internal static class DataReaderHelper
-    {
-        private static Type s_sqlDataReader = typeof(SqlDataReader);
-        private static MethodInfo s_completePendingReadWithSuccess = s_sqlDataReader.GetMethod("CompletePendingReadWithSuccess", BindingFlags.NonPublic | BindingFlags.Instance);
-        private static MethodInfo s_completePendingReadWithFailure = s_sqlDataReader.GetMethod("CompletePendingReadWithFailure", BindingFlags.NonPublic | BindingFlags.Instance);
-        private static FieldInfo s_defaultTimeoutMilliseconds = s_sqlDataReader.GetField("_defaultTimeoutMilliseconds", BindingFlags.NonPublic | BindingFlags.Instance);
-
-        private static PropertyInfo s_metaData = s_sqlDataReader.GetProperty("MetaData", BindingFlags.NonPublic | BindingFlags.Instance);
-
-        internal static void CompletePendingReadWithSuccess(SqlDataReader reader, bool resetForcePendingReadsToWait)
-        {
-            s_completePendingReadWithSuccess.Invoke(reader, new object[] { resetForcePendingReadsToWait });
-        }
-
-        internal static void CompletePendingReadWithFailure(SqlDataReader reader, int errorCode, bool resetForcePendingReadsToWait)
-        {
-            s_completePendingReadWithFailure.Invoke(reader, new object[] { errorCode, resetForcePendingReadsToWait });
-        }
-
-        internal static void SetDefaultTimeout(SqlDataReader reader, long milliseconds)
-        {
-            s_defaultTimeoutMilliseconds.SetValue(reader, milliseconds);
-        }
-
-        internal static bool IsLong(SqlDataReader reader, int row)
-        {
-            object schema = GetSchemaEntry<object>(reader, row, "metaType");
-            object islong = schema.GetType().GetMethod("IsLong").Invoke(schema, new object[] { null });
-            return (bool)islong;
-        }
-
-        internal static T GetSchemaEntry<T>(SqlDataReader reader, int row, string schemaEntry)
-        {
-            object[] metadataarray = GetMetaEntries(reader);
-            object schema = metadataarray[row].GetType().GetField(schemaEntry).GetValue(metadataarray[row]);
-
-            return (T)schema;
-        }
-
-        internal static object[] GetMetaEntries(SqlDataReader reader)
-        {
-            object metadatas = s_metaData.GetValue(reader);
-            object metadataarray = metadatas.GetType().GetField("metaDataArray").GetValue(metadatas);
-
-            return (object[])metadataarray;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserHelper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserHelper.cs
deleted file mode 100644 (file)
index ee13abb..0000000
+++ /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.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals
-{
-    internal static class TdsParserHelper
-    {
-        private static Assembly s_systemDotData = Assembly.Load(new AssemblyName(typeof(SqlConnection).GetTypeInfo().Assembly.FullName));
-        private static Type s_tdsParser = s_systemDotData.GetType("System.Data.SqlClient.TdsParser");
-        private static FieldInfo s_tdsParserPhysicalStateObject = s_tdsParser.GetField("_physicalStateObj", BindingFlags.Instance | BindingFlags.NonPublic);
-
-        private static void VerifyObjectIsTdsParser(object parser)
-        {
-            if (parser == null)
-                throw new ArgumentNullException("stateObject");
-            if (!s_tdsParser.IsInstanceOfType(parser))
-                throw new ArgumentException("Object provided was not a DbConnectionInternal", "internalConnection");
-        }
-
-        internal static object GetStateObject(object parser)
-        {
-            VerifyObjectIsTdsParser(parser);
-            return s_tdsParserPhysicalStateObject.GetValue(parser);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserStateObjectHelper.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserStateObjectHelper.cs
deleted file mode 100644 (file)
index 54b60d4..0000000
+++ /dev/null
@@ -1,67 +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.Reflection;
-
-namespace System.Data.SqlClient.ManualTesting.Tests.SystemDataInternals
-{
-    internal static class TdsParserStateObjectHelper
-    {
-        private static Assembly s_systemDotData = typeof(System.Data.SqlClient.SqlConnection).GetTypeInfo().Assembly;
-        private static Type s_tdsParserStateObject = s_systemDotData.GetType("System.Data.SqlClient.TdsParserStateObject");
-        private static Type s_tdsParserStateObjectNative = s_systemDotData.GetType("System.Data.SqlClient.TdsParserStateObjectNative");
-        private static FieldInfo s_forceAllPends = s_tdsParserStateObject.GetField("_forceAllPends", BindingFlags.Static | BindingFlags.NonPublic);
-        private static FieldInfo s_skipSendAttention = s_tdsParserStateObject.GetField("_skipSendAttention", BindingFlags.Static | BindingFlags.NonPublic);
-        private static FieldInfo s_forceSyncOverAsyncAfterFirstPend = s_tdsParserStateObject.GetField("_forceSyncOverAsyncAfterFirstPend", BindingFlags.Static | BindingFlags.NonPublic);
-        private static FieldInfo s_failAsyncPends = s_tdsParserStateObject.GetField("_failAsyncPends", BindingFlags.Static | BindingFlags.NonPublic);
-        private static FieldInfo s_forcePendingReadsToWaitForUser = s_tdsParserStateObject.GetField("_forcePendingReadsToWaitForUser", BindingFlags.Static | BindingFlags.NonPublic);
-        private static FieldInfo s_tdsParserStateObjectNativeSessionHandle = s_tdsParserStateObjectNative.GetField("_sessionHandle", BindingFlags.Instance | BindingFlags.NonPublic);
-        private static Type s_tdsParserStateObjectManaged = s_systemDotData.GetType("System.Data.SqlClient.SNI.TdsParserStateObjectManaged");
-        private static FieldInfo s_tdsParserStateObjectManagedSessionHandle = s_tdsParserStateObjectManaged.GetField("_sessionHandle", BindingFlags.Instance | BindingFlags.NonPublic);
-
-        internal static bool ForceAllPends
-        {
-            get { return (bool)s_forceAllPends.GetValue(null); }
-            set { s_forceAllPends.SetValue(null, value); }
-        }
-
-        internal static bool SkipSendAttention
-        {
-            get { return (bool)s_skipSendAttention.GetValue(null); }
-            set { s_skipSendAttention.SetValue(null, value); }
-        }
-
-        internal static bool ForceSyncOverAsyncAfterFirstPend
-        {
-            get { return (bool)s_forceSyncOverAsyncAfterFirstPend.GetValue(null); }
-            set { s_forceSyncOverAsyncAfterFirstPend.SetValue(null, value); }
-        }
-
-        internal static bool ForcePendingReadsToWaitForUser
-        {
-            get { return (bool)s_forcePendingReadsToWaitForUser.GetValue(null); }
-            set { s_forcePendingReadsToWaitForUser.SetValue(null, value); }
-        }
-
-        internal static bool FailAsyncPends
-        {
-            get { return (bool)s_failAsyncPends.GetValue(null); }
-            set { s_failAsyncPends.SetValue(null, value); }
-        }
-
-        private static void VerifyObjectIsTdsParserStateObject(object stateObject)
-        {
-            if (stateObject == null)
-                throw new ArgumentNullException(nameof(stateObject));
-            if (!s_tdsParserStateObjectManaged.IsInstanceOfType(stateObject))
-                throw new ArgumentException("Object provided was not a DbConnectionInternal", "internalConnection");
-        }
-
-        internal static object GetSessionHandle(object stateObject)
-        {
-            VerifyObjectIsTdsParserStateObject(stateObject);
-            return s_tdsParserStateObjectManagedSessionHandle.GetValue(stateObject);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/ConnectionPoolTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/ConnectionPoolTest.cs
deleted file mode 100644 (file)
index a6edea5..0000000
+++ /dev/null
@@ -1,252 +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.Threading.Tasks;
-using System.Threading;
-using System.Runtime.ExceptionServices;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ConnectionPoolTest
-    {
-        private static readonly string _tcpConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = false, Pooling = true }).ConnectionString;
-        private static readonly string _tcpMarsConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true, Pooling = true }).ConnectionString;
-
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ConnectionPool_NonMars()
-        {
-            RunDataTestForSingleConnString(_tcpConnStr);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ConnectionPool_Mars()
-        {
-            RunDataTestForSingleConnString(_tcpMarsConnStr);
-        }
-
-        private static void RunDataTestForSingleConnString(string tcpConnectionString)
-        {
-            BasicConnectionPoolingTest(tcpConnectionString);
-            ClearAllPoolsTest(tcpConnectionString);
-            ReclaimEmancipatedOnOpenTest(tcpConnectionString);
-
-            if (DataTestUtility.IsUsingManagedSNI())
-            {
-                KillConnectionTest(tcpConnectionString);
-            }
-        }
-
-        /// <summary>
-        /// Tests that using the same connection string results in the same pool\internal connection and a different string results in a different pool\internal connection
-        /// </summary>
-        /// <param name="connectionString"></param>
-        private static void BasicConnectionPoolingTest(string connectionString)
-        {
-            SqlConnection connection = new SqlConnection(connectionString);
-            connection.Open();
-            InternalConnectionWrapper internalConnection = new InternalConnectionWrapper(connection);
-            ConnectionPoolWrapper connectionPool = new ConnectionPoolWrapper(connection);
-            connection.Close();
-
-            SqlConnection connection2 = new SqlConnection(connectionString);
-            connection2.Open();
-            Assert.True(internalConnection.IsInternalConnectionOf(connection2), "New connection does not use same internal connection");
-            Assert.True(connectionPool.ContainsConnection(connection2), "New connection is in a different pool");
-            connection2.Close();
-
-            SqlConnection connection3 = new SqlConnection(connectionString + ";App=SqlConnectionPoolUnitTest;");
-            connection3.Open();
-            Assert.False(internalConnection.IsInternalConnectionOf(connection3), "Connection with different connection string uses same internal connection");
-            Assert.False(connectionPool.ContainsConnection(connection3), "Connection with different connection string uses same connection pool");
-            connection3.Close();
-
-            connectionPool.Cleanup();
-            SqlConnection connection4 = new SqlConnection(connectionString);
-
-            connection4.Open();
-            Assert.True(internalConnection.IsInternalConnectionOf(connection4), "New connection does not use same internal connection");
-            Assert.True(connectionPool.ContainsConnection(connection4), "New connection is in a different pool");
-            connection4.Close();
-        }
-
-        /// <summary>
-        /// Tests if killing the connection using the InternalConnectionWrapper is working
-        /// </summary>
-        /// <param name="connectionString"></param>
-        private static void KillConnectionTest(string connectionString)
-        {
-#if DEBUG
-            InternalConnectionWrapper wrapper = null;
-
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                wrapper = new InternalConnectionWrapper(connection);
-
-                using (SqlCommand command = new SqlCommand("SELECT 5;", connection))
-                {
-                    DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result.");
-                }
-
-                wrapper.KillConnection();
-            }
-
-            using (SqlConnection connection2 = new SqlConnection(connectionString))
-            {
-                connection2.Open();
-                Assert.False(wrapper.IsInternalConnectionOf(connection2), "New connection has internal connection that was just killed");
-                using (SqlCommand command = new SqlCommand("SELECT 5;", connection2))
-                {
-                    DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result.");
-                }
-            }
-#endif
-        }
-
-        /// <summary>
-        /// Tests if clearing all of the pools does actually remove the pools
-        /// </summary>
-        /// <param name="connectionString"></param>
-        private static void ClearAllPoolsTest(string connectionString)
-        {
-            SqlConnection.ClearAllPools();
-            Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools");
-
-            SqlConnection connection = new SqlConnection(connectionString);
-            connection.Open();
-            ConnectionPoolWrapper pool = new ConnectionPoolWrapper(connection);
-            connection.Close();
-            ConnectionPoolWrapper[] allPools = ConnectionPoolWrapper.AllConnectionPools();
-            DataTestUtility.AssertEqualsWithDescription(1, allPools.Length, "Incorrect number of pools exist.");
-            Assert.True(allPools[0].Equals(pool), "Saved pool is not in the list of all pools");
-            DataTestUtility.AssertEqualsWithDescription(1, pool.ConnectionCount, "Saved pool has incorrect number of connections");
-
-            SqlConnection.ClearAllPools();
-            Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools");
-            DataTestUtility.AssertEqualsWithDescription(0, pool.ConnectionCount, "Saved pool has incorrect number of connections.");
-        }
-
-        /// <summary>
-        /// Checks if an 'emancipated' internal connection is reclaimed when a new connection is opened AND we hit max pool size
-        /// NOTE: 'emancipated' means that the internal connection's SqlConnection has fallen out of scope and has no references, but was not explicitly disposed\closed
-        /// </summary>
-        /// <param name="connectionString"></param>
-        private static void ReclaimEmancipatedOnOpenTest(string connectionString)
-        {
-            string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 1 }).ConnectionString;
-            SqlConnection.ClearAllPools();
-
-            InternalConnectionWrapper internalConnection = CreateEmancipatedConnection(newConnectionString);
-            ConnectionPoolWrapper connectionPool = internalConnection.ConnectionPool;
-            GC.Collect();
-            GC.WaitForPendingFinalizers();
-
-            DataTestUtility.AssertEqualsWithDescription(1, connectionPool.ConnectionCount, "Wrong number of connections in the pool.");
-            DataTestUtility.AssertEqualsWithDescription(0, connectionPool.FreeConnectionCount, "Wrong number of free connections in the pool.");
-
-            using (SqlConnection connection = new SqlConnection(newConnectionString))
-            {
-                connection.Open();
-                Assert.True(internalConnection.IsInternalConnectionOf(connection), "Connection has wrong internal connection");
-                Assert.True(connectionPool.ContainsConnection(connection), "Connection is in wrong connection pool");
-            }
-        }
-
-        private static void ReplacementConnectionUsesSemaphoreTest(string connectionString)
-        {
-            string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 2, ConnectTimeout = 5 }).ConnectionString;
-            SqlConnection.ClearAllPools();
-
-            SqlConnection liveConnection = new SqlConnection(newConnectionString);
-            SqlConnection deadConnection = new SqlConnection(newConnectionString);
-            liveConnection.Open();
-            deadConnection.Open();
-            InternalConnectionWrapper deadConnectionInternal = new InternalConnectionWrapper(deadConnection);
-            InternalConnectionWrapper liveConnectionInternal = new InternalConnectionWrapper(liveConnection);
-            deadConnectionInternal.KillConnection();
-            deadConnection.Close();
-            liveConnection.Close();
-
-            Task<InternalConnectionWrapper>[] tasks = new Task<InternalConnectionWrapper>[3];
-            Barrier syncBarrier = new Barrier(tasks.Length);
-            Func<InternalConnectionWrapper> taskFunction = (() => ReplacementConnectionUsesSemaphoreTask(newConnectionString, syncBarrier));
-            for (int i = 0; i < tasks.Length; i++)
-            {
-                tasks[i] = Task.Factory.StartNew<InternalConnectionWrapper>(taskFunction);
-            }
-
-
-            bool taskWithLiveConnection = false;
-            bool taskWithNewConnection = false;
-            bool taskWithCorrectException = false;
-
-            Task waitAllTask = Task.Factory.ContinueWhenAll(tasks, (completedTasks) =>
-            {
-                foreach (var item in completedTasks)
-                {
-                    if (item.Status == TaskStatus.Faulted)
-                    {
-                        // One task should have a timeout exception
-                        if ((!taskWithCorrectException) && (item.Exception.InnerException is InvalidOperationException) && (item.Exception.InnerException.Message.StartsWith(SystemDataResourceManager.Instance.ADP_PooledOpenTimeout)))
-                            taskWithCorrectException = true;
-                        else if (!taskWithCorrectException)
-                        {
-                            // Rethrow the unknown exception
-                            ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(item.Exception);
-                            exceptionInfo.Throw();
-                        }
-                    }
-                    else if (item.Status == TaskStatus.RanToCompletion)
-                    {
-                        // One task should get the live connection
-                        if (item.Result.Equals(liveConnectionInternal))
-                        {
-                            if (!taskWithLiveConnection)
-                                taskWithLiveConnection = true;
-                        }
-                        else if (!item.Result.Equals(deadConnectionInternal) && !taskWithNewConnection)
-                            taskWithNewConnection = true;
-                    }
-                    else
-                        Console.WriteLine("ERROR: Task in unknown state: {0}", item.Status);
-                }
-            });
-
-            waitAllTask.Wait();
-            Assert.True(taskWithLiveConnection && taskWithNewConnection && taskWithCorrectException, string.Format("Tasks didn't finish as expected.\nTask with live connection: {0}\nTask with new connection: {1}\nTask with correct exception: {2}\n", taskWithLiveConnection, taskWithNewConnection, taskWithCorrectException));
-        }
-
-        private static InternalConnectionWrapper ReplacementConnectionUsesSemaphoreTask(string connectionString, Barrier syncBarrier)
-        {
-            InternalConnectionWrapper internalConnection = null;
-
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                try
-                {
-                    connection.Open();
-                    internalConnection = new InternalConnectionWrapper(connection);
-                }
-                catch
-                {
-                    syncBarrier.SignalAndWait();
-                    throw;
-                }
-
-                syncBarrier.SignalAndWait();
-            }
-
-            return internalConnection;
-        }
-
-        private static InternalConnectionWrapper CreateEmancipatedConnection(string connectionString)
-        {
-            SqlConnection connection = new SqlConnection(connectionString);
-            connection.Open();
-            return new InternalConnectionWrapper(connection);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/PoolBlockPeriodTest.netcoreapp.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/PoolBlockPeriodTest.netcoreapp.cs
deleted file mode 100644 (file)
index a60c637..0000000
+++ /dev/null
@@ -1,164 +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.Threading;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class PoolBlockPeriodTest
-    {
-        private const string AzureEndpointSample = "nonexistent.database.windows.net";
-        private const string AzureChinaEnpointSample = "nonexistent.database.chinacloudapi.cn";
-        private const string AzureUSGovernmentEndpointSample = "nonexistent.database.usgovcloudapi.net";
-        private const string AzureGermanEndpointSample = "nonexistent.database.cloudapi.de";
-        private const string AzureEndpointMixedCaseSample = "nonexistent.database.WINDOWS.net";
-        private const string NonExistentServer = "nonexistentserver";
-        private const string PolicyKeyword = "PoolBlockingPeriod";
-        private const string PortNumber = "1234";
-        private const string InstanceName = "InstanceName";
-        private const int ConnectionTimeout = 15;
-        private const int CompareMargin = 2;
-
-        [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        [InlineData("Azure with Default Policy must Disable blocking (*.database.windows.net)", new object[] { AzureEndpointSample })]
-        [InlineData("Azure with Default Policy must Disable blocking (*.database.chinacloudapi.cn)", new object[] { AzureChinaEnpointSample })]
-        [InlineData("Azure with Default Policy must Disable blocking (*.database.usgovcloudapi.net)", new object[] { AzureUSGovernmentEndpointSample })]
-        [InlineData("Azure with Default Policy must Disable blocking (*.database.cloudapi.de)", new object[] { AzureGermanEndpointSample })]
-        [InlineData("Azure with Default Policy must Disable blocking (MIXED CASES) (*.database.WINDOWS.net)", new object[] { AzureEndpointMixedCaseSample })]
-        [InlineData("Azure with Default Policy must Disable blocking (PORT) (*.database.WINDOWS.net,1234)", new object[] { AzureEndpointMixedCaseSample + "," + PortNumber })]
-        [InlineData("Azure with Default Policy must Disable blocking (INSTANCE NAME) (*.database.WINDOWS.net,1234\\InstanceName)", new object[] { AzureEndpointMixedCaseSample + "," + PortNumber + "\\" + InstanceName })]
-        [InlineData("Azure with Auto Policy must Disable Blocking", new object[] { AzureEndpointSample, PoolBlockingPeriod.Auto })]
-        [InlineData("Azure with Always Policy must Enable Blocking", new object[] { AzureEndpointSample, PoolBlockingPeriod.AlwaysBlock })]
-        [InlineData("Azure with Never Policy must Disable Blocking", new object[] { AzureEndpointSample, PoolBlockingPeriod.NeverBlock })]
-        public void TestAzureBlockingPeriod(string description, object[] Params)
-        {
-            _ = description;
-            string serverName = Params[0] as string;
-            PoolBlockingPeriod? policy = null;
-            if (Params.Length > 1)
-            {
-                policy = (PoolBlockingPeriod)Params[1];
-            }
-
-            string connString = CreateConnectionString(serverName, policy);
-            PoolBlockingPeriodAzureTest(connString, policy);
-        }
-
-        [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        [InlineData("NonAzure with Default Policy must Enable blocking", new object[] { NonExistentServer })]
-        [InlineData("NonAzure with Auto Policy must Enable Blocking", new object[] { NonExistentServer, PoolBlockingPeriod.Auto })]
-        [InlineData("NonAzure with Always Policy must Enable Blocking", new object[] { NonExistentServer, PoolBlockingPeriod.AlwaysBlock })]
-        [InlineData("NonAzure with Never Policy must Disable Blocking", new object[] { NonExistentServer, PoolBlockingPeriod.NeverBlock })]
-        [InlineData("NonAzure (which contains azure endpoint - nonexistent.WINDOWS.net) with Default Policy must Enable Blocking", new object[] { "nonexistent.windows.net" })]
-        [InlineData("NonAzure (which contains azure endpoint - nonexistent.database.windows.net.else) with Default Policy must Enable Blocking", new object[] { "nonexistent.database.windows.net.else" })]
-        public void TestNonAzureBlockingPeriod(string description, object[] Params)
-        {
-            _ = description;
-            string serverName = Params[0] as string;
-            PoolBlockingPeriod? policy = null;
-
-            if (Params.Length > 1)
-            {
-                policy = (PoolBlockingPeriod)Params[1];
-            }
-
-            string connString = CreateConnectionString(serverName, policy);
-            PoolBlockingPeriodNonAzureTest(connString, policy);
-        }
-
-        [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        [InlineData("Test policy with Auto (lowercase)", "auto")]
-        [InlineData("Test policy with Auto (PascalCase)", "Auto")]
-        [InlineData("Test policy with Always (lowercase)", "alwaysblock")]
-        [InlineData("Test policy with Always (PascalCase)", "AlwaysBlock")]
-        [InlineData("Test policy with Never (lowercase)", "neverblock")]
-        [InlineData("Test policy with Never (PascalCase)", "NeverBlock")]
-        public void TestSetPolicyWithVariations(string description, string policyString)
-        {
-            _ = description;
-            PoolBlockingPeriod? policy = null;
-            if (policyString.ToLower().Contains("auto"))
-            {
-                policy = PoolBlockingPeriod.Auto;
-            }
-            else if (policyString.ToLower().Contains("always"))
-            {
-                policy = PoolBlockingPeriod.AlwaysBlock;
-            }
-            else
-            {
-                policy = PoolBlockingPeriod.NeverBlock;
-            }
-            string connString = $"{CreateConnectionString(AzureEndpointSample, null)};{PolicyKeyword}={policyString}";
-            PoolBlockingPeriodAzureTest(connString, policy);
-        }
-
-        private void PoolBlockingPeriodNonAzureTest(string connStr, PoolBlockingPeriod? policy)
-        {
-            int firstErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr);
-            int secondErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr);
-            switch (policy)
-            {
-                case PoolBlockingPeriod.Auto:
-                case PoolBlockingPeriod.AlwaysBlock:
-                    Assert.InRange(secondErrorTimeInSecs, 0, firstErrorTimeInSecs + CompareMargin);
-                    break;
-                case PoolBlockingPeriod.NeverBlock:
-                    Assert.InRange(secondErrorTimeInSecs, 1, 2 * ConnectionTimeout);
-                    break;
-            }
-        }
-
-        private void PoolBlockingPeriodAzureTest(string connStr, PoolBlockingPeriod? policy)
-        {
-            int firstErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr);
-            int secondErrorTimeInSecs = GetConnectionOpenTimeInSeconds(connStr);
-            switch (policy)
-            {
-                case PoolBlockingPeriod.AlwaysBlock:
-                    Assert.InRange(secondErrorTimeInSecs, 0, firstErrorTimeInSecs + CompareMargin);
-                    break;
-                case PoolBlockingPeriod.Auto:
-                case PoolBlockingPeriod.NeverBlock:
-                    Assert.InRange(secondErrorTimeInSecs, 1, 2 * ConnectionTimeout);
-                    break;
-            }
-        }
-
-        private int GetConnectionOpenTimeInSeconds(string connString)
-        {
-            using (SqlConnection conn = new SqlConnection(connString))
-            {
-                System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
-                try
-                {
-                    stopwatch.Start();
-                    conn.Open();
-                    throw new Exception("Connection Open must expect an exception");
-                }
-                catch (Exception)
-                {
-                    stopwatch.Stop();
-                }
-                return stopwatch.Elapsed.Seconds;
-            }
-        }
-
-        public string CreateConnectionString(string serverName, PoolBlockingPeriod? policy)
-        {
-            SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
-            connBuilder.DataSource = serverName;
-            connBuilder.UserID = "user";
-            connBuilder.Password = "password";
-            connBuilder.InitialCatalog = "test";
-            connBuilder.PersistSecurityInfo = true;
-            if (policy != null)
-            {
-                connBuilder.PoolBlockingPeriod = policy.Value;
-            }
-            return connBuilder.ToString();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/AADAccessTokenTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/AADAccessTokenTest.cs
deleted file mode 100644 (file)
index 9564bf4..0000000
+++ /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 Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class AADAccessTokenTest
-    {
-        private static bool IsAccessTokenSetup() => DataTestUtility.IsAccessTokenSetup();
-        private static bool IsAzureServer() => DataTestUtility.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TcpConnStr)).DataSource);
-
-        [ConditionalFact(nameof(IsAccessTokenSetup), nameof(IsAzureServer))]
-        public static void AccessTokenTest()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.AccessToken = DataTestUtility.getAccessToken();
-                connection.Open();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs
deleted file mode 100644 (file)
index e5f886e..0000000
+++ /dev/null
@@ -1,213 +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.Generic;
-using System.Diagnostics;
-using System.Threading;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ConnectivityParametersTest
-    {
-        private const string COL_PROGRAM_NAME = "ProgramName";
-        private const string COL_HOSTNAME = "HostName";
-        private static readonly string s_databaseName = "d_" + Guid.NewGuid().ToString().Replace('-', '_');
-        private static readonly string s_tableName = "Person";
-        private static readonly string s_connectionString = DataTestUtility.TcpConnStr;
-        private static readonly string s_dbConnectionString = new SqlConnectionStringBuilder(s_connectionString) { InitialCatalog = s_databaseName }.ConnectionString;
-        private static readonly string s_createDatabaseCmd = $"CREATE DATABASE {s_databaseName}";
-        private static readonly string s_createTableCmd = $"CREATE TABLE {s_tableName} (NAME NVARCHAR(40), AGE INT)";
-        private static readonly string s_alterDatabaseSingleCmd = $"ALTER DATABASE {s_databaseName} SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
-        private static readonly string s_alterDatabaseMultiCmd = $"ALTER DATABASE {s_databaseName} SET MULTI_USER WITH ROLLBACK IMMEDIATE;";
-        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))]
-        public static void EnvironmentHostNameTest()
-        {
-            SqlConnectionStringBuilder builder = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = true });
-            builder.ApplicationName = "HostNameTest";
-
-            using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString))
-            {
-                sqlConnection.Open();
-                using (SqlCommand command = new SqlCommand("sp_who2", sqlConnection))
-                {
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        while (reader.Read())
-                        {
-                            int programNameOrdinal = reader.GetOrdinal(COL_PROGRAM_NAME);
-                            string programName = reader.GetString(programNameOrdinal);
-
-                            if (programName != null && programName.Trim().Equals(builder.ApplicationName))
-                            {
-                                // Get the hostname
-                                int hostnameOrdinal = reader.GetOrdinal(COL_HOSTNAME);
-                                string hostnameFromServer = reader.GetString(hostnameOrdinal);
-                                string expectedMachineName = Environment.MachineName.ToUpper();
-                                string hostNameFromServer = hostnameFromServer.Trim().ToUpper();
-                                Assert.Matches(expectedMachineName, hostNameFromServer);
-                                return;
-                            }
-                        }
-                    }
-                }
-            }
-            Assert.True(false, "No non-empty hostname found for the application");
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ConnectionTimeoutTestWithThread()
-        {
-            const int timeoutSec = 5;
-            const int numOfTry = 2;
-            const int numOfThreads = 5;
-
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            builder.DataSource = "invalidhost";
-            builder.ConnectTimeout = timeoutSec;
-            string connStrNotAvailable = builder.ConnectionString;
-
-            for (int i = 0; i < numOfThreads; ++i)
-            {
-                new ConnectionWorker(connStrNotAvailable, numOfTry);
-            }
-
-            ConnectionWorker.Start();
-            ConnectionWorker.Stop();
-
-            double timeTotal = 0;
-            double timeElapsed = 0;
-
-            foreach (ConnectionWorker w in ConnectionWorker.WorkerList)
-            {
-                timeTotal += w.TimeElapsed;
-            }
-            timeElapsed = timeTotal / Convert.ToDouble(ConnectionWorker.WorkerList.Count);
-
-            int threshold = timeoutSec * numOfTry * 2 * 1000;
-
-            Assert.True(timeElapsed < threshold);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ProcessIdTest()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            string sqlProviderName = builder.ApplicationName;
-            string sqlProviderProcessID = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
-
-            using (SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString))
-            {
-                sqlConnection.Open();
-                string strCommand = $"SELECT PROGRAM_NAME,HOSTPROCESS FROM SYS.SYSPROCESSES WHERE PROGRAM_NAME LIKE ('%{sqlProviderName}%')";
-                using (SqlCommand command = new SqlCommand(strCommand, sqlConnection))
-                {
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        while (reader.Read())
-                        {
-                            Assert.Equal(sqlProviderName,reader.GetString(0).Trim());
-                            Assert.Equal(sqlProviderProcessID, reader.GetString(1).Trim());
-                        }
-                    }
-                }
-            }
-        }
-        public class ConnectionWorker
-        {
-            private static List<ConnectionWorker> workerList = new List<ConnectionWorker>();
-            private ManualResetEventSlim _doneEvent = new ManualResetEventSlim(false);
-            private double _timeElapsed;
-            private Thread _thread;
-            private string _connectionString;
-            private int _numOfTry;
-
-            public ConnectionWorker(string connectionString, int numOfTry)
-            {
-                workerList.Add(this);
-                _connectionString = connectionString;
-                _numOfTry = numOfTry;
-                _thread = new Thread(new ThreadStart(SqlConnectionOpen));
-            }
-
-            public static List<ConnectionWorker> WorkerList => workerList;
-
-            public double TimeElapsed => _timeElapsed;
-
-            public static void Start()
-            {
-                foreach (ConnectionWorker w in workerList)
-                {
-                    w._thread.Start();
-                }
-            }
-
-            public static void Stop()
-            {
-                foreach (ConnectionWorker w in workerList)
-                {
-                    w._doneEvent.Wait();
-                }
-            }
-
-            public void SqlConnectionOpen()
-            {
-                Stopwatch sw = new Stopwatch();
-                double totalTime = 0;
-                for (int i = 0; i < _numOfTry; ++i)
-                {
-                    using (SqlConnection con = new SqlConnection(_connectionString))
-                    {
-                        sw.Start();
-                        try
-                        {
-                            con.Open();
-                        }
-                        catch { }
-                        sw.Stop();
-                    }
-                    totalTime += sw.Elapsed.TotalMilliseconds;
-                    sw.Reset();
-                }
-
-                _timeElapsed = totalTime / Convert.ToDouble(_numOfTry);
-
-                _doneEvent.Set();
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ConnectionKilledTest()
-        {
-            try
-            {
-                // Setup Database and Table.
-                DataTestUtility.RunNonQuery(s_connectionString, s_createDatabaseCmd);
-                DataTestUtility.RunNonQuery(s_dbConnectionString, s_createTableCmd);
-
-                // Kill all the connections and set Database to SINGLE_USER Mode.
-                DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseSingleCmd);
-                // Set Database back to MULTI_USER Mode
-                DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseMultiCmd);
-
-                // Execute SELECT statement.
-                DataTestUtility.RunNonQuery(s_dbConnectionString, s_selectTableCmd);
-            }
-            catch (Exception ex)
-            {
-                Console.WriteLine($"Error: {ex.Message}");
-                Assert.Null(ex);
-            }
-            finally
-            {
-                // Kill all the connections, set Database to SINGLE_USER Mode and drop Database
-                DataTestUtility.RunNonQuery(s_connectionString, s_alterDatabaseSingleCmd);
-                DataTestUtility.RunNonQuery(s_connectionString, s_dropDatabaseCmd);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataBaseSchemaTest/ConnectionSchemaTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataBaseSchemaTest/ConnectionSchemaTest.cs
deleted file mode 100644 (file)
index be52d30..0000000
+++ /dev/null
@@ -1,53 +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.Generic;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ConnectionSchemaTest
-    {
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void GetAllTablesFromSchema()
-        {
-            VerifySchemaTable(SqlClientMetaDataCollectionNames.Tables, new string[] {"TABLE_CATALOG", "TABLE_SCHEMA", "TABLE_NAME", "TABLE_TYPE" });
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void GetAllProceduresFromSchema()
-        {
-            VerifySchemaTable(SqlClientMetaDataCollectionNames.Procedures, new string[] { "ROUTINE_SCHEMA", "ROUTINE_NAME", "ROUTINE_TYPE" });
-        }
-
-        private static void VerifySchemaTable(string schemaItemName, string[] testColumnNames)
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
-            {
-                InitialCatalog = "master"
-            };
-
-            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
-            {
-                // Connect to the database then retrieve the schema information.
-                connection.Open();
-                DataTable table = connection.GetSchema(schemaItemName);
-
-                // Display the contents of the table.
-                Assert.InRange<int>(table.Rows.Count, 1, int.MaxValue);
-
-                // Get all table columns
-                HashSet<string> columnNames = new HashSet<string>();
-
-                foreach (DataColumn column in table.Columns)
-                {
-                    columnNames.Add(column.ColumnName);
-                }
-
-                Assert.All<string>(testColumnNames, column => Assert.Contains<string>(column, columnNames));
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs
deleted file mode 100644 (file)
index 478f225..0000000
+++ /dev/null
@@ -1,151 +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.Generic;
-using System.Text;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DataReaderTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void LoadReaderIntoDataTableToTestGetSchemaTable()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                var dt = new DataTable();
-                using (SqlCommand command = connection.CreateCommand())
-                {
-                    command.CommandText = "select 3 as [three], 4 as [four]";
-                    // Datatables internally call IDataReader.GetSchemaTable()
-                    dt.Load(command.ExecuteReader());
-                    Assert.Equal(2, dt.Columns.Count);
-                    Assert.Equal("three", dt.Columns[0].ColumnName);
-                    Assert.Equal("four", dt.Columns[1].ColumnName);
-                    Assert.Equal(1, dt.Rows.Count);
-                    Assert.Equal(3, (int)dt.Rows[0][0]);
-                    Assert.Equal(4, (int)dt.Rows[0][1]);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MultiQuerySchema()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-
-                using (SqlCommand command = connection.CreateCommand())
-                {
-                    // Use multiple queries
-                    command.CommandText = "SELECT 1 as ColInteger;  SELECT 'STRING' as ColString";
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        HashSet<string> columnNames = new HashSet<string>();
-                        do
-                        {
-                            DataTable schemaTable = reader.GetSchemaTable();
-                            foreach (DataRow myField in schemaTable.Rows)
-                            {
-                                columnNames.Add(myField["ColumnName"].ToString());
-                            }
-
-                        } while (reader.NextResult());
-
-                        Assert.Contains("ColInteger", columnNames);
-                        Assert.Contains("ColString", columnNames);
-                    }
-                }
-            }
-        }
-
-
-        // Checks for the IsColumnSet bit in the GetSchemaTable for Sparse columns
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void CheckSparseColumnBit()
-        {
-            const int sparseColumns = 4095;
-            string tempTableName = "SparseColumnTable";
-
-            // TSQL for "CREATE TABLE" with sparse columns
-            // table name will be provided as an argument
-            StringBuilder createBuilder = new StringBuilder("CREATE TABLE {0} ([ID] int PRIMARY KEY, [CSET] xml COLUMN_SET FOR ALL_SPARSE_COLUMNS NULL");
-
-            // TSQL to create the same table, but without the column set column and without sparse
-            // also, it has only 1024 columns, which is the server limit in this case
-            StringBuilder createNonSparseBuilder = new StringBuilder("CREATE TABLE {0} ([ID] int PRIMARY KEY");
-
-            // TSQL to select all columns from the sparse table, without columnset one
-            StringBuilder selectBuilder = new StringBuilder("SELECT [ID]");
-
-            // TSQL to select all columns from the sparse table, with a limit of 1024 (for bulk-copy test)
-            StringBuilder selectNonSparseBuilder = new StringBuilder("SELECT [ID]");
-
-            // add sparse columns
-            for (int c = 0; c < sparseColumns; c++)
-            {
-                createBuilder.AppendFormat(", [C{0}] int SPARSE NULL", c);
-                selectBuilder.AppendFormat(", [C{0}]", c);
-            }
-
-            createBuilder.Append(")");
-            // table name provided as an argument
-            selectBuilder.Append(" FROM {0}");
-
-            string selectStatementFormat = selectBuilder.ToString();
-            string createStatementFormat = createBuilder.ToString();
-
-            // add a row with nulls only
-            using (SqlConnection con = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                con.Open();
-
-                SqlCommand cmd = con.CreateCommand();
-                cmd.CommandType = CommandType.Text;
-
-                cmd.CommandText = string.Format(createStatementFormat, tempTableName);
-                cmd.ExecuteNonQuery();
-
-                cmd.CommandText = string.Format("INSERT INTO {0} ([ID]) VALUES (0)", tempTableName);// insert row with values set to their defaults (DBNULL)
-                cmd.ExecuteNonQuery();
-
-                // run the test cases
-                Assert.True(IsColumnBitSet(con, string.Format("SELECT [ID], [CSET], [C1] FROM {0}", tempTableName), indexOfColumnSet: 1));
-
-                // drop the temp table to release its resources
-                cmd.CommandText = "DROP TABLE " + tempTableName;
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private static bool IsColumnBitSet(SqlConnection con, string selectQuery, int indexOfColumnSet)
-        {
-            bool columnSetPresent = false;
-            {
-                SqlCommand cmd = con.CreateCommand();
-                cmd.CommandText = selectQuery;
-
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTable schemaTable = reader.GetSchemaTable();
-
-                    for (int i = 0; i < schemaTable.Rows.Count; i++)
-                    {
-                        bool isColumnSet = (bool)schemaTable.Rows[i]["IsColumnSet"];
-
-                        if (indexOfColumnSet == i)
-                        {
-                            columnSetPresent = true;
-                        }
-                    }
-                }
-            }
-            return columnSetPresent;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs
deleted file mode 100644 (file)
index 2c1d473..0000000
+++ /dev/null
@@ -1,1973 +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.Data.SqlTypes;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DataStreamTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void RunAllTestsForSingleServer_NP()
-        {
-            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
-            {
-                DataTestUtility.AssertThrowsWrapper<PlatformNotSupportedException>(() => RunAllTestsForSingleServer(DataTestUtility.NpConnStr, true));
-            }
-            else
-            {
-                RunAllTestsForSingleServer(DataTestUtility.NpConnStr, true);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void RunAllTestsForSingleServer_TCP()
-        {
-            RunAllTestsForSingleServer(DataTestUtility.TcpConnStr);
-        }
-
-        private static void RunAllTestsForSingleServer(string connectionString, bool usingNamePipes = false)
-        {
-            RowBuffer(connectionString);
-            InvalidRead(connectionString);
-            VariantRead(connectionString);
-            TypeRead(connectionString);
-            SQLTypeRead(connectionString);
-            GetValueOfTRead(connectionString);
-            MultipleResults(connectionString);
-            NumericRead(connectionString);
-            TimestampRead(connectionString);
-            OrphanReader(connectionString);
-            BufferSize(connectionString);
-            ExecuteXmlReaderTest(connectionString);
-            SequentialAccess(connectionString);
-            HasRowsTest(connectionString);
-            CloseConnection(connectionString);
-            OpenConnection(connectionString);
-            SqlCharsBytesTest(connectionString);
-            GetStream(connectionString);
-            GetTextReader(connectionString);
-            GetXmlReader(connectionString);
-            ReadStream(connectionString);
-            ReadTextReader(connectionString);
-            StreamingBlobDataTypes(connectionString);
-            OutOfOrderGetChars(connectionString);
-            TestXEventsStreaming(connectionString);
-            // These tests fail with named pipes, since they try to do DNS lookups on named pipe paths.
-            if (!usingNamePipes)
-            {
-                if (DataTestUtility.IsUsingNativeSNI())
-                {
-                    TimeoutDuringReadAsyncWithClosedReaderTest(connectionString);
-                }
-                NonFatalTimeoutDuringRead(connectionString);
-            }
-        }
-
-        private static void MultipleResults(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                string query =
-                    "select orderid from orders where orderid < @id order by orderid;" +
-                    "set no_browsetable on set fmtonly on select * from shippers order by shipperid set fmtonly off;" +
-                    "select * from shippers order by shipperid;" +
-                    "select * from region order by regionid set no_browsetable off;" +
-                    "select lastname from employees order by lastname";
-
-                // Each array in the expectedResults is a separate query result
-                string[][] expectedResults =
-                {
-                    new string[] { "10248", "10249", "10250", "10251", "10252", "10253", "10254" }, // All separate rows
-                    new string[] { "" }, // Empty query result
-                    new string[]
-                    {
-                        "1", "Speedy Express", "(503) 555-9831",  // Query Row 1
-                        "2", "United Package", "(503) 555-3199",  // Query Row 2
-                        "3", "Federal Shipping", "(503) 555-9931" // Query Row 3
-                    },
-                    new string[]
-                    {
-                        "1", "Eastern                                           ", // Query Row 1
-                        "2", "Western                                           ", // Query Row 2
-                        "3", "Northern                                          ", // Query Row 3
-                        "4", "Southern                                          "  // Query Row 4
-                    },
-                    new string[] { "Buchanan", "Callahan", "Davolio", "Dodsworth", "Fuller", "King", "Leverling", "Peacock", "Suyama" } // All separate rows
-                };
-
-                using (SqlCommand cmd = new SqlCommand(query, conn))
-                {
-                    cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = 10255;
-                    using (SqlDataReader r1 = cmd.ExecuteReader())
-                    {
-                        int numBatches = 0;
-                        do
-                        {
-                            Assert.True(numBatches < expectedResults.Length, "ERROR: Received more batches than were expected.");
-                            object[] values = new object[r1.FieldCount];
-                            // Current "column" in expected row is (valuesChecked MOD FieldCount), since
-                            // expected rows for current batch are appended together for easy formatting
-                            int valuesChecked = 0;
-                            while (r1.Read())
-                            {
-                                r1.GetValues(values);
-
-                                for (int col = 0; col < values.Length; col++, valuesChecked++)
-                                {
-                                    Assert.True(valuesChecked < expectedResults[numBatches].Length, "ERROR: Received more results for this batch than was expected");
-                                    string expectedVal = expectedResults[numBatches][valuesChecked];
-                                    string actualVal = values[col].ToString();
-
-                                    DataTestUtility.AssertEqualsWithDescription(expectedVal, actualVal, "FAILED: Received a different value than expected.");
-                                }
-                            }
-                            numBatches++;
-                        } while (r1.NextResult());
-                    }
-                }
-            }
-        }
-
-        private static void InvalidRead(string connectionString)
-        {
-            using (SqlConnection c = new SqlConnection(connectionString))
-            {
-                c.Open();
-                string sqlBatch = "select * from orders where orderid < 10253";
-                using (SqlCommand cmd = new SqlCommand(sqlBatch, c))
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    string errorMessage = SystemDataResourceManager.Instance.SQL_InvalidRead;
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetInt32(0), errorMessage);
-                }
-            }
-        }
-
-        private static void VariantRead(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                string sqlBatch = "select * from orders where orderid < 10253";
-                using (SqlCommand cmd = new SqlCommand(sqlBatch, conn))
-                using (SqlDataReader rdr = cmd.ExecuteReader())
-                {
-                    rdr.Read();
-                    object v = null;
-
-                    DateTime d;
-                    decimal m;
-                    string s = null;
-                    int i;
-
-                    // read data out of buffer
-                    v = rdr.GetValue(0); i = (int)v;
-                    v = rdr.GetValue(1); s = v is DBNull ? null : (string)v;
-                    v = rdr.GetValue(2); i = (int)v;
-                    v = rdr.GetValue(3); d = (DateTime)v;
-                    v = rdr.GetValue(4); d = (DateTime)v;
-                    v = rdr.GetValue(5); d = (DateTime)v;
-                    v = rdr.GetValue(6); i = (int)v;
-                    v = rdr.GetValue(7); m = (decimal)v;
-                    v = rdr.GetValue(8); s = v is DBNull ? null : (string)v;
-                    v = rdr.GetValue(9); s = v is DBNull ? null : (string)v;
-                    v = rdr.GetValue(10); s = v is DBNull ? null : (string)v;
-                    v = rdr.GetValue(11); s = v is DBNull ? null : (string)v;
-                    v = rdr.GetValue(12); s = v is DBNull ? null : (string)v;
-                    v = rdr.GetValue(13); s = v is DBNull ? null : (string)v;
-
-                    DataTestUtility.AssertEqualsWithDescription("France", s.ToString(), "FAILED: Received incorrect last value.");
-                }
-            }
-        }
-
-        private static void TypeRead(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                string sqlBatch = "select * from orders where orderid < 10253";
-                using (SqlCommand cmd = new SqlCommand(sqlBatch, conn))
-                using (SqlDataReader rdr = cmd.ExecuteReader())
-                {
-                    rdr.Read();
-
-                    DateTime d;
-                    decimal m;
-                    string s = null;
-                    int i;
-
-                    // read data out of buffer
-                    i = rdr.GetInt32(0); //order id
-                    s = rdr.GetString(1); //customer id
-                    i = rdr.GetInt32(2); // employee id
-                    d = rdr.GetDateTime(3); //OrderDate
-                    d = rdr.GetDateTime(4); //RequiredDate
-                    d = rdr.GetDateTime(5); //ShippedDate;
-                    i = rdr.GetInt32(6); //ShipVia;
-                    m = rdr.GetDecimal(7); //Freight;
-                    s = rdr.GetString(8); //ShipName;
-                    s = rdr.GetString(9); //ShipAddres;
-                    s = rdr.GetString(10); //ShipCity;
-                                           // should get an exception here
-                    string errorMessage = SystemDataResourceManager.Instance.SqlMisc_NullValueMessage;
-                    DataTestUtility.AssertThrowsWrapper<SqlNullValueException>(() => rdr.GetString(11), errorMessage);
-
-                    s = rdr.GetString(12); //ShipPostalCode;
-                    s = rdr.GetString(13); //ShipCountry;
-                    DataTestUtility.AssertEqualsWithDescription("France", s.ToString(), "FAILED: Received incorrect last value.");
-                }
-            }
-        }
-
-        private static void GetValueOfTRead(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                string sqlBatch = "select *, CAST(N'<test>Hello, World</test>' AS XML), CAST(NULL AS XML) from orders where orderid < 10253 and shipregion is null";
-                using (SqlCommand cmd = new SqlCommand(sqlBatch, conn))
-                using (SqlDataReader rdr = cmd.ExecuteReader())
-                {
-                    string errorMessage = SystemDataResourceManager.Instance.SqlMisc_NullValueMessage;
-
-                    rdr.Read();
-                    // read data out of buffer
-                    rdr.GetFieldValue<int>(0); //order id
-                    rdr.GetFieldValue<string>(1); //customer id
-                    rdr.GetFieldValue<SqlInt32>(2); // employee id
-                    rdr.GetFieldValue<DateTime>(3); //OrderDate
-                    rdr.GetFieldValue<SqlDateTime>(4); //RequiredDate
-                    rdr.GetFieldValue<DateTime>(5); //ShippedDate;
-                    rdr.GetFieldValue<int>(6); //ShipVia;
-                    rdr.GetFieldValue<decimal>(7); //Freight;
-                    rdr.GetFieldValue<string>(8); //ShipName;
-                    rdr.GetFieldValue<SqlString>(9); //ShipAddres;
-                    rdr.IsDBNull(10);
-                    rdr.IsDBNull(10);
-                    rdr.GetFieldValue<string>(10); //ShipCity;
-                    // should get an exception here
-                    DataTestUtility.AssertThrowsWrapper<SqlNullValueException>(() => rdr.GetFieldValue<string>(11), errorMessage);
-                    rdr.IsDBNull(11);
-                    rdr.GetFieldValue<SqlString>(11);
-                    rdr.IsDBNull(11);
-                    rdr.IsDBNull(12);
-                    rdr.GetChars(12, 0, null, 0, 0);
-                    rdr.IsDBNull(12);
-                    rdr.GetFieldValue<INullable>(13);//ShipCountry;
-                    rdr.GetFieldValue<string>(14);
-                    DataTestUtility.AssertThrowsWrapper<SqlNullValueException>(() => rdr.GetFieldValue<string>(15), errorMessage);
-
-                    rdr.Read();
-                    // read data out of buffer
-                    rdr.GetFieldValueAsync<int>(0).Wait(); //order id
-                    rdr.GetFieldValueAsync<string>(1).Wait(); //customer id
-                    rdr.GetFieldValueAsync<SqlInt32>(2).Wait(); // employee id
-                    rdr.GetFieldValueAsync<DateTime>(3).Wait(); //OrderDate
-                    rdr.GetFieldValueAsync<SqlDateTime>(4).Wait(); //RequiredDate
-                    rdr.GetFieldValueAsync<DateTime>(5).Wait(); //ShippedDate;
-                    rdr.GetFieldValueAsync<int>(6).Wait(); //ShipVia;
-                    rdr.GetFieldValueAsync<decimal>(7).Wait(); //Freight;
-                    rdr.GetFieldValueAsync<string>(8).Wait(); //ShipName;
-                    rdr.GetFieldValueAsync<SqlString>(9).Wait(); //ShipAddres;
-                    Assert.False(rdr.IsDBNullAsync(10).Result, "FAILED: IsDBNull was true for a non-null value");
-                    rdr.GetFieldValueAsync<string>(10).Wait(); //ShipCity;
-                    // should get an exception here
-                    DataTestUtility.AssertThrowsWrapper<AggregateException, SqlNullValueException>(() => rdr.GetFieldValueAsync<string>(11).Wait(), innerExceptionMessage: errorMessage);
-                    Assert.True(rdr.IsDBNullAsync(11).Result, "FAILED: IsDBNull was false for a null value");
-
-                    rdr.IsDBNullAsync(11).Wait();
-                    rdr.GetFieldValueAsync<SqlString>(11).Wait();
-                    rdr.IsDBNullAsync(11).Wait();
-                    rdr.IsDBNullAsync(12).Wait();
-                    rdr.GetChars(12, 0, null, 0, 0);
-                    rdr.IsDBNullAsync(12).Wait();
-                    rdr.GetFieldValueAsync<INullable>(13).Wait(); //ShipCountry;
-                    rdr.GetFieldValue<SqlXml>(14);
-                    rdr.GetFieldValue<SqlXml>(15);
-                    rdr.GetFieldValue<SqlString>(14);
-                    rdr.GetFieldValue<SqlString>(15);
-                    rdr.GetFieldValue<XmlReader>(14);
-                    rdr.GetFieldValue<XmlReader>(15);
-                    rdr.GetFieldValueAsync<XmlReader>(14);
-                    rdr.GetFieldValueAsync<XmlReader>(15);
-
-                    rdr.Read();
-                    Assert.True(rdr.IsDBNullAsync(11).Result, "FAILED: IsDBNull was false for a null value");
-                }
-            }
-        }
-
-        private static void OutOfOrderGetChars(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-
-                string expectedFirstString = "Hello, World!";
-                string expectedSecondString = "Another string";
-
-                // NOTE: Must be non-Plp types (i.e. not MAX sized columns)
-                using (SqlCommand cmd = new SqlCommand("SELECT @r, @p", conn))
-                {
-                    cmd.Parameters.AddWithValue("r", expectedFirstString);
-                    cmd.Parameters.AddWithValue("p", expectedSecondString);
-
-                    // NOTE: Command behavior must NOT be sequential
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        char[] data = new char[20];
-                        reader.Read();
-
-                        // Read last column - this will read in all intermediate columns
-                        reader.GetValue(1);
-
-                        // Read in first column with GetChars
-                        // Since we've haven't called GetChars yet, this caches the value of the column into _columnDataChars
-                        long charsRead = reader.GetChars(0, 0, data, 0, data.Length);
-                        string actualFirstString = new string(data, 0, (int)charsRead);
-
-                        // Now read in the second column
-                        charsRead = reader.GetChars(1, 0, data, 0, data.Length);
-                        string actualSecondString = new string(data, 0, (int)charsRead);
-
-                        // Validate data
-                        DataTestUtility.AssertEqualsWithDescription(expectedFirstString, actualFirstString, "FAILED: First string did not match");
-                        DataTestUtility.AssertEqualsWithDescription(expectedSecondString, actualSecondString, "FAILED: Second string did not match");
-                    }
-                }
-            }
-        }
-
-        private static void SQLTypeRead(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select * from orders where orderid < 10253", conn))
-                using (SqlDataReader rdr = cmd.ExecuteReader())
-                {
-                    rdr.Read();
-
-                    SqlDateTime d;
-                    SqlMoney m;
-                    SqlString s = null;
-                    SqlInt32 i;
-
-                    // read data out of buffer
-                    i = rdr.GetSqlInt32(0); //order id
-                    s = rdr.GetSqlString(1); //customer id
-                    i = rdr.GetSqlInt32(2); // employee id
-                    d = rdr.GetSqlDateTime(3); //OrderDate
-                    d = rdr.GetSqlDateTime(4); //RequiredDate
-                    d = rdr.GetSqlDateTime(5); //ShippedDate;
-                    i = rdr.GetSqlInt32(6); //ShipVia;
-                    m = rdr.GetSqlMoney(7); //Freight;
-                    s = rdr.GetSqlString(8); //ShipName;
-                    s = rdr.GetSqlString(9); //ShipAddres;
-                    s = rdr.GetSqlString(10); //ShipCity;
-                    s = rdr.GetSqlString(11); //ShipRegion;
-                    s = rdr.GetSqlString(12); //ShipPostalCode;
-                    s = rdr.GetSqlString(13); //ShipCountry;
-                    DataTestUtility.AssertEqualsWithDescription("France", s.ToString(), "FAILED: Received incorrect last value.");
-                }
-            }
-        }
-
-        private static void RowBuffer(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select * from orders where orderid < 10253", conn))
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    int cRecords = 0;
-                    object[] buffer = new object[reader.FieldCount];
-                    while (reader.Read())
-                    {
-                        reader.GetValues(buffer);
-
-                        if (cRecords == 0)
-                        {
-                            VerifySchema(reader);
-                        }
-
-                        VerifyData(reader, buffer);
-                        cRecords++;
-                    }
-                    DataTestUtility.AssertEqualsWithDescription(5, cRecords, "FAILED: Received incorrect number of records");
-                }
-            }
-        }
-
-        private static void TimestampRead(string connectionString)
-        {
-            string tempTable = "##" + Environment.GetEnvironmentVariable("ComputerName") + Environment.TickCount.ToString();
-            tempTable = tempTable.Replace('-', '_');
-
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmdDefault = new SqlCommand("", conn))
-                {
-                    cmdDefault.CommandText = "create table " + tempTable + "(c1 int, c2 timestamp)";
-                    cmdDefault.ExecuteNonQuery();
-
-                    cmdDefault.CommandText = "insert into " + tempTable + "(c1) values (1)";
-                    cmdDefault.ExecuteNonQuery();
-
-                    cmdDefault.CommandText = "select * from " + tempTable;
-                    using (SqlDataReader reader = cmdDefault.ExecuteReader())
-                    {
-                        DataTestUtility.AssertEqualsWithDescription("timestamp", reader.GetDataTypeName(1), "FAILED: Data value did not have correct type");
-                        reader.Read();
-
-                        object o = reader[1];
-
-                        // timestamps are really 8-byte binary
-                        byte[] b = (byte[])o;
-                        DataTestUtility.AssertEqualsWithDescription(8, b.Length, "FAILED: Retrieved byte array had incorrect length");
-
-                        SqlBinary sqlBin = reader.GetSqlBinary(1);
-                        b = sqlBin.Value;
-                        DataTestUtility.AssertEqualsWithDescription(8, b.Length, "FAILED: Retrieved SqlBinary value had incorrect length");
-                    }
-                }
-            }
-        }
-
-
-        private static void BufferSize(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select * from orders where orderid<@id", conn))
-                {
-                    cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = 10252;
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        // smaller buffer
-                        object[] buf_small = new object[3];
-                        // bigger buffer
-                        object[] buf_big = new object[reader.FieldCount + 10];
-                        object[] buf = buf_small;
-                        while (reader.Read())
-                        {
-                            // alternate buffers
-                            reader.GetValues(buf);
-                            string bufEntry1 = (string)buf[1];
-                            reader.GetSqlValues(buf);
-                            SqlString bufEntry2 = ((SqlString)buf[1]).Value;
-
-                            Assert.True(bufEntry1.Equals(bufEntry2.ToString()),
-                                string.Format("FAILED: Should have same value with both buffer entries. Buf2 value: {0}. Buf2 value: {1}", bufEntry1, bufEntry2));
-
-                            buf = (buf == buf_small) ? buf_big : buf_small;
-                        }
-                    }
-                }
-            }
-        }
-
-        private static void OrphanReader(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select * from orders where orderid < 10253", conn))
-                {
-                    object value;
-                    SqlDataReader reader;
-                    using (reader = cmd.ExecuteReader())
-                    {
-                        conn.Close();
-                        Assert.True(reader.IsClosed, "FAILED: Stream was not closed by connection close (Scenario: No Read)");
-                    }
-
-                    string errorMessage;
-                    conn.Open();
-                    using (reader = cmd.ExecuteReader())
-                    {
-                        reader.Read();
-                        conn.Close();
-
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "CheckDataIsReady");
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => value = reader[0], errorMessage);
-                        Assert.True(reader.IsClosed, "FAILED: Stream was not closed by connection close (Scenario: Read)");
-                        conn.Open();
-                    }
-
-                    using (reader = cmd.ExecuteReader())
-                    {
-                        reader.Read();
-                        value = reader[0];
-                        conn.Close();
-
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => value = reader[0], errorMessage);
-                        Assert.True(reader.IsClosed, "FAILED: Stream was not closed by connection close (Scenario: Read Partial Data)");
-                        conn.Open();
-                    }
-
-                    using (reader = cmd.ExecuteReader())
-                    {
-                        do
-                        {
-                            while (reader.Read())
-                            {
-                                for (int i = 0; i < reader.FieldCount; i++)
-                                {
-                                    value = reader[i];
-                                }
-                            }
-                        } while (reader.NextResult());
-
-                        conn.Close();
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => value = reader[0], errorMessage);
-                        Assert.True(reader.IsClosed, "FAILED: Stream was not closed by connection close (Scenario: Read All Data)");
-                    }
-                }
-            }
-        }
-
-        private static void ExecuteXmlReaderTest(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select employeeId, lastname, firstname from employees for xml auto", conn))
-                {
-                    XmlReader xr;
-                    using (xr = cmd.ExecuteXmlReader())
-                    {
-                        string[] expectedResults =
-                        {
-                            "<employees employeeId=\"1\" lastname=\"Davolio\" firstname=\"Nancy\" />",
-                            "<employees employeeId=\"2\" lastname=\"Fuller\" firstname=\"Andrew\" />",
-                            "<employees employeeId=\"3\" lastname=\"Leverling\" firstname=\"Janet\" />",
-                            "<employees employeeId=\"4\" lastname=\"Peacock\" firstname=\"Margaret\" />",
-                            "<employees employeeId=\"5\" lastname=\"Buchanan\" firstname=\"Steven\" />",
-                            "<employees employeeId=\"6\" lastname=\"Suyama\" firstname=\"Michael\" />",
-                            "<employees employeeId=\"7\" lastname=\"King\" firstname=\"Robert\" />",
-                            "<employees employeeId=\"8\" lastname=\"Callahan\" firstname=\"Laura\" />",
-                            "<employees employeeId=\"9\" lastname=\"Dodsworth\" firstname=\"Anne\" />",
-                        };
-
-                        xr.Read();
-                        for (int i = 0; !xr.EOF; i++)
-                        {
-                            Assert.True(i < expectedResults.Length, "ERROR: Received more XML results than expected");
-
-                            string actualResult = xr.ReadOuterXml();
-                            DataTestUtility.AssertEqualsWithDescription(expectedResults[i], actualResult, "FAILED: Actual XML results differed from expected value.");
-                        }
-                    }
-
-                    // use a big result to fill up the pipe and do a partial read
-                    cmd.CommandText = "select * from orders for xml auto";
-                    string errorMessage;
-                    using (xr = cmd.ExecuteXmlReader())
-                    {
-                        xr.Read();
-
-                        // make sure we get an exception if we try to get another reader
-                        errorMessage = SystemDataResourceManager.Instance.ADP_OpenReaderExists;
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => xr = cmd.ExecuteXmlReader(), errorMessage);
-                    }
-
-                    // use a big result to fill up the pipe and do a partial read
-                    cmd.CommandText = "select * from orders for xml auto";
-                    using (xr = cmd.ExecuteXmlReader())
-                    {
-                        xr.Read();
-                        conn.Close();
-                        conn.Open();
-                    }
-
-                    // read a large xml input, should succeed
-                    cmd.CommandText = "select * from orders for xml auto";
-                    using (xr = cmd.ExecuteXmlReader())
-                    {
-                        xr.Read();
-                        while (!xr.EOF)
-                        {
-                            xr.ReadOuterXml();
-                        }
-                    }
-
-                    // read an empty xml output, should succeed
-                    cmd.CommandText = "select * from orders where 0 = 1 for xml auto";
-                    using (xr = cmd.ExecuteXmlReader())
-                    {
-                        xr.Read();
-                        while (!xr.EOF)
-                        {
-                            xr.ReadOuterXml();
-                        }
-                    }
-
-                    // multiple results
-                    cmd.CommandText =
-                        "select orderid from orders where orderid < 10253 for xml auto;" +
-                        "select customerid from customers where customerid < 'ANTON' for xml auto;" +
-                        "select employeeId from employees where employeeid < 3 for xml auto;";
-                    using (xr = cmd.ExecuteXmlReader())
-                    {
-                        string[] expectedResults =
-                        {
-                            "<orders orderid=\"10248\" />",
-                            "<orders orderid=\"10249\" />",
-                            "<orders orderid=\"10250\" />",
-                            "<orders orderid=\"10251\" />",
-                            "<orders orderid=\"10252\" />",
-                            "<customers customerid=\"ALFKI\" />",
-                            "<customers customerid=\"ANATR\" />",
-                            "<employees employeeId=\"1\" />",
-                            "<employees employeeId=\"2\" />"
-                        };
-                        xr.Read();
-                        for (int i = 0; !xr.EOF; i++)
-                        {
-                            Assert.True(i < expectedResults.Length, "ERROR: Received more XML results than expected");
-
-                            string actualResult = xr.ReadOuterXml();
-                            DataTestUtility.AssertEqualsWithDescription(expectedResults[i], actualResult, "FAILED: Actual XML results differed from expected value.");
-                        }
-                    }
-
-                    // multiple columns
-                    cmd.CommandText = "select * from customers";
-                    errorMessage = SystemDataResourceManager.Instance.SQL_NonXmlResult;
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => xr = cmd.ExecuteXmlReader(), errorMessage);
-
-                    // non-ntext column
-                    cmd.CommandText = "select employeeID from employees";
-                    errorMessage = SystemDataResourceManager.Instance.SQL_NonXmlResult;
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => xr = cmd.ExecuteXmlReader(), errorMessage);
-                }
-            }
-        }
-
-        private static void SequentialAccess(string connectionString)
-        {
-            SqlDataReader reader;
-            string s;
-            int size = 4096; // some random chunk size
-            byte[] data = new byte[size];
-            char[] chars = new char[size];
-            long cb = 0;
-            long di = 0;
-            long cbTotal = 0;
-            object o;
-            int i;
-            SqlBinary sqlbin;
-
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select * from orders for xml auto", conn))
-                {
-                    // Simple reads
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        do
-                        {
-                            while (reader.Read())
-                            {
-                                s = reader.GetString(0);
-                                cbTotal += s.Length * 2;
-                            }
-                        } while (reader.NextResult());
-                    }
-                    DataTestUtility.AssertEqualsWithDescription((long)536198, cbTotal, "FAILED: cbTotal result did not have expected value");
-
-                    // Simple GetFieldValue<T>
-                    cbTotal = 0;
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        do
-                        {
-                            while (reader.Read())
-                            {
-                                s = reader.GetFieldValue<string>(0);
-                                cbTotal += s.Length * 2;
-                            }
-                        } while (reader.NextResult());
-                    }
-                    DataTestUtility.AssertEqualsWithDescription((long)536198, cbTotal, "FAILED: cbTotal result did not have expected value");
-
-                    // Simple GetFieldValueAsync<T>
-                    cbTotal = 0;
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        do
-                        {
-                            while (reader.Read())
-                            {
-                                s = reader.GetFieldValueAsync<string>(0).Result;
-                                cbTotal += s.Length * 2;
-                            }
-                        } while (reader.NextResult());
-                    }
-                    DataTestUtility.AssertEqualsWithDescription((long)536198, cbTotal, "FAILED: cbTotal result did not have expected value");
-
-                    // test sequential access reading everything
-                    cbTotal = 0;
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        do
-                        {
-                            while (reader.Read())
-                            {
-                                do
-                                {
-                                    cb = reader.GetBytes(0, di, data, 0, size);
-                                    di += cb;
-                                    cbTotal += cb;
-                                    if ((int)cb < size)
-                                        break;
-                                } while (cb > 0);
-                                di = 0;
-                            }
-                        } while (reader.NextResult());
-                    }
-                    DataTestUtility.AssertEqualsWithDescription((long)536198, cbTotal, "FAILED: cbTotal result did not have expected value");
-                }
-
-                // Test IsDBNull
-                using (SqlCommand cmd = new SqlCommand("select city, region from employees where region is null", conn))
-                {
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        reader.Read();
-                        Assert.False(reader.IsDBNull(0), "FAILED: IsDBNull is true for non-null value");
-                        Assert.True(reader.IsDBNull(1), "FAILED: IsDBNull is false for null value");
-
-                        reader.Read();
-                        Assert.False(reader.IsDBNullAsync(0).Result, "FAILED: IsDBNull is true for non-null value");
-                        Assert.True(reader.IsDBNullAsync(1).Result, "FAILED: IsDBNull is false for null value");
-                    }
-                }
-
-                using (SqlCommand cmd = new SqlCommand("select * from employees", conn))
-                {
-                    // test sequential access with partial reads
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        int currentCity = 0;
-                        int currentNote = 0;
-                        string[] expectedCities = { "Seattle", "Tacoma", "Kirkland", "Redmond", "London", "London", "London", "Seattle", "London" };
-                        string expectedPhotoBytes = "00 21 00 ff ff ff ff 42 69 74 6d 61 70 ";
-                        string[] expectedNotes =
-                        {
-                            "Education inclu", "Andrew received", "Janet has a BS ", "Margaret holds ",
-                            "Steven Buchanan", "Michael is a gr", "Robert King ser", "Laura received ", "Anne has a BA d"
-                        };
-
-                        while (reader.Read())
-                        {
-                            i = reader.GetOrdinal("City");
-                            o = reader.GetValue(i);
-                            DataTestUtility.AssertEqualsWithDescription(expectedCities[currentCity], o.ToString(), "FAILED: Received unexpected city value.");
-
-                            i = reader.GetOrdinal("photo");
-                            cb = reader.GetBytes(i, 13, data, 0, 13);
-                            StringBuilder byteBuilder = new StringBuilder();
-                            for (int j = 0; j < 13; j++)
-                            {
-                                byteBuilder.Append(data[j].ToString("x2") + " ");
-                            }
-                            DataTestUtility.AssertEqualsWithDescription(expectedPhotoBytes, byteBuilder.ToString(), "FAILED: Photo byte array did not contain correct values");
-
-                            i = reader.GetOrdinal("notes");
-                            cb = reader.GetChars(i, 0, chars, 0, 15);
-                            DataTestUtility.AssertEqualsWithDescription(expectedNotes[currentNote], new string(chars, 0, 15), "FAILED: Received unexpected city value.");
-
-                            currentCity++;
-                            currentNote++;
-                        }
-                    }
-
-                    // test GetSqlBinary special case
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        reader.Read();
-
-                        i = reader.GetOrdinal("photo");
-                        long actualLength = reader.GetBytes(i, 0, null, 0, 0);
-                        cb = reader.GetBytes(i, 0, data, 0, 13);
-                        sqlbin = reader.GetSqlBinary(i);
-                        DataTestUtility.AssertEqualsWithDescription((actualLength - 13), (long)sqlbin.Length, "FAILED: Did not receive expected number of bytes");
-                    }
-
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        // Tests GetBytes\Chars before GetValue
-                        reader.Read();
-                        i = reader.GetOrdinal("notes");
-                        reader.GetChars(i, 14, chars, 0, 14);
-                        string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, i, i + 1);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetString(i), errorMessage);
-
-                        // Tests GetValue before GetBytes\Chars
-                        reader.Read();
-                        i = reader.GetOrdinal("photo");
-                        reader.GetSqlBinary(i);
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, i, i + 1);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetBytes(i, 0, data, 0, 13), errorMessage);
-
-                        i = reader.GetOrdinal("notes");
-                        reader.GetString(i);
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, i, i + 1);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetChars(i, 0, chars, 0, 14), errorMessage);
-
-                        // Tests GetBytes\GetChars re-reading same characters
-                        reader.Read();
-                        i = reader.GetOrdinal("photo");
-                        reader.GetBytes(i, 0, data, 0, 13);
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSeqByteAccess, 0, 13, "GetBytes");
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetBytes(i, 0, data, 0, 13), errorMessage);
-
-                        i = reader.GetOrdinal("notes");
-                        reader.GetChars(i, 0, chars, 0, 14);
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSeqByteAccess, 0, 14, "GetChars");
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetChars(i, 0, chars, 0, 14), errorMessage);
-                    }
-
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        // exception tests
-                        reader.Read();
-                        object[] sqldata = new object[reader.FieldCount];
-                        reader.GetValues(sqldata); // should work
-
-                        int columnToTry = 0;
-                        string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, columnToTry, sqldata.Length);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetInt32(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetValue(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetFieldValue<int>(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetFieldValue<SqlInt32>(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => reader.GetFieldValueAsync<int>(columnToTry).Wait(), innerExceptionMessage: errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => reader.GetFieldValueAsync<SqlInt32>(columnToTry).Wait(), innerExceptionMessage: errorMessage);
-
-                        reader.Read();
-                        columnToTry = 17;
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_NonSequentialColumnAccess, columnToTry, sqldata.Length);
-
-                        s = reader.GetString(columnToTry);
-                        DataTestUtility.AssertEqualsWithDescription("http://accweb/emmployees/fuller.bmp", s, "FAILED: Did not receive expected string.");
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetInt32(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetValue(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetFieldValue<int>(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetFieldValue<SqlInt32>(columnToTry), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => reader.GetFieldValueAsync<int>(columnToTry).Wait(), innerExceptionMessage: errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => reader.GetFieldValueAsync<SqlInt32>(columnToTry).Wait(), innerExceptionMessage: errorMessage);
-
-                        reader.Read();
-                        // skip all columns up to photo, and read from it partially
-                        i = reader.GetOrdinal("photo");
-                        // partially read data (20 bytes from offset 50);
-                        cb = reader.GetBytes(i, 50, data, 0, 20);
-                        DataTestUtility.AssertEqualsWithDescription((long)20, cb, "FAILED: Did not receive expected number of bytes");
-                    }
-
-                    // close connection while in the middle of a read
-                    using (reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        reader.Read();
-                        i = reader.GetOrdinal("photo");
-                        cb = reader.GetBytes(i, 50, data, 0, 1);
-                        DataTestUtility.AssertEqualsWithDescription((long)1, cb, "FAILED: Did not receive expected number of bytes");
-                        conn.Close();
-
-                        // now try to read one more byte
-                        string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "GetBytes");
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => cb = reader.GetBytes(i, 51, data, 0, 1), errorMessage);
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "CheckDataIsReady");
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetValue(i), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetFieldValue<byte[]>(i), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetFieldValue<SqlBinary>(i), errorMessage);
-                        errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "GetFieldValueAsync");
-                        DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => reader.GetFieldValueAsync<byte[]>(i).Wait(), innerExceptionMessage: errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => reader.GetFieldValueAsync<SqlBinary>(i).Wait(), innerExceptionMessage: errorMessage);
-                    }
-                }
-            }
-        }
-
-        private static void NumericRead(string connectionString)
-        {
-            string tempTable = "##" + Environment.GetEnvironmentVariable("ComputerName") + Environment.TickCount.ToString();
-            tempTable = tempTable.Replace('-', '_');
-
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("", conn))
-                {
-                    cmd.CommandText = "create table " + tempTable + "(c1 sql_variant, c2 numeric(38,23))";
-                    cmd.ExecuteNonQuery();
-
-                    cmd.CommandText = "insert into " + tempTable + " values (convert(numeric(38,23), -123456789012345.67890123456789012345678), convert(numeric(38,23), -123456789012345.67890123456789012345678))";
-                    cmd.ExecuteNonQuery();
-
-                    cmd.CommandText = "select * from " + tempTable;
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        reader.Read();
-
-                        object o = reader.GetSqlValue(0);
-                        SqlDecimal n = reader.GetSqlDecimal(1);
-
-                        Assert.True(o is SqlDecimal, "FAILED: Query result was not a SqlDecimal value");
-                        DataTestUtility.AssertEqualsWithDescription("-123456789012345.67890123456789012345678", ((SqlDecimal)o).ToString(), "FAILED: SqlDecimal did not have expected value");
-                        DataTestUtility.AssertEqualsWithDescription("-123456789012345.67890123456789012345678", n.ToString(), "FAILED: SqlDecimal did not have expected value");
-
-                        // com+ type coercion should fail
-                        // Em
-                        object value;
-                        string errorMessage = SystemDataResourceManager.Instance.SqlMisc_ConversionOverflowMessage;
-                        DataTestUtility.AssertThrowsWrapper<OverflowException>(() => value = reader[0], errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<OverflowException>(() => value = reader[1], errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<OverflowException>(() => value = reader.GetDecimal(0), errorMessage);
-                        DataTestUtility.AssertThrowsWrapper<OverflowException>(() => value = reader.GetDecimal(1), errorMessage);
-                    }
-                }
-            }
-        }
-
-        private static void HasRowsTest(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                string sqlBatch =
-                    "select top 10 * from orders;" +
-                    "select top 5 * from orders;" +
-                    "select top 0 * from orders;";
-                using (SqlCommand cmd = new SqlCommand(sqlBatch, conn))
-                {
-                    SqlDataReader reader;
-                    using (reader = cmd.ExecuteReader())
-                    {
-                        Assert.True(reader.HasRows, "FAILED: Failure #1: HasRows");
-                        while (reader.Read())
-                        {
-                            Assert.True(reader.HasRows, "FAILED: Failure #2: HasRows");
-                        }
-                        Assert.True(reader.HasRows, "FAILED: Failure #3: HasRows");
-
-                        Assert.True(reader.NextResult(), "FAILED: Failure #3.5: NextResult");
-
-                        Assert.True(reader.HasRows, "FAILED: Failure #4: HasRows");
-                        while (reader.Read())
-                        {
-                            Assert.True(reader.HasRows, "FAILED: Failure #5: HasRows");
-                        }
-                        Assert.True(reader.HasRows, "FAILED: Failure #6: HasRows");
-
-                        Assert.True(reader.NextResult(), "FAILED: Failure #6.5: NextResult");
-
-                        Assert.False(reader.HasRows, "FAILED: Failure #7: HasRows");
-                        while (reader.Read())
-                        {
-                            Assert.False(reader.HasRows, "FAILED: Failure #8: HasRows");
-                        }
-                        Assert.False(reader.HasRows, "FAILED: Failure #9: HasRows");
-
-                        Assert.False(reader.NextResult(), "FAILED: Failure #9.5: NextResult");
-
-                        Assert.False(reader.HasRows, "FAILED: Failure #10: HasRows");
-                    }
-
-                    bool result;
-                    string errorMessage = string.Format(SystemDataResourceManager.Instance.ADP_DataReaderClosed, "HasRows");
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => result = reader.HasRows, errorMessage);
-                }
-            }
-        }
-
-        private static void SqlCharsBytesTest(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-
-                // select with SqlChars parameter
-                SqlCommand cmd;
-                SqlDataReader reader;
-                using (cmd = conn.CreateCommand())
-                {
-                    cmd.CommandText = "select EmployeeID, FirstName, LastName from Employees where Title = @vm ";
-
-                    (cmd.Parameters.Add("@vm", SqlDbType.VarChar)).Value = new SqlChars("Vice President, Sales");
-
-                    using (reader = cmd.ExecuteReader())
-                    {
-                        Assert.True(reader.Read(), "FAILED: No results were returned from read()");
-                        DataTestUtility.AssertEqualsWithDescription(2, reader.GetInt32(0), "FAILED: GetInt32(0) result did not match expected value");
-                        DataTestUtility.AssertEqualsWithDescription("Andrew", reader.GetString(1), "FAILED: GetString(1) result did not match expected value");
-                        DataTestUtility.AssertEqualsWithDescription("Fuller", reader.GetString(2), "FAILED: GetString(2) result did not match expected value");
-                    }
-                }
-
-                // select with SqlBytes parameter
-                using (cmd = conn.CreateCommand())
-                {
-                    cmd.CommandText = "select EmployeeID, FirstName, LastName from Employees where EmployeeID = 2 and Convert(binary(5), Photo) = @bn ";
-
-                    byte[] barr = new byte[5] { 0x15, 0x1c, 0x2F, 0x00, 0x02 };
-                    (cmd.Parameters.Add("@bn", SqlDbType.VarBinary)).Value = new SqlBytes(barr);
-
-                    using (reader = cmd.ExecuteReader())
-                    {
-                        Assert.True(reader.Read(), "FAILED: No results were returned from read()");
-                        DataTestUtility.AssertEqualsWithDescription(2, reader.GetInt32(0), "FAILED: GetInt32(0) result did not match expected value");
-                        DataTestUtility.AssertEqualsWithDescription("Andrew", reader.GetString(1), "FAILED: GetString(1) result did not match expected value");
-                        DataTestUtility.AssertEqualsWithDescription("Fuller", reader.GetString(2), "FAILED: GetString(2) result did not match expected value");
-                    }
-                }
-            }
-        }
-
-        private static void CloseConnection(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select * from orders where orderid < 10253", conn))
-                using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
-                {
-                    DataTestUtility.AssertEqualsWithDescription(ConnectionState.Open, conn.State, "FAILED: Connection should be in open state");
-
-                    while (reader.Read())
-                    {
-                        for (int i = 0; i < reader.FieldCount; i++)
-                        {
-                            reader.GetValue(i);
-                        }
-                    }
-                }
-
-                DataTestUtility.AssertEqualsWithDescription(ConnectionState.Closed, conn.State, "FAILED: Connection should be in closed state after reader close");
-            }
-        }
-
-        private static void OpenConnection(string connectionString)
-        {
-            // Isolates OpenConnection behavior for sanity testing on x-plat
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                DataTestUtility.AssertEqualsWithDescription(ConnectionState.Open, conn.State, "FAILED: Connection should be in open state");
-            }
-        }
-
-        private static void SeqAccessFailureWrapper<TException>(Action action, CommandBehavior behavior) where TException : Exception
-        {
-            if (behavior == CommandBehavior.SequentialAccess)
-                DataTestUtility.AssertThrowsWrapper<TException>(action);
-            else
-                action();
-        }
-
-        private static void GetStream(string connectionString)
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                using (SqlCommand cmd = new SqlCommand("SELECT 0x12341234, 0x12341234, 12, CAST(NULL AS VARBINARY(MAX)), 0x12341234, 0x12341234, 0x12341234, CAST(REPLICATE('a', 8000) AS VARBINARY(MAX)), 0x12341234", connection))
-                {
-                    CommandBehavior[] behaviors = new CommandBehavior[] { CommandBehavior.Default, CommandBehavior.SequentialAccess };
-                    foreach (CommandBehavior behavior in behaviors)
-                    {
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            byte[] buffer = new byte[9000];
-                            reader.Read();
-
-                            // Basic success paths
-                            reader.GetStream(0);
-                            reader.GetStream(1);
-
-                            // Bad values
-                            DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => reader.GetStream(2));
-                            // Null stream
-                            Stream stream = reader.GetStream(3);
-                            Assert.False(stream.Read(buffer, 0, buffer.Length) > 0, "FAILED: Read more than 0 bytes from a null stream");
-
-                            // Get column before current column
-                            Action action = (() => reader.GetStream(0));
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                            // Two streams on same column
-                            reader.GetStream(4);
-                            action = (() => reader.GetStream(4));
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                            // GetStream then GetBytes on same column
-                            reader.GetStream(5);
-                            action = (() => reader.GetBytes(5, 0, null, 0, 0));
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                            action = (() => reader.GetBytes(5, 0, buffer, 0, buffer.Length));
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                            // GetBytes then GetStream on same column
-                            reader.GetBytes(6, 0, null, 0, 0);
-                            action = (() => reader.GetStream(6));
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                            reader.GetBytes(6, 0, buffer, 0, buffer.Length);
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-#if DEBUG
-                            // GetStream while async is pending
-                            Task t = null;
-                            using (PendAsyncReadsScope pendScope = new PendAsyncReadsScope(reader))
-                            {
-                                t = reader.ReadAsync();
-                                Assert.False(t.Wait(1), "FAILED: Read completed immediately");
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetStream(8));
-                            }
-                            t.Wait();
-
-                            // GetStream after Read
-                            DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetStream(0));
-#endif
-                        }
-
-                        // IsDBNull + GetStream
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-                            reader.GetStream(8);
-                            // Past column
-                            reader.IsDBNull(8);
-                        }
-
-                        // IsDBNullAsync + GetStream
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-                            reader.GetStream(8);
-                            // Past column
-                            reader.IsDBNullAsync(8).Wait();
-                        }
-                    }
-#if DEBUG
-                    // Test GetStream is non-blocking
-                    using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                    {
-                        reader.Read();
-                        Task t = null;
-                        using (PendAsyncReadsScope pendScope = new PendAsyncReadsScope(reader))
-                        {
-                            t = Task.Factory.StartNew(() => reader.GetStream(8));
-                            t.Wait(1000);
-                            Assert.True(t.IsCompleted, "FAILED: Failed to get stream within 1 second");
-                            t = reader.ReadAsync();
-                        }
-                        t.Wait();
-                    }
-#endif
-                }
-            }
-        }
-
-        private static void GetTextReader(string connectionString)
-        {
-            string[] queryStrings =
-            {
-                "SELECT N'Hello World', N'Hello World', 12, CAST(NULL AS NVARCHAR(MAX)), N'Hello World', N'Hello World', N'Hello World', CAST(REPLICATE('a', 8000) AS NVARCHAR(MAX)), N'Hello World'",
-                "SELECT 'Hello World', 'Hello World', 12, CAST(NULL AS VARCHAR(MAX)), 'Hello World', 'Hello World', 'Hello World', CAST(REPLICATE('a', 8000) AS VARCHAR(MAX)), 'Hello World' COLLATE Latin1_General_CI_AS",
-                string.Format("SELECT {0} {1}, {0} {1}, 12, CAST(NULL AS VARCHAR(MAX)), {0} {1}, {0} {1}, {0} {1}, CAST(REPLICATE(('\uFF8A' {1}), 8000) AS VARCHAR(MAX)), {0} {1}", "'\uFF8A\uFF9B\uFF70\uFF9C\uFF70\uFF99\uFF84\uFF9E'", "COLLATE Japanese_CI_AS")
-            };
-
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                foreach (string query in queryStrings)
-                {
-                    using (SqlCommand cmd = new SqlCommand(query, connection))
-                    {
-                        CommandBehavior[] behaviors = new CommandBehavior[] { CommandBehavior.Default, CommandBehavior.SequentialAccess };
-                        foreach (CommandBehavior behavior in behaviors)
-                        {
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                char[] buffer = new char[9000];
-                                reader.Read();
-
-                                // Basic success paths
-                                reader.GetTextReader(0);
-                                reader.GetTextReader(1);
-
-                                // Bad values
-                                DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => reader.GetTextReader(2));
-                                // Null stream
-                                TextReader textReader = reader.GetTextReader(3);
-                                Assert.False(textReader.Read(buffer, 0, buffer.Length) > 0, "FAILED: Read more than 0 chars from a null TextReader");
-
-                                // Get column before current column
-                                Action action = (() => reader.GetTextReader(0));
-                                SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                                // Two TextReaders on same column
-                                reader.GetTextReader(4);
-                                action = (() => reader.GetTextReader(4));
-                                SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                                // GetTextReader then GetBytes on same column
-                                reader.GetTextReader(5);
-                                action = (() => reader.GetChars(0, 0, null, 0, 0));
-                                SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                                action = (() => reader.GetChars(5, 0, buffer, 0, buffer.Length));
-                                SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                                // GetBytes then GetTextReader on same column
-                                reader.GetChars(6, 0, null, 0, 0);
-                                action = (() => reader.GetTextReader(6));
-                                SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                                reader.GetChars(6, 0, buffer, 0, buffer.Length);
-                                SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-#if DEBUG
-                                // GetTextReader while async is pending
-                                Task t = null;
-                                using (PendAsyncReadsScope pendScope = new PendAsyncReadsScope(reader))
-                                {
-                                    t = reader.ReadAsync();
-                                    Assert.False(t.IsCompleted, "FAILED: Read completed immediately");
-                                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetTextReader(8));
-                                }
-                                t.Wait();
-
-                                // GetTextReader after Read
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetTextReader(0));
-#endif
-                            }
-
-                            // IsDBNull + GetTextReader
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                reader.GetTextReader(8);
-                                // Past column
-                                reader.IsDBNull(8);
-                            }
-
-                            // IsDBNullAsync + GetTextReader
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                reader.GetTextReader(8);
-                                // Past column
-                                reader.IsDBNullAsync(8).Wait();
-                            }
-                        }
-#if DEBUG
-                        // Test GetTextReader is non-blocking
-                        using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
-                        {
-                            reader.Read();
-
-                            Task t = null;
-                            using (PendAsyncReadsScope pendScope = new PendAsyncReadsScope(reader))
-                            {
-                                t = Task.Factory.StartNew(() => reader.GetTextReader(8));
-                                t.Wait(1000);
-                                Assert.True(t.IsCompleted, "FAILED: Failed to get TextReader within 1 second");
-                                t = reader.ReadAsync();
-                            }
-                            t.Wait();
-                        }
-#endif
-                    }
-                }
-            }
-        }
-
-        private static void GetXmlReader(string connectionString)
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                string xml = "CAST('<test><subtest /><subtest>asdfasdfasdf</subtest></test>' AS XML)";
-                string queryString = string.Format("SELECT {0}, {0}, 12, CAST(NULL AS XML), {0}, CAST(('<test>' + REPLICATE(CAST('a' AS VARCHAR(MAX)), 10000) + '</test>') AS XML), {0}", xml);
-                using (SqlCommand cmd = new SqlCommand(queryString, connection))
-                {
-                    CommandBehavior[] behaviors = new CommandBehavior[] { CommandBehavior.Default, CommandBehavior.SequentialAccess };
-                    foreach (CommandBehavior behavior in behaviors)
-                    {
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-
-                            // Basic success paths
-                            reader.GetXmlReader(0);
-                            reader.GetXmlReader(1);
-
-                            // Bad values
-                            DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => reader.GetXmlReader(2));
-                            // Null stream
-                            XmlReader xmlReader = reader.GetXmlReader(3);
-                            Assert.False(xmlReader.Read(), "FAILED: Successfully read on a null XmlReader");
-
-                            // Get column before current column
-                            Action action = (() => reader.GetXmlReader(0));
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-
-                            // Two XmlReaders on same column
-                            reader.GetXmlReader(4);
-                            action = (() => reader.GetXmlReader(4));
-                            SeqAccessFailureWrapper<InvalidOperationException>(action, behavior);
-#if DEBUG
-                            // GetXmlReader while async is pending
-                            Task t = null;
-                            using (PendAsyncReadsScope pendScope = new PendAsyncReadsScope(reader))
-                            {
-                                t = reader.ReadAsync();
-                                Assert.False(t.IsCompleted, "FAILED: Read completed immediately");
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetXmlReader(6));
-                            }
-                            t.Wait();
-
-                            // GetXmlReader after Read
-                            DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.GetXmlReader(0));
-#endif
-                        }
-                    }
-                }
-            }
-        }
-
-        private static void ReadStream(string connectionString)
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                CommandBehavior[] behaviors = new CommandBehavior[] { CommandBehavior.Default, CommandBehavior.SequentialAccess };
-                foreach (CommandBehavior behavior in behaviors)
-                {
-                    byte[] smallBuffer = new byte[2];
-                    byte[] buffer = new byte[16];
-                    byte[] largeBuffer = new byte[9000];
-                    Stream stream = null;
-                    Action action = null;
-                    using (SqlCommand cmd = new SqlCommand("SELECT 0x12341234", connection))
-                    {
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-                            // Basic case
-                            using (stream = reader.GetStream(0))
-                            {
-                                stream.Read(smallBuffer, 0, smallBuffer.Length);
-                                stream.Read(buffer, 2, 2);
-
-                                // Testing stream properties
-                                stream.Flush();
-                                DataTestUtility.AssertThrowsWrapper<NotSupportedException>(() => stream.SetLength(1));
-                                Action<Stream> performOnStream = ((s) => { int i = s.WriteTimeout; });
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => performOnStream(stream));
-                                if (behavior == CommandBehavior.SequentialAccess)
-                                {
-                                    DataTestUtility.AssertThrowsWrapper<NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin));
-                                    performOnStream = ((s) => { long i = s.Position; });
-                                    DataTestUtility.AssertThrowsWrapper<NotSupportedException>(() => performOnStream(stream));
-                                    performOnStream = ((s) => { long i = s.Length; });
-                                    DataTestUtility.AssertThrowsWrapper<NotSupportedException>(() => performOnStream(stream));
-                                }
-                                else
-                                {
-                                    stream.Seek(0, SeekOrigin.Begin);
-                                    long position = stream.Position;
-                                    long length = stream.Length;
-                                }
-                            }
-
-                            // Once Stream is closed
-                            DataTestUtility.AssertThrowsWrapper<ObjectDisposedException>(() => stream.Read(buffer, 0, buffer.Length));
-                        }
-
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-                            // Reading more than is there, and when there is nothing there
-                            stream = reader.GetStream(0);
-                            stream.Read(buffer, 0, buffer.Length);
-                            stream.Read(buffer, 0, buffer.Length);
-
-                            // Argument exceptions
-                            DataTestUtility.AssertThrowsWrapper<ArgumentNullException>(() => stream.Read(null, 0, 1));
-                            DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(() => stream.Read(buffer, -1, 2));
-                            DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(() => stream.Read(buffer, 2, -1));
-                            DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => stream.Read(buffer, buffer.Length, buffer.Length));
-                            DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => stream.Read(buffer, int.MaxValue, int.MaxValue));
-                        }
-
-                        // Once Reader is closed
-                        action = (() => stream.Read(buffer, 0, buffer.Length));
-                        SeqAccessFailureWrapper<ObjectDisposedException>(action, behavior);
-                    }
-
-                    using (SqlCommand cmd = new SqlCommand("SELECT 0x12341234, 12", connection))
-                    {
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-                            // Read after advancing reader
-                            stream = reader.GetStream(0);
-                            reader.GetInt32(1);
-
-                            action = (() => stream.Read(buffer, 0, buffer.Length));
-                            SeqAccessFailureWrapper<ObjectDisposedException>(action, behavior);
-                        }
-                    }
-
-                    if (behavior == CommandBehavior.SequentialAccess)
-                    {
-                        using (SqlCommand cmd = new SqlCommand("SELECT CAST(REPLICATE('a', 8000) AS VARBINARY(MAX)), CAST(REPLICATE('a', 8000) AS VARBINARY(MAX))", connection))
-                        {
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                // 0 byte read
-                                reader.Read();
-                                stream = reader.GetStream(1);
-                                stream.Read(largeBuffer, 0, 0);
-                            }
-#if DEBUG
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                stream = reader.GetStream(1);
-
-                                Task t = null;
-                                using (PendAsyncReadsScope debugScope = new PendAsyncReadsScope(reader))
-                                {
-                                    // Read during async
-                                    t = stream.ReadAsync(largeBuffer, 0, largeBuffer.Length);
-                                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => stream.Read(largeBuffer, 0, largeBuffer.Length));
-                                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.Read());
-                                }
-                                t.Wait();
-                            }
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                stream = reader.GetStream(0);
-                                stream.ReadTimeout = 20;
-                                Task t = null;
-
-                                using (PendAsyncReadsScope debugScope = new PendAsyncReadsScope(reader))
-                                {
-                                    // Timeout
-                                    t = stream.ReadAsync(largeBuffer, 0, largeBuffer.Length);
-                                    // Guarantee that timeout occurs:
-                                    Thread.Sleep(stream.ReadTimeout * 4);
-                                }
-                                DataTestUtility.AssertThrowsWrapper<AggregateException, IOException>(() => t.Wait());
-                            }
-
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                stream = reader.GetStream(1);
-                                Task t = null;
-                                using (PendAsyncReadsScope debugScope = new PendAsyncReadsScope(reader))
-                                {
-                                    // Cancellation
-                                    CancellationTokenSource tokenSource = new CancellationTokenSource();
-                                    t = stream.ReadAsync(largeBuffer, 0, largeBuffer.Length, tokenSource.Token);
-                                    tokenSource.Cancel();
-                                }
-                                DataTestUtility.AssertThrowsWrapper<AggregateException, TaskCanceledException>(() => t.Wait());
-                            }
-
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                stream = reader.GetStream(0);
-                                Task t = null;
-                                using (PendAsyncReadsScope debugScope = new PendAsyncReadsScope(reader, errorCode: 11))
-                                {
-                                    // Error during read
-                                    t = stream.ReadAsync(largeBuffer, 0, largeBuffer.Length);
-                                }
-                                DataTestUtility.AssertThrowsWrapper<AggregateException, IOException, SqlException>(() => t.Wait());
-                            }
-#endif
-                        }
-                    }
-                }
-            }
-        }
-
-        private static void ReadTextReader(string connectionString)
-        {
-            CommandBehavior[] behaviors = new CommandBehavior[] { CommandBehavior.Default, CommandBehavior.SequentialAccess };
-
-            // Some more complex unicode characters, including surrogate pairs
-            byte[] unicodeArray = { 0xFF, 0xDB, 0xFD, 0xDF, 0x34, 0xD8, 0xDD, 0xD8, 0x1E, 0xDC, 0x00, 0x6C, 0x00, 0x34 };
-            string unicodeString = System.Text.Encoding.Unicode.GetString(unicodeArray, 0, unicodeArray.Length);
-
-            foreach (CommandBehavior behavior in behaviors)
-            {
-                string[] correctStrings = {
-                    "CAST(('Hello world' COLLATE Latin1_General_CI_AS) AS VARCHAR(MAX))",
-                    string.Format("CAST(N'{0}Hello world' AS NVARCHAR(MAX))", unicodeString),
-                    "CAST((N'\uFF8A\uFF9B\uFF70\uFF9C\uFF70\uFF99\uFF84\uFF9E' COLLATE Japanese_CI_AS) AS VARCHAR(MAX))" };
-
-                foreach (string correctString in correctStrings)
-                {
-                    using (SqlConnection connection = new SqlConnection(connectionString))
-                    {
-                        connection.Open();
-                        char[] smallBuffer = new char[2];
-                        char[] buffer = new char[16];
-                        char[] largeBuffer = new char[9000];
-                        TextReader textReader = null;
-                        Action action = null;
-                        using (SqlCommand cmd = new SqlCommand(string.Format("SELECT {0}", correctString), connection))
-                        {
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                // Basic case
-                                using (textReader = reader.GetTextReader(0))
-                                {
-                                    textReader.Read();
-                                    textReader.Read(smallBuffer, 0, smallBuffer.Length);
-                                    textReader.Read(buffer, 2, 2);
-                                    textReader.Peek();
-                                    textReader.Read(buffer, 3, 2);
-                                    textReader.Peek();
-                                    textReader.Read();
-                                }
-
-                                // Once Reader is closed
-                                DataTestUtility.AssertThrowsWrapper<ObjectDisposedException>(() => textReader.Read(buffer, 0, buffer.Length));
-                            }
-
-                            using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                            {
-                                reader.Read();
-                                // Reading more than is there, and when there is nothing there
-                                textReader = reader.GetTextReader(0);
-                                textReader.Read(buffer, 0, buffer.Length);
-                                textReader.Read(buffer, 0, buffer.Length);
-                                textReader.Read();
-                                textReader.Peek();
-
-                                // Argument exceptions
-                                DataTestUtility.AssertThrowsWrapper<ArgumentNullException>(() => textReader.Read(null, 0, 1));
-                                DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(() => textReader.Read(buffer, -1, 2));
-                                DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(() => textReader.Read(buffer, 2, -1));
-                                DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => textReader.Read(buffer, buffer.Length, buffer.Length));
-                                DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => textReader.Read(buffer, int.MaxValue, int.MaxValue));
-                            }
-
-                            // Once Reader is closed
-                            action = (() => textReader.Read(buffer, 0, buffer.Length));
-                            SeqAccessFailureWrapper<ObjectDisposedException>(action, behavior);
-                        }
-
-                        using (SqlCommand cmd = new SqlCommand(string.Format("SELECT {0}, 12", correctString), connection))
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-                            // Read after advancing reader
-                            textReader = reader.GetTextReader(0);
-                            reader.GetInt32(1);
-
-                            action = (() => textReader.Read(buffer, 0, buffer.Length));
-                            SeqAccessFailureWrapper<ObjectDisposedException>(action, behavior);
-                        }
-
-                        if (behavior == CommandBehavior.SequentialAccess)
-                        {
-                            using (SqlCommand cmd = new SqlCommand(string.Format("SELECT REPLICATE({0}, 1500), REPLICATE({0}, 1500)", correctString), connection))
-                            {
-                                using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                                {
-                                    // 0 char read
-                                    reader.Read();
-                                    textReader = reader.GetTextReader(1);
-                                    textReader.Read(largeBuffer, 0, 0);
-                                }
-#if DEBUG
-                                using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                                {
-                                    reader.Read();
-                                    textReader = reader.GetTextReader(1);
-
-                                    Task t = null;
-                                    using (PendAsyncReadsScope debugScope = new PendAsyncReadsScope(reader))
-                                    {
-                                        // Read during async
-                                        t = textReader.ReadAsync(largeBuffer, 0, largeBuffer.Length);
-                                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => textReader.Read(largeBuffer, 0, largeBuffer.Length));
-                                        DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => reader.Read());
-                                    }
-                                    t.Wait();
-                                }
-
-                                using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                                {
-                                    reader.Read();
-                                    textReader = reader.GetTextReader(0);
-                                    Task t = null;
-                                    using (PendAsyncReadsScope debugScope = new PendAsyncReadsScope(reader, errorCode: 11))
-                                    {
-                                        // Error during read
-                                        t = textReader.ReadAsync(largeBuffer, 0, largeBuffer.Length);
-                                    }
-                                    DataTestUtility.AssertThrowsWrapper<AggregateException, IOException, SqlException>(() => t.Wait());
-                                }
-#endif
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        private static void StreamingBlobDataTypes(string connectionString)
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                CommandBehavior[] behaviors = new CommandBehavior[] { CommandBehavior.Default, CommandBehavior.SequentialAccess };
-                foreach (CommandBehavior behavior in behaviors)
-                {
-                    // GetStream
-                    byte[] correctBytes = { 0x12, 0x34, 0x56, 0x78 };
-                    string correctBytesAsString = "0x12345678";
-                    string queryString = string.Format("SELECT CAST({0} AS BINARY(20)), CAST({0} AS IMAGE), CAST({0} AS VARBINARY(20)), CAST({0} AS VARBINARY(MAX)), CAST({0} AS SQL_VARIANT)", correctBytesAsString);
-                    using (SqlCommand cmd = new SqlCommand(queryString, connection))
-                    using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                    {
-                        reader.Read();
-                        for (int i = 0; i < reader.FieldCount; i++)
-                        {
-                            byte[] buffer = new byte[256];
-                            Stream stream = reader.GetStream(i);
-                            int bytesRead = stream.Read(buffer, 0, buffer.Length);
-                            for (int j = 0; j < correctBytes.Length; j++)
-                            {
-                                DataTestUtility.AssertEqualsWithDescription(correctBytes[j], buffer[j], "FAILED: Bytes do not match");
-                            }
-                        }
-                    }
-
-                    // GetTextReader
-                    string[] correctStrings = { "Hello World", "\uFF8A\uFF9B\uFF70\uFF9C\uFF70\uFF99\uFF84\uFF9E" };
-                    string[] collations = { "Latin1_General_CI_AS", "Japanese_CI_AS" };
-
-                    for (int j = 0; j < collations.Length; j++)
-                    {
-                        string substring = string.Format("(N'{0}' COLLATE {1})", correctStrings[j], collations[j]);
-                        queryString = string.Format("SELECT CAST({0} AS CHAR(20)), CAST({0} AS NCHAR(20)), CAST({0} AS NTEXT), CAST({0} AS NVARCHAR(20)), CAST({0} AS NVARCHAR(MAX)), CAST({0} AS TEXT), CAST({0} AS NVARCHAR(20)), CAST({0} AS VARCHAR(MAX)), CAST({0} AS SQL_VARIANT)", substring);
-                        using (SqlCommand cmd = new SqlCommand(queryString, connection))
-                        using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                        {
-                            reader.Read();
-                            for (int i = 0; i < reader.FieldCount; i++)
-                            {
-                                char[] buffer = new char[256];
-                                TextReader textReader = reader.GetTextReader(i);
-                                int charsRead = textReader.Read(buffer, 0, buffer.Length);
-                                string stringRead = new string(buffer, 0, charsRead);
-                                DataTestUtility.AssertEqualsWithDescription(correctStrings[j], stringRead.TrimEnd(), "FAILED: Strings to not match");
-                            }
-                        }
-                    }
-
-                    // GetXmlReader
-                    string correctXml = "<test><subtest>asdf</subtest><subtest /></test>";
-                    byte[] correctXmlAsBytes = System.Text.Encoding.Unicode.GetBytes(correctXml);
-                    XmlReader correctXmlReader = XmlReader.Create(new StringReader(correctXml), new XmlReaderSettings() { ConformanceLevel = System.Xml.ConformanceLevel.Fragment, CloseInput = true });
-                    queryString = string.Format("SELECT CAST(N'{0}' AS XML)", correctXml);
-                    using (SqlCommand cmd = new SqlCommand(queryString, connection))
-                    using (SqlDataReader reader = cmd.ExecuteReader(behavior))
-                    {
-                        reader.Read();
-                        XmlReader xmlReader = reader.GetXmlReader(0);
-                        bool match = true;
-                        while ((match) && (xmlReader.Read()))
-                        {
-                            match = correctXmlReader.Read();
-                            if (match)
-                            {
-                                match &= (correctXmlReader.Name == xmlReader.Name);
-                                match &= (correctXmlReader.Value == xmlReader.Value);
-                            }
-                        }
-
-                        Assert.True(match, "FAILED: XmlReaders do not match");
-                    }
-                }
-            }
-        }
-
-        private static void VariantCollationsTest(string connectionString)
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                using (SqlCommand cmd = new SqlCommand())
-                {
-                    cmd.Connection = connection;
-
-                    // Setup japanese database
-                    cmd.CommandText = "USE master; IF EXISTS (SELECT * FROM sys.databases WHERE name='japaneseCollationTest') DROP DATABASE japaneseCollationTest; CREATE DATABASE japaneseCollationTest COLLATE Japanese_90_BIN;";
-                    cmd.ExecuteNonQuery();
-                    cmd.CommandText = "USE japaneseCollationTest; CREATE TABLE japaneseCollationTest.dbo.tVar (c1 SQL_VARIANT);INSERT INTO japaneseCollationTest.dbo.tVar VALUES (CAST(0xA6 AS VARCHAR(2)) COLLATE Japanese_90_bin);";
-                    cmd.ExecuteNonQuery();
-
-                    // Select the same string - once using japaneseCollationTest context and the second time using master context
-                    cmd.CommandText = "SELECT c1 FROM japaneseCollationTest.dbo.tVar;";
-                    connection.ChangeDatabase("japaneseCollationTest");
-                    string fromJapaneseDb = (string)cmd.ExecuteScalar();
-                    connection.ChangeDatabase("master");
-                    string fromMasterDb = (string)cmd.ExecuteScalar();
-
-                    Assert.True(fromJapaneseDb == fromMasterDb, "FAILED: Variant collations strings do not match");
-
-                    // drop japanese database
-                    cmd.CommandText = "USE master; DROP DATABASE japaneseCollationTest;";
-                }
-            }
-        }
-
-       private static void TestXEventsStreaming(string connectionString)
-        {
-            string sessionName = "xeventStreamTest";
-            //Create XEvent
-            SetupXevent(connectionString, sessionName);
-            Task.Factory.StartNew(() =>
-            {
-                // Read XEvents
-                int streamXeventCount = 3;
-                using (SqlConnection xEventsReadConnection = new SqlConnection(connectionString))
-                {
-                    xEventsReadConnection.Open();
-                    string xEventDataStreamCommand ="USE master; " + @"select [type], [data] from sys.fn_MSxe_read_event_stream ('" + sessionName + "',0)";
-                    using (SqlCommand cmd = new SqlCommand(xEventDataStreamCommand, xEventsReadConnection))
-                    {
-                        SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
-                        for (int i = 0; i < streamXeventCount && reader.Read(); i++)
-                        {
-                            Int32 colType = reader.GetInt32(0);
-                            int cb = (int)reader.GetBytes(1, 0, null, 0, 0);
-
-                            byte[] bytes = new byte[cb];
-                            long read = reader.GetBytes(1, 0, bytes, 0, cb);
-
-                            // Don't send data on the first read because there is already data in the buffer.
-                            // Don't send data on the last iteration. We will not be reading that data.
-                            if (i == 0 || i == streamXeventCount - 1) continue;
-
-                            using (SqlConnection xEventWriteConnection = new SqlConnection(connectionString))
-                            {
-                                xEventWriteConnection.Open();
-                                string xEventWriteCommandText = @"exec sp_trace_generateevent 90, N'Test2'";
-                                using (SqlCommand xEventWriteCommand = new SqlCommand(xEventWriteCommandText, xEventWriteConnection))
-                                {
-                                    xEventWriteCommand.ExecuteNonQuery();
-                                }
-                            }
-                        }
-                    }
-                }
-            }).Wait(10000);
-            //Delete XEvent
-            DeleteXevent(connectionString, sessionName);
-        }
-
-        private static void SetupXevent(string connectionString, string sessionName)
-        {
-            string xEventCreateAndStartCommandText = @"CREATE EVENT SESSION [" + sessionName + @"] ON SERVER
-                        ADD EVENT sqlserver.user_event(ACTION(package0.event_sequence))
-                        ADD TARGET package0.ring_buffer
-                        WITH (
-                            MAX_MEMORY=4096 KB,
-                            EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,
-                            MAX_DISPATCH_LATENCY=30 SECONDS,
-                            MAX_EVENT_SIZE=0 KB,
-                            MEMORY_PARTITION_MODE=NONE,
-                            TRACK_CAUSALITY=ON,
-                            STARTUP_STATE=OFF)
-
-                        ALTER EVENT SESSION [" + sessionName + "] ON SERVER STATE = START ";
-
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                using (SqlCommand createXeventSession = new SqlCommand(xEventCreateAndStartCommandText, connection))
-                {
-                    createXeventSession.ExecuteNonQuery();
-                }
-            }
-        }
-
-        private static void DeleteXevent(string connectionString, string sessionName)
-        {
-            string deleteXeventSessionCommand = @"IF EXISTS (select * from sys.server_event_sessions where name ='" + sessionName + "') DROP  EVENT SESSION [" + sessionName + "] ON SERVER";
-
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                using (SqlCommand deleteXeventSession = new SqlCommand(deleteXeventSessionCommand, connection))
-                {
-                    deleteXeventSession.ExecuteNonQuery();
-                }
-            }
-
-        }
-
-        private static void TimeoutDuringReadAsyncWithClosedReaderTest(string connectionString)
-        {
-            // Create the proxy
-            ProxyServer proxy = ProxyServer.CreateAndStartProxy(connectionString, out connectionString);
-            proxy.SimulatedPacketDelay = 100;
-            proxy.SimulatedOutDelay = true;
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(connectionString))
-                {
-                    // Start the command
-                    conn.Open();
-                    using (SqlCommand cmd = new SqlCommand("SELECT @p, @p, @p, @p, @p", conn))
-                    {
-                        cmd.CommandTimeout = 1;
-                        cmd.Parameters.AddWithValue("p", new string('a', 3000));
-                        using (SqlDataReader reader = cmd.ExecuteReader())
-                        {
-                            // Start reading, and then force a timeout
-                            Task<bool> task = reader.ReadAsync();
-                            proxy.PauseCopying();
-                            // Before the timeout occurs, but after ReadAsync has started waiting for a packet, close the reader
-                            Thread.Sleep(200);
-                            Task closeTask = Task.Run(() => reader.Dispose());
-
-                            // Wait for the task to see the timeout
-                            string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
-                            DataTestUtility.AssertThrowsWrapper<AggregateException, SqlException>(() => task.Wait(), innerExceptionMessage: errorMessage);
-                        }
-                    }
-                }
-                proxy.Stop();
-            }
-            catch (SqlException ex)
-            {
-                // In case of error, stop the proxy and dump its logs (hopefully this will help with debugging
-                proxy.Stop();
-                throw ex;
-            }
-        }
-
-        private static void NonFatalTimeoutDuringRead(string connectionString)
-        {
-            // Create the proxy
-            ProxyServer proxy = ProxyServer.CreateAndStartProxy(connectionString, out connectionString);
-            proxy.SimulatedPacketDelay = 100;
-            proxy.SimulatedOutDelay = true;
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(connectionString))
-                {
-                    // Start the command
-                    conn.Open();
-                    using (SqlCommand cmd = new SqlCommand("SELECT @p, @p, @p, @p, @p", conn))
-                    {
-                        cmd.CommandTimeout = 1;
-                        cmd.Parameters.AddWithValue("p", new string('a', 3000));
-                        using (SqlDataReader reader = cmd.ExecuteReader())
-                        {
-                            // Slow down packets and wait on ReadAsync
-                            proxy.SimulatedPacketDelay = 1500;
-                            reader.ReadAsync().Wait();
-
-                            // Allow proxy to copy at full speed again
-                            proxy.SimulatedOutDelay = false;
-                            reader.SetDefaultTimeout(30000);
-
-                            // Close will now observe the stored timeout error
-                            string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
-                            DataTestUtility.AssertThrowsWrapper<SqlException>(reader.Dispose, errorMessage);
-                        }
-                    }
-                }
-                proxy.Stop();
-            }
-            catch
-            {
-                // In case of error, stop the proxy and dump its logs (hopefully this will help with debugging
-                proxy.Stop();
-                throw;
-            }
-        }
-
-        internal static void VerifySchema(SqlDataReader reader)
-        {
-            string[] expectedColNames =
-            {
-                "OrderID", "CustomerID", "EmployeeID", "OrderDate", "RequiredDate", "ShippedDate", "ShipVia",
-                "Freight", "ShipName", "ShipAddress", "ShipCity", "ShipRegion", "ShipPostalCode", "ShipCountry"
-            };
-            string[] expectedColTypeNames =
-            {
-                "int", "nchar", "int", "datetime", "datetime", "datetime", "int",
-                "money", "nvarchar", "nvarchar", "nvarchar", "nvarchar", "nvarchar", "nvarchar"
-            };
-
-            for (int i = 0; i < reader.FieldCount; i++)
-            {
-                DataTestUtility.AssertEqualsWithDescription(expectedColNames[i], reader.GetName(i), "FAILED: Received incorrect column name in VerifySchema.");
-                DataTestUtility.AssertEqualsWithDescription(expectedColTypeNames[i], reader.GetDataTypeName(i), "FAILED: Received incorrect column type name in VerifySchema.");
-            }
-        }
-
-        private static bool Equal(object v1, object v2)
-        {
-            if (v1 is DBNull && v2 is DBNull)
-            {
-                return true;
-            }
-            return (v1.Equals(v2));
-        }
-
-        internal static void VerifyData(SqlDataReader reader, object[] buffer)
-        {
-            object value = null;
-
-            for (int i = 0; i < reader.FieldCount; i++)
-            {
-                value = reader.GetValue(i);
-                Assert.True(Equal(buffer[i], value),
-                    string.Format("FAILED: Buffer value and stream.GetValue(i, v) don't match. Buffer value: {0}. GetValue value: {1}.", buffer[i], value));
-
-                value = reader[i];
-                Assert.True(Equal(buffer[i], value),
-                    string.Format("FAILED: Buffer value and stream.this[i] don't match. Buffer value: {0}. this[i] value: {1}.", buffer[i], value));
-
-                value = reader[reader.GetName(i)];
-                Assert.True(Equal(buffer[i], value),
-                    string.Format("FAILED: Buffer value and stream.this[name] don't match. Buffer value: {0}. this[name] value: {1}.", buffer[i], value));
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DateTimeTest/DateTimeTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/DateTimeTest/DateTimeTest.cs
deleted file mode 100644 (file)
index 947da98..0000000
+++ /dev/null
@@ -1,544 +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.Data.SqlTypes;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DateTimeTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void SQLBU503165Test()
-        {
-            SqlParameter p = new SqlParameter();
-            p.SqlValue = new DateTime(1200, 1, 1);
-            p.SqlDbType = SqlDbType.DateTime2;
-
-            DateTime expectedValue = new DateTime(1200, 1, 1);
-            Assert.True(p.Value.Equals(expectedValue), "FAILED: Value did not match expected DateTime value");
-            Assert.True(p.SqlValue.Equals(expectedValue), "FAILED: SqlValue did not match expected DateTime value");
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void SQLBU527900Test()
-        {
-            object chs = new char[] { 'a', 'b', 'c' };
-
-            SqlCommand command = new SqlCommand();
-            SqlParameter parameter = command.Parameters.AddWithValue("@o", chs);
-
-            Assert.True(parameter.Value is char[], "FAILED: Expected parameter value to be char[]");
-            Assert.True(parameter.SqlValue is SqlChars, "FAILED: Expected parameter value to be SqlChars");
-            Assert.True(parameter.SqlValue is SqlChars, "FAILED: Expected parameter value to be SqlChars");
-            Assert.True(parameter.Value is char[], "FAILED: Expected parameter value to be char[]");
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void SQLBU503290Test()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                conn.Open();
-                SqlParameter p = new SqlParameter("@p", SqlDbType.DateTimeOffset);
-                p.Value = DBNull.Value;
-                p.Size = 27;
-                SqlCommand cmd = conn.CreateCommand();
-                cmd.CommandText = "SELECT @p";
-                cmd.Parameters.Add(p);
-
-                Assert.True(cmd.ExecuteScalar() is DBNull, "FAILED: ExecuteScalar did not return a result of type DBNull");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ReaderParameterTest()
-        {
-            string tempTable = "#t_" + Guid.NewGuid().ToString().Replace('-', '_');
-            string tempProc = "#p_" + Guid.NewGuid().ToString().Replace('-', '_');
-            string tempProcN = "#pn_" + Guid.NewGuid().ToString().Replace('-', '_');
-            string prepTable1 = "CREATE TABLE " + tempTable + " (ci int, c0 dateTime, c1 date, c2 time(7), c3 datetime2(3), c4 datetimeoffset)";
-            string prepTable2 = "INSERT INTO " + tempTable + " VALUES (0, " +
-                "'1753-01-01 12:00AM', " +
-                "'1753-01-01', " +
-                "'20:12:13.36', " +
-                "'2000-12-31 23:59:59.997', " +
-                "'9999-12-31 15:59:59.997 -08:00')";
-            string prepTable3 = "INSERT INTO " + tempTable + " VALUES (@pi, @p0, @p1, @p2, @p3, @p4)";
-            string prepProc = "CREATE PROCEDURE " + tempProc + " @p0 datetime OUTPUT, @p1 date OUTPUT, @p2 time(7) OUTPUT, @p3 datetime2(3) OUTPUT, @p4 datetimeoffset OUTPUT";
-            prepProc += " AS ";
-            prepProc += " SET @p0 = '1753-01-01 12:00AM'";
-            prepProc += " SET @p1 = '1753-01-01'";
-            prepProc += " SET @p2 = '20:12:13.36'";
-            prepProc += " SET @p3 = '2000-12-31 23:59:59.997'";
-            prepProc += "SET @p4 = '9999-12-31 15:59:59.997 -08:00'";
-            string prepProcN = "CREATE PROCEDURE " + tempProcN + " @p0 datetime OUTPUT, @p1 date OUTPUT, @p2 time(7) OUTPUT, @p3 datetime2(3) OUTPUT, @p4 datetimeoffset OUTPUT";
-            prepProcN += " AS ";
-            prepProcN += " SET @p0 = NULL";
-            prepProcN += " SET @p1 = NULL";
-            prepProcN += " SET @p2 = NULL";
-            prepProcN += " SET @p3 = NULL";
-            prepProcN += " SET @p4 = NULL";
-
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                // ReaderParameterTest Setup
-                conn.Open();
-                SqlCommand cmd = conn.CreateCommand();
-                cmd.CommandText = prepTable1;
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = prepTable2;
-                cmd.ExecuteNonQuery();
-
-                #region parameter
-                // Parameter Tests
-                // Test 1
-                SqlCommand cmd2 = conn.CreateCommand();
-                cmd2.CommandText = prepTable3;
-                SqlParameter pi = cmd2.Parameters.Add("@pi", SqlDbType.Int);
-                SqlParameter p0 = cmd2.Parameters.Add("@p0", SqlDbType.DateTime);
-                SqlParameter p1 = cmd2.Parameters.Add("@p1", SqlDbType.Date);
-                SqlParameter p2 = cmd2.Parameters.Add("@p2", SqlDbType.Time);
-                SqlParameter p3 = cmd2.Parameters.Add("@p3", SqlDbType.DateTime2);
-                SqlParameter p4 = cmd2.Parameters.Add("@p4", SqlDbType.DateTimeOffset);
-                pi.Value = DBNull.Value;
-                p0.Value = DBNull.Value;
-                p1.Value = DBNull.Value;
-                p2.Value = DBNull.Value;
-                p3.Value = DBNull.Value;
-                p4.Value = DBNull.Value;
-                p3.Scale = 7;
-                cmd2.ExecuteNonQuery();
-                pi.Value = 1;
-                p0.Value = new DateTime(2000, 12, 31);
-                p1.Value = new DateTime(2000, 12, 31);
-                p2.Value = new TimeSpan(23, 59, 59);
-                p3.Value = new DateTime(2000, 12, 31);
-                p4.Value = new DateTimeOffset(2000, 12, 31, 23, 59, 59, new TimeSpan(-8, 0, 0));
-                p3.Scale = 3;
-                cmd2.ExecuteNonQuery();
-
-                // Test 2
-                cmd2.CommandText = "SELECT COUNT(*) FROM " + tempTable + " WHERE @pi = ci AND @p0 = c0 AND @p1 = c1 AND @p2 = c2 AND @p3 = c3 AND @p4 = c4";
-                pi.Value = 0;
-                p0.Value = new DateTime(1753, 1, 1, 0, 0, 0);
-                p1.Value = new DateTime(1753, 1, 1, 0, 0, 0);
-                p2.Value = new TimeSpan(0, 20, 12, 13, 360);
-                p3.Value = new DateTime(2000, 12, 31, 23, 59, 59, 997);
-                p4.Value = new DateTimeOffset(9999, 12, 31, 23, 59, 59, 997, TimeSpan.Zero);
-                p4.Scale = 3;
-                object scalarResult = cmd2.ExecuteScalar();
-                Assert.True(scalarResult.Equals(1), string.Format("FAILED: Execute scalar returned unexpected result. Expected: {0}. Actual: {1}.", 1, scalarResult));
-
-                cmd2.Parameters.Clear();
-                pi = cmd2.Parameters.Add("@pi", SqlDbType.Int);
-                p0 = cmd2.Parameters.Add("@p0", SqlDbType.DateTime);
-                p1 = cmd2.Parameters.Add("@p1", SqlDbType.Date);
-                p2 = cmd2.Parameters.Add("@p2", SqlDbType.Time);
-                p3 = cmd2.Parameters.Add("@p3", SqlDbType.DateTime2);
-                p4 = cmd2.Parameters.Add("@p4", SqlDbType.DateTimeOffset);
-                pi.SqlValue = new SqlInt32(0);
-                p0.SqlValue = new SqlDateTime(1753, 1, 1, 0, 0, 0);
-                p1.SqlValue = new DateTime(1753, 1, 1, 0, 0, 0);
-                p2.SqlValue = new TimeSpan(0, 20, 12, 13, 360);
-                p3.SqlValue = new DateTime(2000, 12, 31, 23, 59, 59, 997);
-                p4.SqlValue = new DateTimeOffset(9999, 12, 31, 23, 59, 59, 997, TimeSpan.Zero);
-                p2.Scale = 3;
-                p3.Scale = 3;
-                p4.Scale = 3;
-                scalarResult = cmd2.ExecuteScalar();
-                Assert.True(scalarResult.Equals(1), string.Format("FAILED: ExecutScalar returned unexpected result. Expected: {0}. Actual: {1}.", 1, scalarResult));
-
-                // Test 3
-                cmd.CommandText = prepProc;
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = prepProcN;
-                cmd.ExecuteNonQuery();
-                SqlCommand cmd3 = conn.CreateCommand();
-                cmd3.CommandType = CommandType.StoredProcedure;
-                cmd3.CommandText = tempProc;
-                p0 = cmd3.Parameters.Add("@p0", SqlDbType.DateTime);
-                p1 = cmd3.Parameters.Add("@p1", SqlDbType.Date);
-                p2 = cmd3.Parameters.Add("@p2", SqlDbType.Time);
-                p3 = cmd3.Parameters.Add("@p3", SqlDbType.DateTime2);
-                p4 = cmd3.Parameters.Add("@p4", SqlDbType.DateTimeOffset);
-                p0.Direction = ParameterDirection.Output;
-                p1.Direction = ParameterDirection.Output;
-                p2.Direction = ParameterDirection.Output;
-                p3.Direction = ParameterDirection.Output;
-                p4.Direction = ParameterDirection.Output;
-                p2.Scale = 7;
-                cmd3.ExecuteNonQuery();
-
-                Assert.True(p0.Value.Equals((new SqlDateTime(1753, 1, 1, 0, 0, 0)).Value), "FAILED: SqlParameter p0 contained incorrect value");
-                Assert.True(p1.Value.Equals(new DateTime(1753, 1, 1, 0, 0, 0)), "FAILED: SqlParameter p1 contained incorrect value");
-                Assert.True(p2.Value.Equals(new TimeSpan(0, 20, 12, 13, 360)), "FAILED: SqlParameter p2 contained incorrect value");
-                Assert.True(p2.Scale.Equals(7), "FAILED: SqlParameter p0 contained incorrect scale");
-                Assert.True(p3.Value.Equals(new DateTime(2000, 12, 31, 23, 59, 59, 997)), "FAILED: SqlParameter p3 contained incorrect value");
-                Assert.True(p3.Scale.Equals(7), "FAILED: SqlParameter p3 contained incorrect scale");
-                Assert.True(p4.Value.Equals(new DateTimeOffset(9999, 12, 31, 23, 59, 59, 997, TimeSpan.Zero)), "FAILED: SqlParameter p4 contained incorrect value");
-                Assert.True(p4.Scale.Equals(7), "FAILED: SqlParameter p4 contained incorrect scale");
-
-                // Test 4
-                cmd3.CommandText = tempProcN;
-                cmd3.ExecuteNonQuery();
-                Assert.True(p0.Value.Equals(DBNull.Value), "FAILED: SqlParameter p0 expected to be NULL");
-                Assert.True(p1.Value.Equals(DBNull.Value), "FAILED: SqlParameter p1 expected to be NULL");
-                Assert.True(p2.Value.Equals(DBNull.Value), "FAILED: SqlParameter p2 expected to be NULL");
-                Assert.True(p3.Value.Equals(DBNull.Value), "FAILED: SqlParameter p3 expected to be NULL");
-                Assert.True(p4.Value.Equals(DBNull.Value), "FAILED: SqlParameter p4 expected to be NULL");
-
-                // Date
-                Assert.False(IsValidParam(SqlDbType.Date, "c1", new DateTimeOffset(1753, 1, 1, 0, 0, 0, TimeSpan.Zero), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.Date, "c1", new SqlDateTime(1753, 1, 1, 0, 0, 0), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.Date, "c1", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.Date, "c1", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Utc), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.Date, "c1", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Local), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.Date, "c1", new TimeSpan(), conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.Date, "c1", "1753-1-1", conn, tempTable), "FAILED: Invalid param for Date SqlDbType");
-
-                // Time
-                Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTimeOffset(1753, 1, 1, 0, 0, 0, TimeSpan.Zero), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.Time, "c2", new SqlDateTime(1753, 1, 1, 0, 0, 0), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Utc), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.Time, "c2", new DateTime(1753, 1, 1, 0, 0, 0, DateTimeKind.Local), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.Time, "c2", TimeSpan.Parse("20:12:13.36"), conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.Time, "c2", "20:12:13.36", conn, tempTable), "FAILED: Invalid param for Time SqlDbType");
-
-                // DateTime2
-                DateTime dt = DateTime.Parse("2000-12-31 23:59:59.997");
-                Assert.False(IsValidParam(SqlDbType.DateTime2, "c3", new DateTimeOffset(1753, 1, 1, 0, 0, 0, TimeSpan.Zero), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.DateTime2, "c3", new SqlDateTime(2000, 12, 31, 23, 59, 59, 997), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", new DateTime(2000, 12, 31, 23, 59, 59, 997, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", new DateTime(2000, 12, 31, 23, 59, 59, 997, DateTimeKind.Utc), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", new DateTime(2000, 12, 31, 23, 59, 59, 997, DateTimeKind.Local), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.DateTime2, "c3", new TimeSpan(), conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTime2, "c3", "2000-12-31 23:59:59.997", conn, tempTable), "FAILED: Invalid param for DateTime2 SqlDbType");
-
-                // DateTimeOffset
-                DateTimeOffset dto = DateTimeOffset.Parse("9999-12-31 23:59:59.997 +00:00");
-                Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", dto, conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.DateTimeOffset, "c4", new SqlDateTime(1753, 1, 1, 0, 0, 0), conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", new DateTime(9999, 12, 31, 15, 59, 59, 997, DateTimeKind.Unspecified), conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", dto.UtcDateTime, conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", dto.LocalDateTime, conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
-                Assert.False(IsValidParam(SqlDbType.DateTimeOffset, "c4", new TimeSpan(), conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
-                Assert.True(IsValidParam(SqlDbType.DateTimeOffset, "c4", "9999-12-31 23:59:59.997 +00:00", conn, tempTable), "FAILED: Invalid param for DateTimeOffset SqlDbType");
-                #endregion
-
-                #region reader
-                // Reader Tests
-                cmd.CommandText = "SELECT * FROM " + tempTable;
-                using (SqlDataReader rdr = cmd.ExecuteReader())
-                {
-                    object[] values = new object[rdr.FieldCount];
-                    object[] sqlValues = new object[rdr.FieldCount];
-                    object[] psValues = new object[rdr.FieldCount];
-
-                    while (rdr.Read())
-                    {
-                        rdr.GetValues(values);
-                        rdr.GetSqlValues(sqlValues);
-                        rdr.GetProviderSpecificValues(psValues);
-
-                        for (int i = 0; i < rdr.FieldCount; ++i)
-                        {
-                            if (!rdr.IsDBNull(i))
-                            {
-                                bool parsingSucceeded = true;
-                                try
-                                {
-                                    switch (i)
-                                    {
-                                        case 0:
-                                            rdr.GetInt32(i);
-                                            break;
-                                        case 1:
-                                            rdr.GetDateTime(i);
-                                            break;
-                                        case 2:
-                                            rdr.GetDateTime(i);
-                                            break;
-                                        case 3:
-                                            rdr.GetTimeSpan(i);
-                                            break;
-                                        case 4:
-                                            rdr.GetDateTime(i);
-                                            break;
-                                        case 5:
-                                            rdr.GetDateTimeOffset(i);
-                                            break;
-                                        default:
-                                            Console.WriteLine("Received unknown column number {0} during ReaderParameterTest.", i);
-                                            parsingSucceeded = false;
-                                            break;
-                                    }
-                                }
-                                catch (InvalidCastException)
-                                {
-                                    parsingSucceeded = false;
-                                }
-                                Assert.True(parsingSucceeded, "FAILED: SqlDataReader parsing failed for column: " + i);
-
-                                // Check if each value cast is equivalent to the others
-                                // Using ToString() helps get around different representations (mainly for values[] and GetValue())
-                                string[] valueStrList =
-                                    {
-                                        sqlValues[i].ToString(), rdr.GetSqlValue(i).ToString(), psValues[i].ToString(),
-                                        rdr.GetProviderSpecificValue(i).ToString(), values[i].ToString(), rdr.GetValue(i).ToString()
-                                    };
-                                string[] valueNameList = { "sqlValues[]", "GetSqlValue", "psValues[]", "GetProviderSpecificValue", "values[]", "GetValue" };
-
-                                for (int valNum = 0; valNum < valueStrList.Length; valNum++)
-                                {
-                                    string currValueStr = valueStrList[valNum].ToString();
-                                    for (int otherValNum = 0; otherValNum < valueStrList.Length; otherValNum++)
-                                    {
-                                        if (valNum == otherValNum) continue;
-
-                                        Assert.True(currValueStr.Equals(valueStrList[otherValNum]),
-                                            string.Format("FAILED: Value from {0} not equivalent to {1} result", valueNameList[valNum], valueNameList[otherValNum]));
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-                #endregion
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TypeVersionKnobTest()
-        {
-            string tempTable = "#t_" + Guid.NewGuid().ToString().Replace('-', '_');
-            string prepTable1 = "CREATE TABLE " + tempTable + " (ci int, c0 dateTime, c1 date, c2 time(7), c3 datetime2(3), c4 datetimeoffset)";
-            string prepTable2 = "INSERT INTO " + tempTable + " VALUES (0, " +
-                "'1753-01-01 12:00AM', " +
-                "'1753-01-01', " +
-                "'20:12:13.36', " +
-                "'2000-12-31 23:59:59.997', " +
-                "'9999-12-31 15:59:59.997 -08:00')";
-            string prepTable3 = "INSERT INTO " + tempTable + " VALUES (NULL, NULL, NULL, NULL, NULL, NULL)";
-
-            using (SqlConnection conn = new SqlConnection(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { TypeSystemVersion = "SQL Server 2008" }.ConnectionString))
-            {
-                conn.Open();
-                SqlCommand cmd = conn.CreateCommand();
-                cmd.CommandText = prepTable1;
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = prepTable2;
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = prepTable3;
-                cmd.ExecuteNonQuery();
-
-                cmd.CommandText = "SELECT * FROM " + tempTable;
-                using (SqlDataReader rdr = cmd.ExecuteReader())
-                {
-                    while (rdr.Read())
-                    {
-                        for (int i = 2; i < rdr.FieldCount; ++i)
-                        {
-                            Assert.True(IsNotString(rdr, i), string.Format("FAILED: IsNotString failed for column: {0}", i));
-                        }
-                        for (int i = 2; i < rdr.FieldCount; ++i)
-                        {
-                            ValidateReader(rdr, i);
-                        }
-                    }
-                }
-            }
-
-            using (SqlConnection conn = new SqlConnection(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { TypeSystemVersion = "SQL Server 2005" }.ConnectionString))
-            {
-                conn.Open();
-                SqlCommand cmd = conn.CreateCommand();
-                cmd.CommandText = prepTable1;
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = prepTable2;
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = prepTable3;
-                cmd.ExecuteNonQuery();
-
-                cmd.CommandText = "SELECT * FROM " + tempTable;
-                using (SqlDataReader rdr = cmd.ExecuteReader())
-                {
-                    while (rdr.Read())
-                    {
-                        for (int i = 2; i < rdr.FieldCount; ++i)
-                        {
-                            Assert.True(IsString(rdr, i), string.Format("FAILED: IsString failed for column: {0}", i));
-                        }
-                        for (int i = 2; i < rdr.FieldCount; ++i)
-                        {
-                            ValidateReader(rdr, i);
-                        }
-                    }
-                }
-            }
-        }
-
-
-        private static bool IsValidParam(SqlDbType dbType, string col, object value, SqlConnection conn, string tempTable)
-        {
-            try
-            {
-                SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM " + tempTable + " WHERE " + col + " = @p", conn);
-                cmd.Parameters.Add("@p", dbType).Value = value;
-                cmd.ExecuteScalar();
-            }
-            catch (InvalidCastException)
-            {
-                return false;
-            }
-            return true;
-        }
-
-        private static bool IsString(SqlDataReader rdr, int column)
-        {
-            if (!rdr.IsDBNull(column))
-            {
-                try
-                {
-                    rdr.GetString(column);
-                }
-                catch (InvalidCastException)
-                {
-                    return false;
-                }
-            }
-
-            try
-            {
-                rdr.GetSqlString(column);
-            }
-            catch (InvalidCastException)
-            {
-                return false;
-            }
-
-            try
-            {
-                rdr.GetSqlChars(column);
-            }
-            catch (InvalidCastException)
-            {
-                return false;
-            }
-
-            object o = rdr.GetValue(column);
-            if (o != DBNull.Value && !(o is string))
-            {
-                return false;
-            }
-
-            o = rdr.GetSqlValue(column);
-            if (!(o is SqlString))
-            {
-                return false;
-            }
-
-            return true;
-        }
-
-        private static bool IsNotString(SqlDataReader rdr, int column)
-        {
-            if (!rdr.IsDBNull(column))
-            {
-                try
-                {
-                    rdr.GetString(column);
-                    return false;
-                }
-                catch (InvalidCastException)
-                {
-                }
-            }
-
-            try
-            {
-                rdr.GetSqlString(column);
-                return false;
-            }
-            catch (InvalidCastException)
-            {
-            }
-
-            try
-            {
-                rdr.GetSqlChars(column);
-                return false;
-            }
-            catch (InvalidCastException)
-            {
-            }
-
-            object o = rdr.GetValue(column);
-            if (o is string)
-            {
-                return false;
-            }
-
-            o = rdr.GetSqlValue(column);
-            if (o is SqlString)
-            {
-                return false;
-            }
-
-            return true;
-        }
-
-        private static void ValidateReader(SqlDataReader rdr, int column)
-        {
-            bool validateSucceeded = false;
-            Action[] nonDbNullActions =
-            {
-                () => rdr.GetDateTime(column),
-                () => rdr.GetTimeSpan(column),
-                () => rdr.GetDateTimeOffset(column),
-                () => rdr.GetString(column)
-            };
-            Action[] genericActions =
-            {
-                () => rdr.GetSqlString(column),
-                () => rdr.GetSqlChars(column),
-                () => rdr.GetSqlDateTime(column)
-            };
-
-            Action<Action[]> validateParsingActions =
-                (testActions) =>
-                {
-                    foreach (Action testAction in testActions)
-                    {
-                        try
-                        {
-                            testAction();
-                            validateSucceeded = true;
-                        }
-                        catch (InvalidCastException)
-                        {
-                        }
-                    }
-                };
-
-            if (!rdr.IsDBNull(column))
-            {
-                validateParsingActions(nonDbNullActions);
-            }
-            validateParsingActions(genericActions);
-
-            // Server 2008 & 2005 seem to represent DBNull slightly differently. Might be related to a Timestamp IsDBNull bug
-            // in SqlDataReader, which requires different server versions to handle NULLs differently.
-            // Empty string is expected for DBNull SqlValue (as per API), but SqlServer 2005 returns "Null" for it.
-            // See GetSqlValue code path in SqlDataReader for more details
-            if (!validateSucceeded && rdr.IsDBNull(column) && rdr.GetValue(column).ToString().Equals(""))
-            {
-                validateSucceeded = true;
-            }
-
-            Assert.True(validateSucceeded, string.Format("FAILED: SqlDataReader failed reader validation for column: {0}. Column literal value: {1}", column, rdr.GetSqlValue(column)));
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs
deleted file mode 100644 (file)
index 9a56029..0000000
+++ /dev/null
@@ -1,342 +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.Globalization;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ExceptionTest
-    {
-        // data value and server consts
-        private const string badServer = "NotAServer";
-        private const string sqlsvrBadConn = "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.";
-        private const string logonFailedErrorMessage = "Login failed for user '{0}'.";
-        private const string execReaderFailedMessage = "ExecuteReader requires an open and available Connection. The connection's current state is closed.";
-        private const string warningNoiseMessage = "The full-text search condition contained noise word(s).";
-        private const string warningInfoMessage = "Test of info messages";
-        private const string orderIdQuery = "select orderid from orders where orderid < 10250";
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void WarningTest()
-        {
-            Action<object, SqlInfoMessageEventArgs> warningCallback =
-                (object sender, SqlInfoMessageEventArgs imevent) =>
-                {
-                    for (int i = 0; i < imevent.Errors.Count; i++)
-                    {
-                        Assert.True(imevent.Errors[i].Message.Contains(warningInfoMessage), "FAILED: WarningTest Callback did not contain correct message.");
-                    }
-                };
-
-            SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback);
-            using (SqlConnection sqlConnection = new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = false }).ConnectionString))
-            {
-                sqlConnection.InfoMessage += handler;
-                sqlConnection.Open();
-
-                SqlCommand cmd = new SqlCommand(string.Format("PRINT N'{0}'", warningInfoMessage), sqlConnection);
-                cmd.ExecuteNonQuery();
-
-                sqlConnection.InfoMessage -= handler;
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private static bool EmployeesTableHasFullTextIndex()
-        {
-            if (DataTestUtility.TcpConnStr == null)
-                return false;
-
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                conn.Open();
-                cmd.CommandText = "SELECT object_id FROM sys.fulltext_indexes WHERE object_id = object_id('Northwind.dbo.Employees')";
-
-                return (cmd.ExecuteScalar() != null);
-            }
-        }
-
-        [ConditionalFact(nameof(EmployeesTableHasFullTextIndex))]
-        public static void WarningsBeforeRowsTest()
-        {
-            bool hitWarnings = false;
-
-            int iteration = 0;
-            Action<object, SqlInfoMessageEventArgs> warningCallback =
-                (object sender, SqlInfoMessageEventArgs imevent) =>
-                {
-                    for (int i = 0; i < imevent.Errors.Count; i++)
-                    {
-                        Assert.True(imevent.Errors[i].Message.Contains(warningNoiseMessage), "FAILED: WarningsBeforeRowsTest Callback did not contain correct message. Failed in loop iteration: " + iteration);
-                    }
-                    hitWarnings = true;
-                };
-
-            SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback);
-            SqlConnection sqlConnection = new SqlConnection(DataTestUtility.TcpConnStr);
-            sqlConnection.InfoMessage += handler;
-            sqlConnection.Open();
-            foreach (string orderClause in new string[] { "", " order by FirstName" })
-            {
-                foreach (bool messagesOnErrors in new bool[] { true, false })
-                {
-                    iteration++;
-
-                    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);
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        Assert.True(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be TRUE)");
-
-                        bool receivedRows = false;
-                        while (reader.Read())
-                        {
-                            receivedRows = true;
-                        }
-                        Assert.True(receivedRows, "FAILED: Should have received rows from this query.");
-                        Assert.True(hitWarnings, "FAILED: Should have received warnings from this query");
-                    }
-                    hitWarnings = false;
-
-                    cmd.CommandText = "select FirstName from Northwind.dbo.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)");
-
-                        bool receivedRows = false;
-                        while (reader.Read())
-                        {
-                            receivedRows = true;
-                        }
-                        Assert.False(receivedRows, "FAILED: Should have NOT received rows from this query.");
-                        Assert.True(hitWarnings, "FAILED: Should have received warnings from this query");
-                    }
-                }
-            }
-            sqlConnection.Close();
-        }
-
-        private static bool CheckThatExceptionsAreDistinctButHaveSameData(SqlException e1, SqlException e2)
-        {
-            Assert.True(e1 != e2, "FAILED: verification of exception cloning in subsequent connection attempts");
-
-            Assert.False((e1 == null) || (e2 == null), "FAILED: One of exceptions is null, another is not");
-
-            bool equal = (e1.Message == e2.Message) && (e1.HelpLink == e2.HelpLink) && (e1.InnerException == e2.InnerException)
-                && (e1.Source == e2.Source) && (e1.Data.Count == e2.Data.Count) && (e1.Errors == e2.Errors);
-            IDictionaryEnumerator enum1 = e1.Data.GetEnumerator();
-            IDictionaryEnumerator enum2 = e2.Data.GetEnumerator();
-            while (equal)
-            {
-                if (!enum1.MoveNext())
-                    break;
-                enum2.MoveNext();
-                equal = (enum1.Key == enum2.Key) && (enum2.Value == enum2.Value);
-            }
-
-            Assert.True(equal, string.Format("FAILED: exceptions do not contain the same data (besides call stack):\nFirst: {0}\nSecond: {1}\n", e1, e2));
-
-            return true;
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ExceptionTests()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-
-            // tests improper server name thrown from constructor of tdsparser
-            SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
-
-            VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), sqlsvrBadConn, VerifyException);
-
-            // tests incorrect password - thrown from the adapter
-            badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty, IntegratedSecurity = false };
-            string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
-            VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
-
-            // tests incorrect database name - exception thrown from adapter
-            // (Forcing Pooling here, so that differing ClientConnectionId's in the exceptions won't make the test fail
-            // in CheckThatExceptionsAreDistinctButHaveSameData)
-            badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { InitialCatalog = "NotADatabase", Pooling = true };
-            errorMessage = string.Format(CultureInfo.InvariantCulture, "Cannot open database \"{0}\" requested by the login. The login failed.", badBuilder.InitialCatalog);
-            SqlException firstAttemptException = VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 2, 4060, 1, 11));
-
-            // Verify that the same error results in a different instance of an exception, but with the same data
-            VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => CheckThatExceptionsAreDistinctButHaveSameData(firstAttemptException, ex));
-
-            // tests incorrect user name - exception thrown from adapter
-            badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { UserID = "NotAUser", IntegratedSecurity = false };
-            errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
-            VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void VariousExceptionTests()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-
-
-            // Test 1 - A
-            SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
-            using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
-            {
-                using (SqlCommand command = sqlConnection.CreateCommand())
-                {
-                    command.CommandText = orderIdQuery;
-                    VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
-                }
-            }
-
-            // Test 1 - B
-            badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty, IntegratedSecurity = false };
-            using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
-            {
-                string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
-                VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void IndependentConnectionExceptionTest()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-
-            SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
-            using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
-            {
-                // Test 1
-                VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), sqlsvrBadConn, VerifyException);
-
-                // Test 2
-                using (SqlCommand command = new SqlCommand(orderIdQuery, sqlConnection))
-                {
-                    VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static async Task UnobservedTaskExceptionTest()
-        {
-            List<Exception> exceptionsSeen = new List<Exception>();
-            Action<object, UnobservedTaskExceptionEventArgs> unobservedTaskCallback =
-                (object sender, UnobservedTaskExceptionEventArgs e) =>
-                {
-                    Assert.False(exceptionsSeen.Contains(e.Exception.InnerException), "FAILED: This exception was already observed by awaiting: " + e.Exception.InnerException);
-                };
-            EventHandler<UnobservedTaskExceptionEventArgs> handler = new EventHandler<UnobservedTaskExceptionEventArgs>(unobservedTaskCallback);
-
-            TaskScheduler.UnobservedTaskException += handler;
-
-            using(var connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                await connection.OpenAsync();
-                using (var command = new SqlCommand("select null; select * from dbo.NonexistentTable;", connection))
-                {
-                    try
-                    {
-                        using (var reader = await command.ExecuteReaderAsync())
-                        {
-                            do
-                            {
-                                while (await reader.ReadAsync())
-                                {
-                                }
-                            } while (await reader.NextResultAsync());
-                        }
-                    }
-                    catch (SqlException ex)
-                    {
-                        exceptionsSeen.Add(ex);
-                    }
-                }
-            }
-            GC.Collect();
-            GC.WaitForPendingFinalizers();
-
-            TaskScheduler.UnobservedTaskException -= handler;
-        }
-
-        private static void GenerateConnectionException(string connectionString)
-        {
-            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
-            {
-                sqlConnection.Open();
-                using (SqlCommand command = sqlConnection.CreateCommand())
-                {
-                    command.CommandText = orderIdQuery;
-                    command.ExecuteReader();
-                }
-            }
-        }
-
-        private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage, Func<TException, bool> exVerifier) where TException : Exception
-        {
-            TException ex = Assert.Throws<TException>(connectAction);
-            Assert.True(ex.Message.Contains(expectedExceptionMessage), string.Format("FAILED: SqlException did not contain expected error message. Actual message: {0}", ex.Message));
-            Assert.True(exVerifier(ex), "FAILED: Exception verifier failed on the exception.");
-
-            return ex;
-        }
-
-        private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage) where TException : Exception
-        {
-            return VerifyConnectionFailure<TException>(connectAction, expectedExceptionMessage, (ex) => true);
-        }
-
-        private static bool VerifyException(SqlException exception)
-        {
-            VerifyException(exception, 1);
-            return true;
-        }
-
-        private static bool VerifyException(SqlException exception, int count, int? errorNumber = null, int? errorState = null, int? severity = null)
-        {
-            // Verify that there are the correct number of errors in the exception
-            Assert.True(exception.Errors.Count == count, string.Format("FAILED: Incorrect number of errors. Expected: {0}. Actual: {1}.", count, exception.Errors.Count));
-
-            // Ensure that all errors have an error-level severity
-            for (int i = 0; i < count; i++)
-            {
-                Assert.True(exception.Errors[i].Class >= 10, "FAILED: verification of Exception!  Exception contains a warning!");
-            }
-
-            // Check the properties of the exception populated by the server are correct
-            if (errorNumber.HasValue)
-            {
-                Assert.True(errorNumber.Value == exception.Number, string.Format("FAILED: Error number of exception is incorrect. Expected: {0}. Actual: {1}.", errorNumber.Value, exception.Number));
-            }
-
-            if (errorState.HasValue)
-            {
-                Assert.True(errorState.Value == exception.State, string.Format("FAILED: Error state of exception is incorrect. Expected: {0}. Actual: {1}.", errorState.Value, exception.State));
-            }
-
-            if (severity.HasValue)
-            {
-                Assert.True(severity.Value == exception.Class, string.Format("FAILED: Severity of exception is incorrect. Expected: {0}. Actual: {1}.", severity.Value, exception.Class));
-            }
-
-            if ((errorNumber.HasValue) && (errorState.HasValue) && (severity.HasValue))
-            {
-                string detailsText = string.Format("Error Number:{0},State:{1},Class:{2}", errorNumber.Value, errorState.Value, severity.Value);
-                Assert.True(exception.ToString().Contains(detailsText), string.Format("FAILED: SqlException.ToString does not contain the error number, state and severity information"));
-            }
-
-            // verify that the this[] function on the collection works, as well as the All function
-            SqlError[] errors = new SqlError[exception.Errors.Count];
-            exception.Errors.CopyTo(errors, 0);
-            Assert.True((errors[0].Message).Equals(exception.Errors[0].Message), string.Format("FAILED: verification of Exception! ErrorCollection indexer/CopyTo resulted in incorrect value."));
-
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs
deleted file mode 100644 (file)
index ace4707..0000000
+++ /dev/null
@@ -1,67 +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.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class InstanceNameTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void ConnectToSQLWithInstanceNameTest()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-
-            bool proceed = true;
-            string dataSourceStr = builder.DataSource.Replace("tcp:", "");
-            string[] serverNamePartsByBackSlash = dataSourceStr.Split('\\');
-            if (!dataSourceStr.Contains(",") && serverNamePartsByBackSlash.Length == 2)
-            {
-                string hostname = serverNamePartsByBackSlash[0];
-                proceed = !string.IsNullOrWhiteSpace(hostname) && IsBrowserAlive(hostname);
-            }
-
-            if (proceed)
-            {
-                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
-                {
-                    connection.Open();
-                    connection.Close();
-                }
-            }
-        }
-
-        private static bool IsBrowserAlive(string browserHostname)
-        {
-            const int DefaultBrowserPort = 1434;
-            const int sendTimeout = 1000;
-            const int receiveTimeout = 1000;
-            const byte ClntUcastEx = 0x03;
-
-            byte[] requestPacket = new byte[] { ClntUcastEx };
-            byte[] responsePacket = null;
-            using (UdpClient client = new UdpClient(AddressFamily.InterNetwork))
-            {
-                try
-                {
-                    Task<int> sendTask = client.SendAsync(requestPacket, requestPacket.Length, browserHostname, DefaultBrowserPort);
-                    Task<UdpReceiveResult> receiveTask = null;
-                    if (sendTask.Wait(sendTimeout) && (receiveTask = client.ReceiveAsync()).Wait(receiveTimeout))
-                    {
-                        responsePacket = receiveTask.Result.Buffer;
-                    }
-                }
-                catch { }
-            }
-            return responsePacket != null && responsePacket.Length > 0;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/IntegratedAuthenticationTest/IntegratedAuthenticationTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/IntegratedAuthenticationTest/IntegratedAuthenticationTest.cs
deleted file mode 100644 (file)
index 35e5a24..0000000
+++ /dev/null
@@ -1,48 +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.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class IntegratedAuthenticationTest
-    {
-        private static bool IsIntegratedSecurityEnvironmentSet() => DataTestUtility.IsIntegratedSecuritySetup();
-        private static bool AreConnectionStringsSetup() => DataTestUtility.AreConnStringsSetup();
-
-
-        [ConditionalFact(nameof(IsIntegratedSecurityEnvironmentSet),nameof(AreConnectionStringsSetup))]
-        public static void IntegratedAuthenticationTestWithConnectionPooling()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            builder.IntegratedSecurity = true;
-            builder.Pooling = true;
-            TryOpenConnectionWithIntegratedAuthentication(builder.ConnectionString);
-        }
-
-        [ConditionalFact(nameof(IsIntegratedSecurityEnvironmentSet), nameof(AreConnectionStringsSetup))]
-        public static void IntegratedAuthenticationTestWithOutConnectionPooling()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            builder.IntegratedSecurity = true;
-            builder.Pooling = false;
-            TryOpenConnectionWithIntegratedAuthentication(builder.ConnectionString);
-        }
-
-        private static void TryOpenConnectionWithIntegratedAuthentication(string connectionString)
-        {
-            using (SqlConnection connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/LocalDBTest/LocalDBTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/LocalDBTest/LocalDBTest.cs
deleted file mode 100644 (file)
index 9f05b3d..0000000
+++ /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 Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class LocalDBTest
-    {
-        private static bool IsLocalDBEnvironmentSet() => DataTestUtility.IsLocalDBInstalled();
-
-        [ConditionalFact(nameof(IsLocalDBEnvironmentSet))]
-        public static void LocalDBConnectionTest()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(@"server=(localdb)\MSSQLLocalDB");
-            builder.IntegratedSecurity = true;
-            builder.ConnectTimeout = 2;
-            OpenConnection(builder.ConnectionString);
-        }
-
-        [ConditionalFact(nameof(IsLocalDBEnvironmentSet))]
-        public static void LocalDBMarsTest()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(@"server=(localdb)\MSSQLLocalDB;");
-            builder.IntegratedSecurity = true;
-            builder.MultipleActiveResultSets = true;
-            builder.ConnectTimeout = 2;
-            OpenConnection(builder.ConnectionString);
-        }
-
-        [ConditionalFact(nameof(IsLocalDBEnvironmentSet))]
-        public static void InvalidDBTest()
-        {
-            using (var connection = new SqlConnection(@"Data Source=(localdb)\MSSQLLOCALDB;Database=DOES_NOT_EXIST;Pooling=false;"))
-            {
-                DataTestUtility.AssertThrowsWrapper<SqlException>(() => connection.Open());
-            }
-        }
-
-        private static void OpenConnection(string connString)
-        {
-            using (SqlConnection connection = new SqlConnection(connString))
-            {
-                connection.Open();
-                using (SqlCommand command = new SqlCommand("SELECT @@SERVERNAME", connection))
-                {
-                    var result = command.ExecuteScalar();
-                    Assert.NotNull(result);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MARSSessionPoolingTest/MARSSessionPoolingTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MARSSessionPoolingTest/MARSSessionPoolingTest.cs
deleted file mode 100644 (file)
index 15a2348..0000000
+++ /dev/null
@@ -1,257 +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.CompilerServices;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class MARSSessionPoolingTest
-    {
-        private const string COMMAND_STATUS = "select count(*) as ConnectionCount from sys.dm_exec_connections where session_id=@@spid and net_transport='Session'; select count(*) as ActiveRequestCount from sys.dm_exec_requests where session_id=@@spid and status='running' or session_id=@@spid and status='suspended'";
-        private const string COMMAND_SPID = "select @@spid";
-        private const int CONCURRENT_COMMANDS = 5;
-
-        private const string _COMMAND_RPC = "sp_who";
-        private const string _COMMAND_SQL =
-            "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " +
-            "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " +
-            "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " +
-            "select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; select * from sys.databases; " +
-            "select * from sys.databases; print 'THIS IS THE END!'";
-
-        private static readonly string _testConnString =
-            (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
-            {
-                PacketSize = 512,
-                MaxPoolSize = 1,
-                MultipleActiveResultSets = true
-            }).ConnectionString;
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        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))]
-        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))]
-        public static void MarsExecuteReader_Text_NoGC()
-        {
-            TestMARSSessionPooling("Case: Text, ExecuteReader, ReaderClose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderClose, GCType.Wait);
-            TestMARSSessionPooling("Case: Text, ExecuteReader, ReaderDispose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderDispose, GCType.Wait);
-            TestMARSSessionPooling("Case: Text, ExecuteReader, ConnectionClose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ConnectionClose, GCType.Wait);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MarsExecuteReader_RPC_NoGC()
-        {
-            TestMARSSessionPooling("Case: RPC,  ExecuteReader, ReaderClose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderClose, GCType.Wait);
-            TestMARSSessionPooling("Case: RPC,  ExecuteReader, ReaderDispose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderDispose, GCType.Wait);
-            TestMARSSessionPooling("Case: RPC,  ExecuteReader, ConnectionClose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ConnectionClose, GCType.Wait);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        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);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MarsExecuteReader_StoredProcedure_WithGC()
-        {
-            TestMARSSessionPooling("Case: RPC,  ExecuteReader, GC-Wait", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.Wait);
-            TestMARSSessionPooling("Case: RPC,  ExecuteReader, GC-NoWait", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.NoWait);
-
-            TestMARSSessionPooling("Case: Text, ExecuteReader, NoCloses", _testConnString + " ", CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.NoCloses, GCType.Wait);
-            TestMARSSessionPooling("Case: RPC,  ExecuteReader, NoCloses", _testConnString + "  ", CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.NoCloses, GCType.Wait);
-        }
-
-        private enum ExecuteType
-        {
-            ExecuteScalar,
-            ExecuteNonQuery,
-            ExecuteReader,
-        }
-
-        private enum ReaderTestType
-        {
-            ReaderClose,
-            ReaderDispose,
-            ReaderGC,
-            ConnectionClose,
-            NoCloses,
-        }
-
-        private enum GCType
-        {
-            Wait,
-            NoWait,
-        }
-
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static void TestMARSSessionPooling(string caseName, string connectionString, CommandType commandType,
-                                           ExecuteType executeType, ReaderTestType readerTestType, GCType gcType)
-        {
-            SqlCommand[] cmd = new SqlCommand[CONCURRENT_COMMANDS];
-            SqlDataReader[] gch = new SqlDataReader[CONCURRENT_COMMANDS];
-
-            using (SqlConnection con = new SqlConnection(connectionString))
-            {
-                con.Open();
-
-                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
-                {
-                    // Prepare all commands
-                    cmd[i] = con.CreateCommand();
-                    switch (commandType)
-                    {
-                        case CommandType.Text:
-                            cmd[i].CommandText = _COMMAND_SQL;
-                            cmd[i].CommandTimeout = 120;
-                            break;
-                        case CommandType.StoredProcedure:
-                            cmd[i].CommandText = _COMMAND_RPC;
-                            cmd[i].CommandTimeout = 120;
-                            cmd[i].CommandType = CommandType.StoredProcedure;
-                            break;
-                    }
-                }
-
-                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
-                {
-                    switch (executeType)
-                    {
-                        case ExecuteType.ExecuteScalar:
-                            cmd[i].ExecuteScalar();
-                            break;
-                        case ExecuteType.ExecuteNonQuery:
-                            cmd[i].ExecuteNonQuery();
-                            break;
-                        case ExecuteType.ExecuteReader:
-                            if (readerTestType != ReaderTestType.ReaderGC)
-                                gch[i] = cmd[i].ExecuteReader();
-
-                            switch (readerTestType)
-                            {
-                                case ReaderTestType.ReaderClose:
-                                    {
-                                        gch[i].Dispose();
-                                        break;
-                                    }
-                                case ReaderTestType.ReaderDispose:
-                                    gch[i].Dispose();
-                                    break;
-                                case ReaderTestType.ReaderGC:
-                                    gch[i] = null;
-                                    WeakReference weak = OpenReaderThenNullify(cmd[i]);
-                                    GC.Collect();
-
-                                    if (gcType == GCType.Wait)
-                                    {
-                                        GC.WaitForPendingFinalizers();
-                                        Assert.False(weak.IsAlive, "Error - target still alive!");
-                                    }
-                                    break;
-                                case ReaderTestType.ConnectionClose:
-                                    GC.SuppressFinalize(gch[i]);
-                                    con.Close();
-                                    con.Open();
-                                    break;
-                                case ReaderTestType.NoCloses:
-                                    GC.SuppressFinalize(gch[i]);
-                                    break;
-                            }
-                            break;
-                    }
-
-                    if (readerTestType != ReaderTestType.NoCloses)
-                    {
-                        con.Close();
-                        con.Open(); // Close and open, to re-assure collection!
-                    }
-
-                    SqlCommand verificationCmd = con.CreateCommand();
-
-                    verificationCmd.CommandText = COMMAND_STATUS;
-                    using (SqlDataReader rdr = verificationCmd.ExecuteReader())
-                    {
-                        rdr.Read();
-                        int connections = (int)rdr.GetValue(0);
-                        rdr.NextResult();
-                        rdr.Read();
-                        int requests = (int)rdr.GetValue(0);
-
-                        switch (executeType)
-                        {
-                            case ExecuteType.ExecuteScalar:
-                            case ExecuteType.ExecuteNonQuery:
-                                // 1 for connection, 1 for command
-                                Assert.True(connections == 2, "Failure - incorrect number of connections for ExecuteScalar! #connections: " + connections);
-
-                                // only 1 executing
-                                Assert.True(requests == 1, "Failure - incorrect number of requests for ExecuteScalar! #requests: " + requests);
-                                break;
-                            case ExecuteType.ExecuteReader:
-                                switch (readerTestType)
-                                {
-                                    case ReaderTestType.ReaderClose:
-                                    case ReaderTestType.ReaderDispose:
-                                    case ReaderTestType.ConnectionClose:
-                                        // 1 for connection, 1 for command
-                                        Assert.True(connections == 2, "Failure - Incorrect number of connections for ReaderClose / ReaderDispose / ConnectionClose! #connections: " + connections);
-
-                                        // only 1 executing
-                                        Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderClose/ReaderDispose/ConnectionClose! #requests: " + requests);
-                                        break;
-                                    case ReaderTestType.ReaderGC:
-                                        switch (gcType)
-                                        {
-                                            case GCType.Wait:
-                                                // 1 for connection, 1 for open reader
-                                                Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCWait! #connections: " + connections);
-                                                // only 1 executing
-                                                Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCWait! #requests: " + requests);
-                                                break;
-                                            case GCType.NoWait:
-                                                // 1 for connection, 1 for open reader
-                                                Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCNoWait! #connections: " + connections);
-
-                                                // only 1 executing
-                                                Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCNoWait! #requests: " + requests);
-                                                break;
-                                        }
-                                        break;
-                                    case ReaderTestType.NoCloses:
-                                        // 1 for connection, 1 for current command, 1 for 0 based array offset, plus i for open readers
-                                        Assert.True(connections == (3 + i), "Failure - incorrect number of connections for NoCloses: " + connections);
-
-                                        // 1 for current command, 1 for 0 based array offset, plus i open readers
-                                        Assert.True(requests == (2 + i), "Failure - incorrect number of requests for NoCloses: " + requests);
-                                        break;
-                                }
-                                break;
-                        }
-                    }
-                }
-            }
-        }
-
-        private static WeakReference OpenReaderThenNullify(SqlCommand command)
-        {
-            SqlDataReader reader = command.ExecuteReader();
-            WeakReference weak = new WeakReference(reader);
-            reader = null;
-            return weak;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs
deleted file mode 100644 (file)
index e87b37c..0000000
+++ /dev/null
@@ -1,329 +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.Threading;
-using System.Threading.Tasks;
-using System.Reflection;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class MARSTest
-    {
-        private static readonly string _connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString;
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        [PlatformSpecific(TestPlatforms.Windows)]
-        public static void NamedPipesMARSTest()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.NpConnStr);
-            builder.MultipleActiveResultSets = true;
-            builder.ConnectTimeout = 5;
-
-            using (SqlConnection conn = new SqlConnection(builder.ConnectionString))
-            {
-                conn.Open();
-                using (SqlCommand command = new SqlCommand("SELECT @@SERVERNAME", conn))
-                {
-                    var result = command.ExecuteScalar();
-                    Assert.NotNull(result);
-                }
-            }
-        }
-
-#if DEBUG
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSAsyncTimeoutTest()
-        {
-            using (SqlConnection connection = new SqlConnection(_connStr))
-            {
-                connection.Open();
-                SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
-                command.CommandTimeout = 1;
-                Task<object> result = command.ExecuteScalarAsync();
-
-                Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after one second, but no results after 30 seconds");
-                Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));
-                Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));
-
-                Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
-                FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);
-
-                Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");
-
-                field.SetValue(null, true);
-                try
-                {
-                    SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
-                    command2.CommandTimeout = 1;
-                    result = command2.ExecuteScalarAsync();
-
-                    Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after six or so seconds, but no results after 30 seconds");
-                    Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));
-
-                    // Pause here to ensure that the async closing is completed
-                    Thread.Sleep(200);
-                    Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
-                }
-                finally
-                {
-                    field.SetValue(null, false);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSSyncTimeoutTest()
-        {
-            using (SqlConnection connection = new SqlConnection(_connStr))
-            {
-                connection.Open();
-                SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
-                command.CommandTimeout = 1;
-                bool hitException = false;
-                try
-                {
-                    object result = command.ExecuteScalar();
-                }
-                catch (Exception e)
-                {
-                    Assert.True(e is SqlException, "Expected SqlException but found " + e);
-                    hitException = true;
-                }
-                Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");
-
-                Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));
-
-                Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
-                FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);
-
-                Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");
-
-                field.SetValue(null, true);
-                hitException = false;
-                try
-                {
-                    SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
-                    command2.CommandTimeout = 1;
-                    try
-                    {
-                        object result = command2.ExecuteScalar();
-                    }
-                    catch (Exception e)
-                    {
-                        Assert.True(e is SqlException, "Expected SqlException but found " + e);
-                        hitException = true;
-                    }
-                    Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");
-
-                    Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
-                }
-                finally
-                {
-                    field.SetValue(null, false);
-                }
-            }
-        }
-#endif
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSSyncBusyReaderTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
-                {
-                    int rows1 = 0;
-                    while (reader1.Read())
-                    {
-                        rows1++;
-                        if (rows1 == 415)
-                            break;
-                    }
-                    Assert.True(rows1 == 415, "MARSSyncBusyReaderTest Failure, #1");
-
-                    using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
-                    {
-                        int rows2 = 0;
-                        while (reader2.Read())
-                        {
-                            rows2++;
-                            if (rows2 == 415)
-                                break;
-                        }
-                        Assert.True(rows2 == 415, "MARSSyncBusyReaderTest Failure, #2");
-
-                        for (int i = 415; i < 830; i++)
-                        {
-                            Assert.True(reader1.Read() && reader2.Read(), "MARSSyncBusyReaderTest Failure #3");
-                            Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0),
-                                        "MARSSyncBusyReaderTest, Failure #4" + "\n" +
-                                        "reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" +
-                                        "reader2.GetInt32(0): " + reader2.GetInt32(0));
-                        }
-
-                        Assert.False(reader1.Read() || reader2.Read(), "MARSSyncBusyReaderTest, Failure #5");
-                    }
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSSyncExecuteNonQueryTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                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))
-                {
-                    comm1.ExecuteNonQuery();
-                    comm2.ExecuteNonQuery();
-                    comm3.ExecuteNonQuery();
-                    comm4.ExecuteNonQuery();
-                    comm5.ExecuteNonQuery();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSSyncExecuteReaderTest1()
-        {
-            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())
-                {
-                    int rows = 0;
-                    while (reader1.Read())
-                    {
-                        rows++;
-                    }
-                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #1");
-
-                    rows = 0;
-                    while (reader2.Read())
-                    {
-                        rows++;
-                    }
-                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #2");
-
-                    rows = 0;
-                    while (reader3.Read())
-                    {
-                        rows++;
-                    }
-                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #3");
-
-                    rows = 0;
-                    while (reader4.Read())
-                    {
-                        rows++;
-                    }
-                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #4");
-
-                    rows = 0;
-                    while (reader5.Read())
-                    {
-                        rows++;
-                    }
-                    Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #5");
-                }
-            }
-        }
-
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSSyncExecuteReaderTest2()
-        {
-            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())
-                {
-                    for (int i = 0; i < 830; i++)
-                    {
-                        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");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSSyncExecuteReaderTest3()
-        {
-            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())
-                {
-                    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.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #3");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MARSSyncExecuteReaderTest4()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                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())
-                {
-                    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,
-                                "MARSSyncExecuteReaderTest4 failure #2");
-
-                    Assert.False(reader1.Read() || reader2.Read() || reader3.Read(), "MARSSyncExecuteReaderTest4 failure #3");
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs
deleted file mode 100644 (file)
index 5c69d0e..0000000
+++ /dev/null
@@ -1,98 +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.Generic;
-using System.Diagnostics;
-using System.Threading;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ConnectionOnMirroringTest
-    {
-        private static ManualResetEvent workerCompletedEvent = new ManualResetEvent(false);
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestMultipleConnectionToMirroredServer()
-        {
-            string mirroringStateDesc;
-            string failoverPartnerName;
-            bool isMirroring = GetMirroringInfo(DataTestUtility.TcpConnStr, out mirroringStateDesc, out failoverPartnerName);
-            bool isSynchronized = "SYNCHRONIZED".Equals(mirroringStateDesc, StringComparison.InvariantCultureIgnoreCase);
-            if (isMirroring && isSynchronized && !string.IsNullOrEmpty(failoverPartnerName))
-            {
-                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-                builder.ConnectTimeout = 0;
-
-                TestWorker worker = new TestWorker(builder.ConnectionString);
-                Thread childThread = new Thread(() => worker.TestMultipleConnection());
-                childThread.Start();
-
-                if (workerCompletedEvent.WaitOne(10000))
-                {
-                    childThread.Join();
-                }
-                else
-                {
-                    // currently Thread.Abort() throws PlatformNotSupportedException in CoreFx.
-                    childThread.Interrupt();
-                    throw new Exception("SqlConnection could not open and close successfully in timely manner. Possibly connection hangs.");
-                }
-            }
-        }
-
-        private static bool GetMirroringInfo(string connectionString, out string mirroringStateDesc, out string failoverPartnerName)
-        {
-            mirroringStateDesc = null;
-            failoverPartnerName = null;
-
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
-            string dbname = builder.InitialCatalog;
-
-            builder.ConnectTimeout = 5;
-            connectionString = builder.ConnectionString;
-
-            DataTable dt = DataTestUtility.RunQuery(connectionString, $"select mirroring_state_desc from sys.database_mirroring where database_id = DB_ID('{dbname}')");
-            mirroringStateDesc = dt.Rows[0][0].ToString();
-
-            bool isMirroring = !string.IsNullOrEmpty(mirroringStateDesc);
-            if (isMirroring)
-            {
-                dt = DataTestUtility.RunQuery(connectionString, $"select mirroring_partner_name from sys.database_mirroring where database_id = DB_ID('{dbname}')");
-                failoverPartnerName = dt.Rows[0][0].ToString();
-            }
-
-            return isMirroring;
-        }
-
-        private class TestWorker
-        {
-            private string _connectionString;
-
-            public TestWorker(string connectionString)
-            {
-                _connectionString = connectionString;
-            }
-
-            public void TestMultipleConnection()
-            {
-                List<SqlConnection> list = new List<SqlConnection>();
-
-                for (int i = 0; i < 10; ++i)
-                {
-                    SqlConnection conn = new SqlConnection(_connectionString);
-                    list.Add(conn);
-                    conn.Open();
-                }
-
-                foreach (SqlConnection conn in list)
-                {
-                    conn.Dispose();
-                }
-
-                workerCompletedEvent.Set();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs
deleted file mode 100644 (file)
index 1818514..0000000
+++ /dev/null
@@ -1,156 +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;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ParallelTransactionsTest
-    {
-        #region <<Basic Parallel Test>>
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void BasicParallelTest_shouldThrowsUnsupported()
-        {
-            string connectionString = DataTestUtility.TcpConnStr;
-            string expectedErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported(typeof(SqlConnection).Name);
-            string tempTableName = "";
-            try
-            {
-                tempTableName = CreateTempTable(connectionString);
-                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(
-                    actionThatFails: () => { BasicParallelTest(connectionString, tempTableName); },
-                    exceptionMessage: expectedErrorMessage);
-            }
-            finally
-            {
-                if (!string.IsNullOrEmpty(tempTableName))
-                {
-                    DropTempTable(connectionString, tempTableName);
-                }
-            }
-        }
-
-        private static void BasicParallelTest(string connectionString, string tempTableName)
-        {
-            using (var connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                SqlTransaction trans1 = connection.BeginTransaction();
-                SqlTransaction trans2 = connection.BeginTransaction();
-                SqlTransaction trans3 = connection.BeginTransaction();
-
-                SqlCommand com1 = new SqlCommand("select top 1 EmployeeID from " + tempTableName, connection);
-                com1.Transaction = trans1;
-                com1.ExecuteNonQuery();
-
-                SqlCommand com2 = new SqlCommand("select top 1 EmployeeID from " + tempTableName, connection);
-                com2.Transaction = trans2;
-                com2.ExecuteNonQuery();
-
-                SqlCommand com3 = new SqlCommand("select top 1 EmployeeID from " + tempTableName, connection);
-                com3.Transaction = trans3;
-                com3.ExecuteNonQuery();
-
-                trans1.Rollback();
-                trans2.Rollback();
-                trans3.Rollback();
-
-                com1.Dispose();
-                com2.Dispose();
-                com3.Dispose();
-            }
-        }
-
-        #endregion
-
-        #region <<MultipleExecutesInSameTransactionTest>>
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void MultipleExecutesInSameTransactionTest_shouldThrowsUnsupported()
-        {
-            string connectionString = DataTestUtility.TcpConnStr;
-            string expectedErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported(typeof(SqlConnection).Name);
-            string tempTableName = "";
-            try
-            {
-                tempTableName = CreateTempTable(connectionString);
-                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(
-                    actionThatFails: () => { MultipleExecutesInSameTransactionTest(connectionString, tempTableName); },
-                    exceptionMessage: expectedErrorMessage);
-            }
-            finally
-            {
-                if (!string.IsNullOrEmpty(tempTableName))
-                {
-                    DropTempTable(connectionString, tempTableName);
-                }
-            }
-        }
-
-        private static void MultipleExecutesInSameTransactionTest(string connectionString, string tempTableName)
-        {
-            using (var connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-                SqlTransaction trans1 = connection.BeginTransaction();
-                SqlTransaction trans2 = connection.BeginTransaction();
-                SqlTransaction trans3 = connection.BeginTransaction();
-
-                SqlCommand com1 = new SqlCommand("select top 1 EmployeeID from " + tempTableName, connection);
-                com1.Transaction = trans1;
-                com1.ExecuteNonQuery();
-
-                SqlCommand com2 = new SqlCommand("select top 1 EmployeeID from " + tempTableName, connection);
-                com2.Transaction = trans2;
-                com2.ExecuteNonQuery();
-
-                SqlCommand com3 = new SqlCommand("select top 1 EmployeeID from " + tempTableName, connection);
-                com3.Transaction = trans3;
-                com3.ExecuteNonQuery();
-
-                trans1.Rollback();
-                trans2.Rollback();
-                trans3.Rollback();
-
-                com1.Dispose();
-                com2.Dispose();
-                com3.Dispose();
-
-                SqlCommand com4 = new SqlCommand("select top 1 EmployeeID from " + tempTableName, connection);
-                com4.Transaction = trans1;
-                SqlDataReader reader4 = com4.ExecuteReader();
-                reader4.Dispose();
-                com4.Dispose();
-
-                trans1.Rollback();
-            }
-        }
-        #endregion
-
-        private static string CreateTempTable(string connectionString)
-        {
-            var uniqueKey = string.Format("{0}_{1}_{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace("-", "_");
-            var tempTableName = "TEMP_" + uniqueKey;
-            using (var conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                SqlCommand cmd = new SqlCommand(string.Format("SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country into {0} from Employees", tempTableName), conn);
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = string.Format("alter table {0} add constraint EmployeeID_{1} primary key (EmployeeID)", tempTableName, uniqueKey);
-                cmd.ExecuteNonQuery();
-            }
-
-            return tempTableName;
-        }
-
-        private static void DropTempTable(string connectionString, string tempTableName)
-        {
-            using (SqlConnection con1 = new SqlConnection(connectionString))
-            {
-                con1.Open();
-                SqlCommand cmd = new SqlCommand("Drop table " + tempTableName, con1);
-                cmd.ExecuteNonQuery();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/DateTimeVariantTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/DateTimeVariantTest.cs
deleted file mode 100644 (file)
index 90b11fe..0000000
+++ /dev/null
@@ -1,1323 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Text;
-using System.Data;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.IO;
-using Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class DateTimeVariantTest
-    {
-        private static string s_connStr;
-
-        /// <summary>
-        /// Tests all Katmai DateTime types inside sql_variant to server using sql_variant parameter, SqlBulkCopy, and TVP parameter with sql_variant inside.
-        /// </summary>
-        public static void TestAllDateTimeWithDataTypeAndVariant(string connStr)
-        {
-            s_connStr = connStr;
-
-            SendInfo(System.DateTime.MinValue, "System.DateTime", "date");
-            SendInfo(System.DateTime.MaxValue, "System.DateTime", "date");
-
-            SendInfo(System.DateTime.MinValue, "System.DateTime", "datetime2");
-            SendInfo(System.DateTime.MaxValue, "System.DateTime", "datetime2");
-
-            SendInfo(System.DateTime.MinValue, "System.DateTime", "datetime");
-            SendInfo(System.DateTime.MaxValue, "System.DateTime", "datetime");
-
-            SendInfo(System.DateTimeOffset.MinValue, "System.DateTimeOffset", "datetimeoffset");
-            SendInfo(System.DateTimeOffset.MaxValue, "System.DateTimeOffset", "datetimeoffset");
-
-            SendInfo(System.DateTimeOffset.Parse("12/31/1999 23:59:59.9999999 -08:30"), "System.DateTimeOffset", "datetimeoffset");
-            SendInfo(System.DateTime.Parse("1998-01-01 23:59:59.995"), "System.DateTime", "datetime2");
-
-            SendInfo(System.DateTime.MinValue, "System.DateTime", "smalldatetime");
-            SendInfo(System.DateTime.MaxValue, "System.DateTime", "smalldatetime");
-
-            SendInfo(System.TimeSpan.MinValue, "System.TimeSpan", "time");
-            SendInfo(System.TimeSpan.MaxValue, "System.TimeSpan", "time");
-
-            SendInfo(System.DateTime.MinValue, "System.DateTime", "time");
-            SendInfo(System.DateTime.MaxValue, "System.DateTime", "time");
-        }
-
-        private static void SendInfo(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            TestSimpleParameter_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            TestSimpleParameter_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-
-            TestSqlDataRecordParameterToTVP_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            TestSqlDataRecordParameterToTVP_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-
-            TestSqlDataReaderParameterToTVP_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            TestSqlDataReaderParameterToTVP_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-
-            TestSqlDataReader_TVP_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            TestSqlDataReader_TVP_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-
-            TestSimpleDataReader_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            TestSimpleDataReader_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-
-            SqlBulkCopySqlDataReader_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            SqlBulkCopySqlDataReader_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-
-            SqlBulkCopyDataTable_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            SqlBulkCopyDataTable_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-
-            SqlBulkCopyDataRow_Type(paramValue, expectedTypeName, expectedBaseTypeName);
-            SqlBulkCopyDataRow_Variant(paramValue, expectedTypeName, expectedBaseTypeName);
-        }
-
-        private static void TestSimpleParameter_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSimpleParameter_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string procName = DataTestUtility.GetUniqueNameForSqlServer("paramProc1");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, procName);
-                    xsql(conn, string.Format("create proc {0} (@param {1}) as begin select @param end;", procName, expectedBaseTypeName));
-
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = procName;
-                        cmd.CommandType = CommandType.StoredProcedure;
-                        SqlParameter p = cmd.Parameters.AddWithValue("@param", paramValue);
-                        cmd.Parameters[0].SqlDbType = GetSqlDbType(expectedBaseTypeName);
-                        using (SqlDataReader dr = cmd.ExecuteReader())
-                        {
-                            dr.Read();
-                            VerifyReaderTypeAndValue("Test Simple Parameter [Data Type]", expectedBaseTypeName, expectedTypeName, dr[0], expectedTypeName, paramValue);
-                            dr.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, procName);
-                }
-            }
-        }
-
-        // sql_variant parameters and sql_variant TVPs store all datetime values internally
-        // as datetime, hence breaking for katmai types
-        private static void TestSimpleParameter_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSimpleParameter_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string procName = DataTestUtility.GetUniqueNameForSqlServer("paramProc2");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, procName);
-                    xsql(conn, string.Format("create proc {0} (@param sql_variant) as begin select @param, sql_variant_property(@param,'BaseType') as BaseType end;", procName));
-
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = procName;
-                        cmd.CommandType = CommandType.StoredProcedure;
-                        SqlParameter p = cmd.Parameters.AddWithValue("@param", paramValue);
-                        cmd.Parameters[0].SqlDbType = SqlDbType.Variant;
-                        using (SqlDataReader dr = cmd.ExecuteReader())
-                        {
-                            dr.Read();
-                            VerifyReaderTypeAndValue("Test Simple Parameter [Variant Type]", "SqlDbType.Variant", dr, expectedTypeName, expectedBaseTypeName, paramValue);
-                            dr.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, procName);
-                }
-            }
-        }
-
-        private static void TestSqlDataRecordParameterToTVP_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSqlDataRecordParameterToTVP_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpType");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                    xsql(conn, string.Format("create type dbo.{0} as table (f1 {1})", tvpTypeName, expectedBaseTypeName));
-
-                    // Send TVP using SqlMetaData.
-                    SqlMetaData[] metadata = new SqlMetaData[1];
-                    metadata[0] = new SqlMetaData("f1", GetSqlDbType(expectedBaseTypeName));
-                    SqlDataRecord[] record = new SqlDataRecord[1];
-                    record[0] = new SqlDataRecord(metadata);
-                    record[0].SetValue(0, paramValue);
-
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = "select f1 from @tvpParam";
-                        SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", record);
-                        p.SqlDbType = SqlDbType.Structured;
-                        p.TypeName = string.Format("dbo.{0}", tvpTypeName);
-                        using (SqlDataReader dr = cmd.ExecuteReader())
-                        {
-                            dr.Read();
-                            VerifyReaderTypeAndValue("Test SqlDataRecord Parameter To TVP [Data Type]", expectedBaseTypeName, expectedTypeName, dr[0], expectedTypeName, paramValue);
-                            dr.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                }
-            }
-        }
-
-        // sql_variant parameters and sql_variant TVPs store all datetime values internally
-        // as datetime, hence breaking for katmai types
-        private static void TestSqlDataRecordParameterToTVP_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSqlDataRecordParameterToTVP_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpVariant");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                    xsql(conn, string.Format("create type dbo.{0} as table (f1 sql_variant)", tvpTypeName));
-
-                    // Send TVP using SqlMetaData.
-                    SqlMetaData[] metadata = new SqlMetaData[1];
-                    metadata[0] = new SqlMetaData("f1", SqlDbType.Variant);
-                    SqlDataRecord[] record = new SqlDataRecord[1];
-                    record[0] = new SqlDataRecord(metadata);
-                    record[0].SetValue(0, paramValue);
-
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = "select f1, sql_variant_property(f1,'BaseType') as BaseType from @tvpParam";
-                        SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", record);
-                        p.SqlDbType = SqlDbType.Structured;
-                        p.TypeName = string.Format("dbo.{0}", tvpTypeName);
-                        using (SqlDataReader dr = cmd.ExecuteReader())
-                        {
-                            dr.Read();
-                            VerifyReaderTypeAndValue("Test SqlDataRecord Parameter To TVP [Variant Type]", "SqlDbType.Variant", dr, expectedTypeName, expectedBaseTypeName, paramValue);
-                            dr.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                }
-            }
-        }
-
-        private static void TestSqlDataReaderParameterToTVP_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSqlDataReaderParameterToTVP_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpType");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                    xsql(conn, string.Format("create type dbo.{0} as table (f1 {1})", tvpTypeName, expectedBaseTypeName));
-
-                    // Send TVP using SqlDataReader.
-                    SqlConnection connInput = new SqlConnection(s_connStr);
-                    connInput.Open();
-
-                    using (SqlCommand cmdInput = connInput.CreateCommand())
-                    {
-                        cmdInput.CommandText = "select @p1 as f1";
-                        cmdInput.Parameters.Add("@p1", GetSqlDbType(expectedBaseTypeName));
-                        cmdInput.Parameters["@p1"].Value = paramValue;
-
-                        using (SqlDataReader drInput = cmdInput.ExecuteReader(CommandBehavior.CloseConnection))
-                        {
-                            using (SqlCommand cmd = conn.CreateCommand())
-                            {
-                                cmd.CommandText = "select f1 from @tvpParam";
-                                SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", drInput);
-                                p.SqlDbType = SqlDbType.Structured;
-                                p.TypeName = string.Format("dbo.{0}", tvpTypeName);
-                                using (SqlDataReader dr = cmd.ExecuteReader())
-                                {
-                                    dr.Read();
-                                    VerifyReaderTypeAndValue("Test SqlDataReader Parameter To TVP [Data Type]", expectedBaseTypeName, expectedTypeName, dr[0], expectedTypeName, paramValue);
-                                    dr.Dispose();
-                                }
-                            }
-                        }
-                    }
-                    connInput.Close();
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                }
-            }
-        }
-
-        // sql_variant parameters and sql_variant TVPs store all datetime values internally
-        // as datetime, hence breaking for katmai types
-        private static void TestSqlDataReaderParameterToTVP_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSqlDataReaderParameterToTVP_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpVariant");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                    xsql(conn, string.Format("create type dbo.{0} as table (f1 sql_variant)", tvpTypeName));
-
-                    // Send TVP using SqlDataReader.
-                    SqlConnection connInput = new SqlConnection(s_connStr);
-                    connInput.Open();
-                    using (SqlCommand cmdInput = connInput.CreateCommand())
-                    {
-                        cmdInput.CommandText = "select @p1 as f1";
-                        cmdInput.Parameters.Add("@p1", SqlDbType.Variant);
-                        cmdInput.Parameters["@p1"].Value = paramValue;
-                        using (SqlDataReader drInput = cmdInput.ExecuteReader(CommandBehavior.CloseConnection))
-                        {
-                            using (SqlCommand cmd = conn.CreateCommand())
-                            {
-                                cmd.CommandText = "select f1, sql_variant_property(f1,'BaseType') as BaseType from @tvpParam";
-                                SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", drInput);
-                                p.SqlDbType = SqlDbType.Structured;
-                                p.TypeName = string.Format("dbo.{0}", tvpTypeName);
-                                using (SqlDataReader dr = cmd.ExecuteReader())
-                                {
-                                    dr.Read();
-                                    VerifyReaderTypeAndValue("Test SqlDataReader Parameter To TVP [Variant Type]", "SqlDbType.Variant", dr, expectedTypeName, expectedBaseTypeName, paramValue);
-                                    dr.Dispose();
-                                }
-                            }
-                        }
-                    }
-                    connInput.Close();
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropType(conn, tvpTypeName);
-                }
-            }
-        }
-
-        // sql_variant parameters and sql_variant TVPs store all datetime values internally
-        // as datetime, hence breaking for katmai types
-        private static void TestSqlDataReader_TVP_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSqlDataReader_TVP_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpType");
-            string InputTableName = DataTestUtility.GetUniqueNameForSqlServer("InputTable");
-            string OutputTableName = DataTestUtility.GetUniqueNameForSqlServer("OutputTable");
-            string ProcName = DataTestUtility.GetUniqueNameForSqlServer("spTVPProc");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-
-                    DropStoredProcedure(conn, ProcName);
-                    DropTable(conn, InputTableName);
-                    DropTable(conn, OutputTableName);
-                    DropType(conn, $"dbo.{tvpTypeName}");
-
-                    xsql(conn, string.Format("create type dbo.{0} as table (f1 {1})", tvpTypeName, expectedBaseTypeName));
-                    xsql(conn, string.Format("create table {0} (f1 {1})", InputTableName, expectedBaseTypeName));
-                    xsql(conn, string.Format("create table {0} (f1 {1})", OutputTableName, expectedBaseTypeName));
-
-                    string value = string.Empty;
-                    if (paramValue.GetType() == typeof(System.DateTimeOffset))
-                    {
-                        DateTime dt = ((System.DateTimeOffset)paramValue).UtcDateTime;
-                        value = dt.ToShortDateString() + " " + dt.TimeOfDay;
-                    }
-                    else if (paramValue.GetType() == typeof(System.TimeSpan))
-                    {
-                        value = ((System.TimeSpan)paramValue).ToString();
-                    }
-                    else
-                    {
-                        value = ((System.DateTime)paramValue).ToShortDateString() + " " + ((System.DateTime)paramValue).TimeOfDay;
-                    }
-                    xsql(conn, string.Format("insert into {0} values(CAST('{1}' AS {2}))", InputTableName, value, expectedBaseTypeName));
-                    xsql(conn, string.Format("create proc {0} (@P {1} READONLY) as begin insert into {2} select * from @P; end", ProcName, tvpTypeName, OutputTableName));
-
-                    SqlCommand cmd = conn.CreateCommand();
-                    cmd.CommandText = string.Format("SELECT * FROM {0}", InputTableName);
-                    using (SqlDataReader r = cmd.ExecuteReader())
-                    {
-                        using (SqlConnection conn2 = new SqlConnection(s_connStr))
-                        {
-                            conn2.Open();
-                            SqlCommand cmd2 = new SqlCommand(ProcName, conn2);
-                            cmd2.CommandType = CommandType.StoredProcedure;
-                            SqlParameter p = cmd2.Parameters.AddWithValue("@P", r);
-                            p.SqlDbType = SqlDbType.Structured;
-                            p.TypeName = tvpTypeName;
-                            cmd2.ExecuteNonQuery();
-
-                            cmd2.CommandText = string.Format("SELECT f1 FROM {0}", OutputTableName);
-                            ;
-                            cmd2.CommandType = CommandType.Text;
-                            using (SqlDataReader dr = cmd2.ExecuteReader())
-                            {
-                                dr.Read();
-                                VerifyReaderTypeAndValue("Test SqlDataReader TVP [Data Type]", expectedBaseTypeName, expectedTypeName, dr[0], expectedTypeName, paramValue);
-                                dr.Dispose();
-                            }
-                            conn2.Close();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, ProcName);
-                    DropTable(conn, InputTableName);
-                    DropTable(conn, OutputTableName);
-                    DropType(conn, tvpTypeName);
-                }
-            }
-        }
-
-        private static void TestSqlDataReader_TVP_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSqlDataReader_TVP_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpVariant_DRdrTVPVar");
-            string InputTableName = DataTestUtility.GetUniqueNameForSqlServer("InputTable");
-            string OutputTableName = DataTestUtility.GetUniqueNameForSqlServer("OutputTable");
-            string ProcName = DataTestUtility.GetUniqueNameForSqlServer("spTVPProc_DRdrTVPVar");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-
-                    DropStoredProcedure(conn, ProcName);
-                    DropTable(conn, InputTableName);
-                    DropTable(conn, OutputTableName);
-                    DropType(conn, tvpTypeName);
-
-                    xsql(conn, string.Format("create type {0} as table (f1 sql_variant)", tvpTypeName));
-                    xsql(conn, string.Format("create table {0} (f1 sql_variant)", InputTableName));
-                    xsql(conn, string.Format("create table {0} (f1 sql_variant)", OutputTableName));
-
-                    string value = string.Empty;
-                    if (paramValue.GetType() == typeof(System.DateTimeOffset))
-                    {
-                        DateTime dt = ((System.DateTimeOffset)paramValue).UtcDateTime;
-                        value = dt.ToShortDateString() + " " + dt.TimeOfDay;
-                    }
-                    else if (paramValue.GetType() == typeof(System.TimeSpan))
-                    {
-                        value = ((System.TimeSpan)paramValue).ToString();
-                    }
-                    else
-                    {
-                        value = ((System.DateTime)paramValue).ToShortDateString() + " " + ((System.DateTime)paramValue).TimeOfDay;
-                    }
-                    xsql(conn, string.Format("insert into {0} values(CAST('{1}' AS {2}))", InputTableName, value, expectedBaseTypeName));
-                    xsql(conn, string.Format("create proc {0} (@P {1} READONLY) as begin insert into {2} select * from @P; end", ProcName, tvpTypeName, OutputTableName));
-
-                    SqlCommand cmd = conn.CreateCommand();
-                    cmd.CommandText = string.Format("SELECT * FROM {0}", InputTableName);
-                    using (SqlDataReader r = cmd.ExecuteReader())
-                    {
-                        using (SqlConnection conn2 = new SqlConnection(s_connStr))
-                        {
-                            conn2.Open();
-                            SqlCommand cmd2 = new SqlCommand(ProcName, conn2);
-                            cmd2.CommandType = CommandType.StoredProcedure;
-                            SqlParameter p = cmd2.Parameters.AddWithValue("@P", r);
-                            p.SqlDbType = SqlDbType.Structured;
-                            p.TypeName = tvpTypeName;
-                            cmd2.ExecuteNonQuery();
-
-                            cmd2.CommandText = string.Format("SELECT f1, sql_variant_property(f1,'BaseType') as BaseType FROM {0}", OutputTableName);
-                            ;
-                            cmd2.CommandType = CommandType.Text;
-                            using (SqlDataReader dr = cmd2.ExecuteReader())
-                            {
-                                dr.Read();
-                                VerifyReaderTypeAndValue("Test SqlDataReader TVP [Variant Type]", "SqlDbType.Variant", dr, expectedTypeName, expectedBaseTypeName, paramValue);
-                                dr.Dispose();
-                            }
-                            conn2.Close();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, ProcName);
-                    DropTable(conn, InputTableName);
-                    DropTable(conn, OutputTableName);
-                    DropType(conn, tvpTypeName);
-                }
-            }
-        }
-
-        // sql_variant parameters and sql_variant TVPs store all datetime values internally
-        // as datetime, hence breaking for katmai types
-        private static void TestSimpleDataReader_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSimpleDataReader_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string inputTable = DataTestUtility.GetUniqueNameForSqlServer("inputTable");
-            string procName = DataTestUtility.GetUniqueNameForSqlServer("paramProc3");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, inputTable);
-                    DropStoredProcedure(conn, procName);
-
-                    string value = string.Empty;
-                    if (paramValue.GetType() == typeof(System.DateTimeOffset))
-                    {
-                        DateTime dt = ((System.DateTimeOffset)paramValue).UtcDateTime;
-                        value = dt.ToShortDateString() + " " + dt.TimeOfDay;
-                    }
-                    else if (paramValue.GetType() == typeof(System.TimeSpan))
-                    {
-                        value = ((System.TimeSpan)paramValue).ToString();
-                    }
-                    else
-                    {
-                        value = ((System.DateTime)paramValue).ToShortDateString() + " " + ((System.DateTime)paramValue).TimeOfDay;
-                    }
-                    xsql(conn, string.Format("create table {0} (f1 {1})", inputTable, expectedBaseTypeName));
-                    xsql(conn, string.Format("insert into {0}(f1) values('{1}');", inputTable, value));
-                    xsql(conn, string.Format("create proc {0} as begin select f1 from {1} end;", procName, inputTable));
-
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = procName;
-                        cmd.CommandType = CommandType.StoredProcedure;
-                        using (SqlDataReader dr = cmd.ExecuteReader())
-                        {
-                            dr.Read();
-                            VerifyReaderTypeAndValue("Test Simple Data Reader [Data Type]", expectedBaseTypeName, expectedTypeName, dr[0], expectedTypeName, paramValue);
-                            dr.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, procName);
-                    DropTable(conn, inputTable);
-                }
-            }
-        }
-
-        private static void TestSimpleDataReader_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "TestSimpleDataReader_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string inputTable = DataTestUtility.GetUniqueNameForSqlServer("inputTable");
-            string procName = DataTestUtility.GetUniqueNameForSqlServer("paramProc4");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, inputTable);
-                    DropStoredProcedure(conn, procName);
-
-                    string value = string.Empty;
-                    if (paramValue.GetType() == typeof(System.DateTimeOffset))
-                    {
-                        DateTime dt = ((System.DateTimeOffset)paramValue).UtcDateTime;
-                        value = dt.ToShortDateString() + " " + dt.TimeOfDay;
-                    }
-                    else if (paramValue.GetType() == typeof(System.TimeSpan))
-                    {
-                        value = ((System.TimeSpan)paramValue).ToString();
-                    }
-                    else
-                    {
-                        value = ((System.DateTime)paramValue).ToShortDateString() + " " + ((System.DateTime)paramValue).TimeOfDay;
-                    }
-                    xsql(conn, string.Format("create table {0} (f1 sql_variant)", inputTable));
-                    xsql(conn, string.Format("insert into {0}(f1) values(CAST('{1}' AS {2}));", inputTable, value, expectedBaseTypeName));
-                    xsql(conn, string.Format("create proc {0} as begin select f1, sql_variant_property(f1,'BaseType') as BaseType from {1} end;", procName, inputTable));
-
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = procName;
-                        cmd.CommandType = CommandType.StoredProcedure;
-                        using (SqlDataReader dr = cmd.ExecuteReader())
-                        {
-                            dr.Read();
-                            VerifyReaderTypeAndValue("Test Simple Data Reader [Variant Type]", "SqlDbType.Variant", dr, expectedTypeName, expectedBaseTypeName, paramValue);
-                            dr.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropStoredProcedure(conn, procName);
-                    DropTable(conn, inputTable);
-                }
-            }
-        }
-
-        private static void SqlBulkCopySqlDataReader_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "SqlBulkCopySqlDataReader_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string bulkCopySrcTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkSrcTable");
-            string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDestTable");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    xsql(conn, string.Format("create table {0} (f1 {1})", bulkCopyTableName, expectedBaseTypeName));
-
-                    DropTable(conn, bulkCopySrcTableName);
-                    xsql(conn, string.Format("create table {0} (f1 {1})", bulkCopySrcTableName, expectedBaseTypeName));
-                    string value = string.Empty;
-                    if (paramValue.GetType() == typeof(System.DateTimeOffset))
-                    {
-                        DateTime dt = ((System.DateTimeOffset)paramValue).UtcDateTime;
-                        value = dt.ToShortDateString() + " " + dt.TimeOfDay;
-                    }
-                    else if (paramValue.GetType() == typeof(System.TimeSpan))
-                    {
-                        value = ((System.TimeSpan)paramValue).ToString();
-                    }
-                    else
-                    {
-                        value = ((System.DateTime)paramValue).ToShortDateString() + " " + ((System.DateTime)paramValue).TimeOfDay;
-                    }
-                    xsql(conn, string.Format("insert into {0}(f1) values(CAST('{1}' AS {2}));", bulkCopySrcTableName, value, expectedBaseTypeName));
-
-                    SqlConnection connInput = new SqlConnection(s_connStr);
-                    connInput.Open();
-                    using (SqlCommand cmdInput = connInput.CreateCommand())
-                    {
-                        cmdInput.CommandText = string.Format("select * from {0}", bulkCopySrcTableName);
-                        using (SqlDataReader drInput = cmdInput.ExecuteReader())
-                        {
-                            // Perform bulk copy to target.
-                            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
-                            {
-                                bulkCopy.BulkCopyTimeout = 60;
-                                bulkCopy.BatchSize = 1;
-                                bulkCopy.DestinationTableName = bulkCopyTableName;
-                                bulkCopy.WriteToServer(drInput);
-                            }
-
-                            // Verify target.
-                            using (SqlCommand cmd = conn.CreateCommand())
-                            {
-                                cmd.CommandText = string.Format("select f1 from {0}", bulkCopyTableName);
-                                using (SqlDataReader drVerify = cmd.ExecuteReader())
-                                {
-                                    drVerify.Read();
-                                    VerifyReaderTypeAndValue("SqlBulkCopy From SqlDataReader [Data Type]", expectedBaseTypeName, expectedTypeName, drVerify[0], expectedTypeName, paramValue);
-                                    drVerify.Dispose();
-                                }
-                            }
-                        }
-                    }
-                    connInput.Close();
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    DropTable(conn, bulkCopySrcTableName);
-                }
-            }
-
-        }
-
-        private static void SqlBulkCopySqlDataReader_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "SqlBulkCopySqlDataReader_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string bulkCopySrcTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkSrcTable");
-            string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDestTable");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    xsql(conn, string.Format("create table {0} (f1 sql_variant)", bulkCopyTableName));
-
-                    DropTable(conn, bulkCopySrcTableName);
-                    xsql(conn, string.Format("create table {0} (f1 {1})", bulkCopySrcTableName, expectedBaseTypeName));
-                    string value = string.Empty;
-                    if (paramValue.GetType() == typeof(System.DateTimeOffset))
-                    {
-                        DateTime dt = ((System.DateTimeOffset)paramValue).UtcDateTime;
-                        value = dt.ToShortDateString() + " " + dt.TimeOfDay;
-                    }
-                    else if (paramValue.GetType() == typeof(System.TimeSpan))
-                    {
-                        value = ((System.TimeSpan)paramValue).ToString();
-                    }
-                    else
-                    {
-                        value = ((System.DateTime)paramValue).ToShortDateString() + " " + ((System.DateTime)paramValue).TimeOfDay;
-                    }
-                    xsql(conn, string.Format("insert into {0}(f1) values(CAST('{1}' AS {2}));", bulkCopySrcTableName, value, expectedBaseTypeName));
-
-                    SqlConnection connInput = new SqlConnection(s_connStr);
-                    connInput.Open();
-                    using (SqlCommand cmdInput = connInput.CreateCommand())
-                    {
-                        cmdInput.CommandText = string.Format("select * from {0}", bulkCopySrcTableName);
-                        using (SqlDataReader drInput = cmdInput.ExecuteReader())
-                        {
-                            {
-                                // Perform bulk copy to target.
-                                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
-                                {
-                                    bulkCopy.BulkCopyTimeout = 60;
-                                    bulkCopy.BatchSize = 1;
-                                    bulkCopy.DestinationTableName = bulkCopyTableName;
-                                    bulkCopy.WriteToServer(drInput);
-                                }
-
-                                // Verify target.
-                                using (SqlCommand cmd = conn.CreateCommand())
-                                {
-                                    cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName);
-                                    using (SqlDataReader drVerify = cmd.ExecuteReader())
-                                    {
-                                        drVerify.Read();
-                                        VerifyReaderTypeAndValue("SqlBulkCopy From SqlDataReader [Variant Type]", "SqlDbType.Variant", drVerify, expectedTypeName, expectedBaseTypeName, paramValue);
-                                        drVerify.Dispose();
-                                    }
-                                }
-                            }
-                        }
-                    }
-                    connInput.Close();
-
-                    conn.Close();
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    DropTable(conn, bulkCopySrcTableName);
-                }
-            }
-        }
-
-        private static void SqlBulkCopyDataTable_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "SqlBulkCopyDataTable_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDestType");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    xsql(conn, string.Format("create table {0} (f1 {1})", bulkCopyTableName, expectedBaseTypeName));
-
-                    // Send using DataTable as source.
-                    DataTable t = new DataTable();
-                    t.Columns.Add("f1", paramValue.GetType());
-                    t.Rows.Add(new object[] { paramValue });
-
-                    // Perform bulk copy to target.
-                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
-                    {
-                        bulkCopy.BulkCopyTimeout = 60;
-                        bulkCopy.BatchSize = 1;
-                        bulkCopy.DestinationTableName = bulkCopyTableName;
-                        bulkCopy.WriteToServer(t, DataRowState.Added);
-                    }
-
-                    // Verify target.
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = string.Format("select f1 from {0}", bulkCopyTableName);
-                        using (SqlDataReader drVerify = cmd.ExecuteReader())
-                        {
-                            drVerify.Read();
-                            VerifyReaderTypeAndValue("SqlBulkCopy From Data Table [Data Type]", expectedBaseTypeName, expectedTypeName, drVerify[0], expectedTypeName, paramValue);
-                            drVerify.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                }
-            }
-        }
-
-        // sql_variant parameters and sql_variant TVPs store all datetime values internally
-        // as datetime, hence breaking for katmai types
-        private static void SqlBulkCopyDataTable_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "SqlBulkCopyDataTable_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDestVariant");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    xsql(conn, string.Format("create table {0} (f1 sql_variant)", bulkCopyTableName));
-
-                    // Send using DataTable as source.
-                    DataTable t = new DataTable();
-                    t.Columns.Add("f1", typeof(object));
-                    t.Rows.Add(new object[] { paramValue });
-
-                    // Perform bulk copy to target.
-                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
-                    {
-                        bulkCopy.BulkCopyTimeout = 60;
-                        bulkCopy.BatchSize = 1;
-                        bulkCopy.DestinationTableName = bulkCopyTableName;
-                        bulkCopy.WriteToServer(t, DataRowState.Added);
-                    }
-
-                    // Verify target.
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName);
-                        using (SqlDataReader drVerify = cmd.ExecuteReader())
-                        {
-                            drVerify.Read();
-                            VerifyReaderTypeAndValue("SqlBulkCopy From Data Table [Variant Type]", "SqlDbType.Variant", drVerify, expectedTypeName, expectedBaseTypeName, paramValue);
-                            drVerify.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                }
-            }
-        }
-
-        private static void SqlBulkCopyDataRow_Type(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "SqlBulkCopyDataRow_Type";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDestType");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    xsql(conn, string.Format("create table {0} (f1 {1})", bulkCopyTableName, expectedBaseTypeName));
-
-                    DataTable t = new DataTable();
-                    t.Columns.Add("f1", paramValue.GetType());
-                    t.Rows.Add(new object[] { paramValue });
-                    // Send using DataRow as source.
-                    DataRow[] rowToSend = t.Select();
-
-                    // Perform bulk copy to target.
-                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
-                    {
-                        bulkCopy.BulkCopyTimeout = 60;
-                        bulkCopy.BatchSize = 1;
-                        bulkCopy.DestinationTableName = bulkCopyTableName;
-                        bulkCopy.WriteToServer(rowToSend);
-                    }
-
-                    // Verify target.
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = string.Format("select f1 from {0}", bulkCopyTableName);
-                        using (SqlDataReader drVerify = cmd.ExecuteReader())
-                        {
-                            drVerify.Read();
-                            VerifyReaderTypeAndValue("SqlBulkCopy From Data Row [Data Type]", expectedBaseTypeName, expectedTypeName, drVerify[0], expectedTypeName, paramValue);
-                            drVerify.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                }
-            }
-        }
-
-        // sql_variant parameters and sql_variant TVPs store all datetime values internally
-        // as datetime, hence breaking for katmai types
-        private static void SqlBulkCopyDataRow_Variant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tag = "SqlBulkCopyDataRow_Variant";
-            DisplayHeader(tag, paramValue, expectedBaseTypeName);
-            string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDestVariant");
-            try
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                    xsql(conn, string.Format("create table {0} (f1 sql_variant)", bulkCopyTableName));
-
-                    DataTable t = new DataTable();
-                    t.Columns.Add("f1", typeof(object));
-                    t.Rows.Add(new object[] { paramValue });
-                    // Send using DataRow as source.
-                    DataRow[] rowToSend = t.Select();
-
-                    // Perform bulk copy to target.
-                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
-                    {
-                        bulkCopy.BulkCopyTimeout = 60;
-                        bulkCopy.BatchSize = 1;
-                        bulkCopy.DestinationTableName = bulkCopyTableName;
-                        bulkCopy.WriteToServer(rowToSend);
-                    }
-
-                    // Verify target.
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName);
-                        using (SqlDataReader drVerify = cmd.ExecuteReader())
-                        {
-                            drVerify.Read();
-                            VerifyReaderTypeAndValue("SqlBulkCopy From Data Row [Variant Type]", "SqlDbType.Variant", drVerify, expectedTypeName, expectedBaseTypeName, paramValue);
-                            drVerify.Dispose();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (IsExpectedException(e, paramValue, expectedTypeName, expectedBaseTypeName))
-                    LogMessage(tag, "[EXPECTED EXPECTION] " + e.Message);
-                else
-                    DisplayError(tag, e);
-            }
-            finally
-            {
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.Open();
-                    DropTable(conn, bulkCopyTableName);
-                }
-            }
-        }
-
-        // NOTE: Actions
-
-        private static SqlDbType GetSqlDbType(string expectedBaseTypeName)
-        {
-            switch (expectedBaseTypeName.ToLowerInvariant())
-            {
-                case "time":
-                    return SqlDbType.Time;
-                case "date":
-                    return SqlDbType.Date;
-                case "smalldatetime":
-                    return SqlDbType.SmallDateTime;
-                case "datetime":
-                    return SqlDbType.DateTime;
-                case "datetime2":
-                    return SqlDbType.DateTime2;
-                case "datetimeoffset":
-                    return SqlDbType.DateTimeOffset;
-                default:
-                    return SqlDbType.Variant;
-            }
-        }
-
-        private static void xsql(SqlConnection conn, string sql)
-        {
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                cmd.CommandText = sql;
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private static void DropStoredProcedure(SqlConnection conn, string procName)
-        {
-            xsql(conn, string.Format("if exists(select 1 from sys.procedures where name='{0}') begin drop proc {1} end", procName.Substring(1, procName.Length - 2), procName));
-        }
-
-        private static void DropTable(SqlConnection conn, string tableName)
-        {
-            xsql(conn, string.Format("if exists(select 1 from sys.tables where name='{0}') begin drop table {1} end", tableName.Substring(1, tableName.Length - 2), tableName));
-        }
-
-        private static void DropType(SqlConnection conn, string typeName)
-        {
-            xsql(conn, string.Format("if exists(select 1 from sys.types where name='{0}') begin drop type {1} end", typeName.Substring(1, typeName.Length - 2), typeName));
-        }
-
-        // NOTE: Checking and Verification
-        private static void VerifyReaderTypeAndValue(string tag, string expectedBaseTypeName, string type, object actualValue, string expectedTypeName, object expectedValue)
-        {
-            string actualTypeName = actualValue.GetType().ToString();
-
-            LogValues(tag, expectedTypeName, string.Empty, expectedValue, actualTypeName, string.Empty, actualValue);
-
-            if (!actualTypeName.Equals(expectedTypeName))
-            {
-                string ErrorMessage = string.Format(">>> ERROR: TYPE MISMATCH!!! [Actual = {0}] [Expected = {1}]",
-                    actualTypeName,
-                    expectedTypeName);
-
-                LogMessage(tag, ErrorMessage);
-            }
-            if (!actualValue.Equals(expectedValue))
-            {
-                string ErrorMessage = string.Empty;
-                if (IsValueCorrectForType(expectedBaseTypeName, expectedValue, actualValue))
-                {
-                    ErrorMessage = string.Format("[EXPECTED ERROR]: VALUE MISMATCH - [Actual = {0}] [Expected = {1}]",
-                    actualValue.ToString(),
-                    expectedValue.ToString());
-                }
-                else
-                {
-                    ErrorMessage = string.Format(">>> ERROR: VALUE MISMATCH!!! [Actual = {0}] [Expected = {1}]",
-                    actualValue.ToString(),
-                    expectedValue.ToString());
-                }
-                LogMessage(tag, ErrorMessage);
-            }
-        }
-
-        private static void VerifyReaderTypeAndValue(string tag, string type, SqlDataReader dr, string expectedTypeName, string expectedBaseTypeName, object expectedValue)
-        {
-            object actualValue = dr[0];
-            string actualTypeName = actualValue.GetType().ToString();
-            string actualBaseTypeName = dr.GetString(1);
-
-            LogValues(tag, expectedTypeName, expectedBaseTypeName, expectedValue, actualTypeName, actualBaseTypeName, actualValue);
-
-            if (!actualTypeName.Equals(expectedTypeName))
-            {
-                string ErrorMessage = string.Format(">>> ERROR: TYPE MISMATCH!!! [Actual = {0}] [Expected = {1}]",
-                    actualTypeName,
-                    expectedTypeName);
-                LogMessage(tag, ErrorMessage);
-            }
-            if (!actualBaseTypeName.Equals(expectedBaseTypeName))
-            {
-                if (((actualTypeName.ToLowerInvariant() != "system.datetime") || (actualTypeName.ToLowerInvariant() != "system.datetimeoffset"))
-                    && (actualBaseTypeName != "datetime2"))
-                {
-                    string ErrorMessage = string.Format(">>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = {0}] [Expected = {1}]",
-                        actualBaseTypeName,
-                        expectedBaseTypeName);
-                    LogMessage(tag, ErrorMessage);
-                }
-            }
-            if (!actualValue.Equals(expectedValue))
-            {
-                string ErrorMessage = string.Empty;
-                if (IsValueCorrectForType(expectedBaseTypeName, expectedValue, actualValue))
-                {
-                    ErrorMessage = string.Format("[EXPECTED ERROR]: VALUE MISMATCH - [Actual = {0}] [Expected = {1}]",
-                    actualValue.ToString(),
-                    expectedValue.ToString());
-                }
-                else
-                {
-                    ErrorMessage = string.Format(">>> ERROR: VALUE MISMATCH!!! [Actual = {0}] [Expected = {1}]",
-                    actualValue.ToString(),
-                    expectedValue.ToString());
-                }
-                LogMessage(tag, ErrorMessage);
-            }
-        }
-
-        private static bool IsValueCorrectForType(string expectedBaseTypeName, object expectedValue, object actualValue)
-        {
-            switch (expectedBaseTypeName)
-            {
-                case "date":
-                    if (((System.DateTime)expectedValue).ToShortDateString().Equals(((System.DateTime)actualValue).ToShortDateString()))
-                        return true;
-                    else
-                        return false;
-                case "datetime":
-                    if ((((System.DateTime)expectedValue).Ticks == 3155378975999999999) &&
-                        (((System.DateTime)actualValue).Ticks == 3155378975999970000))
-                        return true;
-                    else
-                        return false;
-                default:
-                    return false;
-            }
-        }
-
-        private static bool IsExpectedException(Exception e, object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            if ((e.GetType() == typeof(System.Data.SqlTypes.SqlTypeException)) &&
-                                (expectedBaseTypeName == "datetime") &&
-                                (e.Message.Contains("1753")) &&
-                                (((DateTime)paramValue).Year < 1753))
-            {
-                return true;
-            }
-            else if ((e.GetType() == typeof(SqlException)) &&
-                                (expectedBaseTypeName == "datetime") &&
-                                (e.Message.Contains("conversion of a varchar data type to a datetime data type")) &&
-                                (((DateTime)paramValue).Year < 1753))
-            {
-                return true;
-            }
-            else if ((e.GetType() == typeof(SqlException)) &&
-                                (expectedBaseTypeName == "datetime") &&
-                                (e.Message.Contains("converting date and/or time from character string")) &&
-                                (((DateTime)paramValue) == DateTime.MaxValue))
-            {
-                return true;
-            }
-            else
-            {
-                return false;
-            }
-        }
-
-        // NOTE: Logging and Display
-        private static void DisplayHeader(string tag, object paramValue, string expectedBaseTypeName)
-        {
-            Console.WriteLine("");
-            string value = string.Empty;
-            if (paramValue.GetType() == typeof(System.DateTimeOffset))
-            {
-                System.DateTimeOffset dt = (System.DateTimeOffset)paramValue;
-                value = dt.DateTime.ToShortDateString() + " " + dt.DateTime.TimeOfDay + " " + dt.Offset;
-            }
-            else if (paramValue.GetType() == typeof(System.TimeSpan))
-            {
-                value = ((System.TimeSpan)paramValue).ToString();
-            }
-            else
-            {
-                value = ((System.DateTime)paramValue).ToShortDateString() + " " + ((System.DateTime)paramValue).TimeOfDay;
-            }
-
-            Console.WriteLine(string.Format("------------------------------ {0} [type: {1} value:{2}] ------------------------------", tag, expectedBaseTypeName, value));
-        }
-
-        private static void DisplayError(string tag, Exception e)
-        {
-            string ExceptionMessage = string.Format(">>> EXCEPTION: [{0}] {1}", e.GetType(), e.Message);
-            LogMessage(tag, ExceptionMessage);
-        }
-
-        private static void LogMessage(string tag, string message)
-        {
-            Console.WriteLine(string.Format("{0}{1}", tag, message));
-        }
-
-        private static void LogValues(string tag, string expectedTypeName, string expectedBaseTypeName, object expectedValue, string actualTypeName, string actualBaseTypeName, object actualValue)
-        {
-            Console.WriteLine(string.Format("Type        => Expected : Actual == {0} : {1}", expectedTypeName, actualTypeName));
-            Console.WriteLine(string.Format("Base Type   => Expected : Actual == {0} : {1}", expectedBaseTypeName, actualBaseTypeName));
-            if (expectedTypeName == "System.DateTimeOffset")
-                Console.WriteLine(string.Format("Value       => Expected : Actual == {0} : {1}", ((DateTimeOffset)expectedValue).Ticks.ToString(), ((DateTimeOffset)actualValue).Ticks.ToString()));
-            else if (expectedTypeName == "System.DateTime")
-                Console.WriteLine(string.Format("Value       => Expected : Actual == {0} : {1}", ((DateTime)expectedValue).Ticks.ToString(), ((DateTime)actualValue).Ticks.ToString()));
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/OutputParameter.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/OutputParameter.cs
deleted file mode 100644 (file)
index b8f0ebd..0000000
+++ /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.Data;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class OutputParameter
-    {
-        public static void Run(string connectionString)
-        {
-            Console.WriteLine("Starting 'OutputParameter' tests");
-            InvalidValueInOutParam(connectionString);
-        }
-
-        // Changing the value of an output parameter to a value of different type throws System.FormatException
-        // You should be able to set an Output SqlParameter to an invalid value (e.g. a string in a decimal param) since we clear its value before starting
-        private static void InvalidValueInOutParam(string connectionString)
-        {
-            Console.WriteLine("Test setting output SqlParameter to an invalid value");
-
-            using (var connection = new SqlConnection(connectionString))
-            {
-                connection.Open();
-
-                // Command simply set the outparam
-                using (var command = new SqlCommand("SET @decimal = 1.23", connection))
-                {
-
-                    // Create valid param
-                    var decimalParam = new SqlParameter("decimal", new decimal(2.34)) { SqlDbType = SqlDbType.Decimal, Direction = ParameterDirection.Output, Scale = 2, Precision = 5 };
-                    command.Parameters.Add(decimalParam);
-                    // Set value of param to invalid value
-                    decimalParam.Value = "Not a decimal";
-
-                    // Execute
-                    command.ExecuteNonQuery();
-                    // Validate
-                    if (((decimal)decimalParam.Value) != new decimal(1.23))
-                    {
-                        Console.WriteLine("FAIL: Value is incorrect: {0}", decimalParam.Value);
-                    }
-                }
-            }
-
-            Console.WriteLine("Done");
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs
deleted file mode 100644 (file)
index 3b0d0b4..0000000
+++ /dev/null
@@ -1,259 +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.Data.Common;
-using System.Data.SqlTypes;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class ParametersTest
-    {
-        private static string s_connString = DataTestUtility.TcpConnStr;
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void CodeCoverageSqlClient()
-        {
-            SqlParameterCollection opc = new SqlCommand().Parameters;
-
-            Assert.True(opc.Count == 0, string.Format("FAILED: Expected count: {0}. Actual count: {1}.", 0, opc.Count));
-            Assert.False(((IList)opc).IsReadOnly, "FAILED: Expected collection to NOT be read only.");
-            Assert.False(((IList)opc).IsFixedSize, "FAILED: Expected collection to NOT be fixed size.");
-            Assert.False(((IList)opc).IsSynchronized, "FAILED: Expected collection to NOT be synchronized.");
-            DataTestUtility.AssertEqualsWithDescription("List`1", ((IList)opc).SyncRoot.GetType().Name, "FAILED: Incorrect SyncRoot Name");
-
-            {
-                string failValue;
-                DataTestUtility.AssertThrowsWrapper<IndexOutOfRangeException>(() => failValue = opc[0].ParameterName, "Invalid index 0 for this SqlParameterCollection with Count=0.");
-
-                DataTestUtility.AssertThrowsWrapper<IndexOutOfRangeException>(() => failValue = opc["@p1"].ParameterName, "An SqlParameter with ParameterName '@p1' is not contained by this SqlParameterCollection.");
-            }
-
-            DataTestUtility.AssertThrowsWrapper<ArgumentNullException>(() => opc.Add(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects.");
-
-            opc.Add((object)new SqlParameter());
-            IEnumerator enm = opc.GetEnumerator();
-            Assert.True(enm.MoveNext(), "FAILED: Expected MoveNext to be true");
-            DataTestUtility.AssertEqualsWithDescription("Parameter1", ((SqlParameter)enm.Current).ParameterName, "FAILED: Incorrect ParameterName");
-
-            opc.Add(new SqlParameter());
-            DataTestUtility.AssertEqualsWithDescription("Parameter2", opc[1].ParameterName, "FAILED: Incorrect ParameterName");
-
-            opc.Add(new SqlParameter(null, null));
-            opc.Add(null, SqlDbType.Int, 0, null);
-            DataTestUtility.AssertEqualsWithDescription("Parameter4", opc["Parameter4"].ParameterName, "FAILED: Incorrect ParameterName");
-
-            opc.Add(new SqlParameter("Parameter5", SqlDbType.NVarChar, 20));
-            opc.Add(new SqlParameter(null, SqlDbType.NVarChar, 20, "a"));
-            opc.RemoveAt(opc[3].ParameterName);
-            DataTestUtility.AssertEqualsWithDescription(-1, opc.IndexOf(null), "FAILED: Incorrect index for null value");
-
-            SqlParameter p = opc[0];
-
-            DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => opc.Add((object)p), "The SqlParameter is already contained by another SqlParameterCollection.");
-
-            DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => new SqlCommand().Parameters.Add(p), "The SqlParameter is already contained by another SqlParameterCollection.");
-
-            DataTestUtility.AssertThrowsWrapper<ArgumentNullException>(() => opc.Remove(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects.");
-
-            string pname = p.ParameterName;
-            p.ParameterName = pname;
-            p.ParameterName = pname.ToUpper();
-            p.ParameterName = pname.ToLower();
-            p.ParameterName = "@p1";
-            p.ParameterName = pname;
-
-            opc.Clear();
-            opc.Add(p);
-
-            opc.Clear();
-            opc.AddWithValue("@p1", null);
-
-            DataTestUtility.AssertEqualsWithDescription(-1, opc.IndexOf(p.ParameterName), "FAILED: Incorrect index for parameter name");
-
-            opc[0] = p;
-            DataTestUtility.AssertEqualsWithDescription(0, opc.IndexOf(p.ParameterName), "FAILED: Incorrect index for parameter name");
-
-            Assert.True(opc.Contains(p.ParameterName), "FAILED: Expected collection to contain provided parameter.");
-            Assert.True(opc.Contains(opc[0]), "FAILED: Expected collection to contain provided parameter.");
-
-            opc[0] = p;
-            opc[p.ParameterName] = new SqlParameter(p.ParameterName, null);
-            opc[p.ParameterName] = new SqlParameter();
-            opc.RemoveAt(0);
-
-            new SqlCommand().Parameters.Clear();
-            new SqlCommand().Parameters.CopyTo(new object[0], 0);
-            Assert.False(new SqlCommand().Parameters.GetEnumerator().MoveNext(), "FAILED: Expected MoveNext to be false");
-
-            DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => new SqlCommand().Parameters.Add(0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");
-
-            DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => new SqlCommand().Parameters.Insert(0, 0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");
-
-            DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => new SqlCommand().Parameters.Remove(0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");
-
-            DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => new SqlCommand().Parameters.Remove(new SqlParameter()), "Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection.");
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void Test_SqlParameter_Constructor()
-        {
-            using (var conn = new SqlConnection(s_connString))
-            {
-                var dataTable = new DataTable();
-                var adapter = new SqlDataAdapter();
-
-                adapter.SelectCommand = new SqlCommand("SELECT CustomerID, ContactTitle FROM dbo.Customers WHERE ContactTitle = @ContactTitle", conn);
-                var selectParam = new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30, ParameterDirection.Input, true, 0, 0, "ContactTitle", DataRowVersion.Current, "Owner");
-                adapter.SelectCommand.Parameters.Add(selectParam);
-
-                adapter.UpdateCommand = new SqlCommand("UPDATE dbo.Customers SET ContactTitle = @ContactTitle WHERE CustomerID = @CustomerID", conn);
-                var titleParam = new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30, ParameterDirection.Input, true, 0, 0, "ContactTitle", DataRowVersion.Current, null);
-                var idParam = new SqlParameter("@CustomerID", SqlDbType.NChar, 5, ParameterDirection.Input, false, 0, 0, "CustomerID", DataRowVersion.Current, null);
-                adapter.UpdateCommand.Parameters.Add(titleParam);
-                adapter.UpdateCommand.Parameters.Add(idParam);
-
-                adapter.Fill(dataTable);
-                object titleData = dataTable.Rows[0]["ContactTitle"];
-                Assert.Equal("Owner", (string)titleData);
-
-                titleData = "Test Data";
-                adapter.Update(dataTable);
-                adapter.Fill(dataTable);
-                Assert.Equal("Test Data", (string)titleData);
-
-                titleData = "Owner";
-                adapter.Update(dataTable);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void Test_WithEnumValue_ShouldInferToUnderlyingType()
-        {
-            using (var conn = new SqlConnection(s_connString))
-            {
-                conn.Open();
-                var cmd = new SqlCommand("select @input", conn);
-                cmd.Parameters.AddWithValue("@input", MyEnum.B);
-                object value = cmd.ExecuteScalar();
-                Assert.Equal(MyEnum.B, (MyEnum)value);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void Test_WithOutputEnumParameter_ShouldReturnEnum()
-        {
-            using (var conn = new SqlConnection(s_connString))
-            {
-                conn.Open();
-                var cmd = new SqlCommand("set @output = @input", conn);
-                cmd.Parameters.AddWithValue("@input", MyEnum.B);
-
-                var outputParam = cmd.CreateParameter();
-                outputParam.ParameterName = "@output";
-                outputParam.DbType = DbType.Int32;
-                outputParam.Direction = ParameterDirection.Output;
-                cmd.Parameters.Add(outputParam);
-
-                cmd.ExecuteNonQuery();
-
-                Assert.Equal(MyEnum.B, (MyEnum)outputParam.Value);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void Test_WithDecimalValue_ShouldReturnDecimal()
-        {
-            using (var conn = new SqlConnection(s_connString))
-            {
-                conn.Open();
-                var cmd = new SqlCommand("select @foo", conn);
-                cmd.Parameters.AddWithValue("@foo", new SqlDecimal(0.5));
-                var result = (decimal)cmd.ExecuteScalar();
-                Assert.Equal(result, (decimal)0.5);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void Test_WithGuidValue_ShouldReturnGuid()
-        {
-            using (var conn = new SqlConnection(s_connString))
-            {
-                conn.Open();
-                var expectedGuid = Guid.NewGuid();
-                var cmd = new SqlCommand("select @input", conn);
-                cmd.Parameters.AddWithValue("@input", expectedGuid);
-                var result = cmd.ExecuteScalar();
-                Assert.Equal(expectedGuid, (Guid)result);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestParametersWithDatatablesTVPInsert()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            builder.InitialCatalog = "tempdb";
-            int x = 4, y = 5;
-
-            DataTable table = new DataTable { Columns = { { "x", typeof(int) }, { "y", typeof(int) } }, Rows = { { x, y } } };
-
-            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
-            {
-                connection.Open();
-
-                ExecuteSqlIgnoreExceptions(connection, "drop proc dbo.UpdatePoint");
-                ExecuteSqlIgnoreExceptions(connection, "drop table dbo.PointTable");
-                ExecuteSqlIgnoreExceptions(connection, "drop type dbo.PointTableType");
-                ExecuteSqlIgnoreExceptions(connection, "CREATE TYPE dbo.PointTableType AS TABLE (x INT, y INT)");
-                ExecuteSqlIgnoreExceptions(connection, "CREATE TABLE dbo.PointTable (x INT, y INT)");
-                ExecuteSqlIgnoreExceptions(connection, "CREATE PROCEDURE dbo.UpdatePoint @TVP dbo.PointTableType READONLY AS SET NOCOUNT ON INSERT INTO dbo.PointTable(x, y) SELECT * FROM  @TVP");
-
-                using (SqlCommand cmd = connection.CreateCommand())
-                {
-                    // Update Data Using TVPs
-                    cmd.CommandText = "dbo.UpdatePoint";
-                    cmd.CommandType = CommandType.StoredProcedure;
-
-                    SqlParameter parameter = cmd.Parameters.AddWithValue("@TVP", table);
-                    parameter.TypeName = "dbo.PointTableType";
-
-                    cmd.ExecuteNonQuery();
-
-                    // Verify if the data was updated
-                    cmd.CommandText = "select * from dbo.PointTable";
-                    cmd.CommandType = CommandType.Text;
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        DataTable dbData = new DataTable();
-                        dbData.Load(reader);
-                        Assert.Equal(1, dbData.Rows.Count);
-                        Assert.Equal(x, dbData.Rows[0][0]);
-                        Assert.Equal(y, dbData.Rows[0][1]);
-                    }
-                }
-            }
-        }
-
-        private static void ExecuteSqlIgnoreExceptions(DbConnection connection, string query)
-        {
-            using (DbCommand cmd = connection.CreateCommand())
-            {
-                try
-                {
-                    cmd.CommandText = query;
-                    cmd.ExecuteNonQuery();
-                }
-                catch { /* Ignore exception if the command execution fails*/ }
-            }
-        }
-
-        private enum MyEnum
-        {
-            A = 1,
-            B = 2
-        }
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlAdapterUpdateBatch.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlAdapterUpdateBatch.cs
deleted file mode 100644 (file)
index 584a04f..0000000
+++ /dev/null
@@ -1,107 +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.Generic;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class SqlAdapterUpdateBatch
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void SqlAdapterTest()
-        {
-            string tableName = "BatchDemoTable";
-            try
-            {
-                var createTableQuery = "IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='BatchDemoTable' AND xtype='U')" +
-                    " CREATE TABLE [dbo].[" + tableName + "]([TransactionNumber][int] IDENTITY(1, 1) NOT NULL,[Level] [nvarchar] (50) NOT NULL," +
-                    "[Message] [nvarchar] (500) NOT NULL,[EventTime] [datetime]NOT NULL,CONSTRAINT[PK_BatchDemoTable] " +
-                    "PRIMARY KEY CLUSTERED([TransactionNumber] ASC)WITH(PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF, " +
-                    "IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON,FILLFACTOR = 90) ON[PRIMARY]) ON[PRIMARY]";
-
-                using (var connection = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (var cmd = new SqlCommand(createTableQuery, connection))
-                {
-                    connection.Open();
-                    cmd.ExecuteNonQuery();
-                }
-                ExecuteNonQueries();
-            }
-            catch (Exception ex)
-            {
-                Console.WriteLine(ex.Message);
-                Console.WriteLine(ex.StackTrace);
-            }
-            finally
-            {
-                var dropTableQuery = "DROP TABLE IF EXISTS " + tableName;
-                using (var connection = new SqlConnection(DataTestUtility.TcpConnStr))
-                using (var cmd = new SqlCommand(dropTableQuery, connection))
-                {
-                    connection.Open();
-                    cmd.ExecuteNonQuery();
-                }
-            }
-        }
-
-
-        private class EventInfo
-        {
-            public string Level { get; set; }
-            public string Message { get; set; }
-            public DateTime EventTime { get; set; }
-
-            public EventInfo()
-            {
-                EventTime = DateTime.Now;
-            }
-        }
-
-        private static void ExecuteNonQueries()
-        {
-            List<EventInfo> entities = new List<EventInfo>
-            {
-                new EventInfo {Level = "L1", Message = "Message 1"},
-                new EventInfo {Level = "L2", Message = "Message 2"},
-                new EventInfo {Level = "L3", Message = "Message 3"},
-                new EventInfo {Level = "L4", Message = "Message 4"},
-            };
-
-            var sql = "INSERT INTO BatchDemoTable(Level, Message, EventTime)  VALUES(@Level, @Message, @EventTime)";
-            using (var connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (var adapter = new SqlDataAdapter())
-            using (var cmd = new SqlCommand(sql, connection))
-            {
-                cmd.Parameters.Add(new SqlParameter("@Level", System.Data.SqlDbType.NVarChar, 50, "Level"));
-                cmd.Parameters.Add(new SqlParameter("@Message", SqlDbType.NVarChar, 500, "Message"));
-                cmd.Parameters.Add(new SqlParameter("@EventTime", SqlDbType.DateTime, 0, "EventTime"));
-                cmd.UpdatedRowSource = UpdateRowSource.None;
-
-                adapter.InsertCommand = cmd;
-                adapter.UpdateBatchSize = 2;
-
-                adapter.Update(ConvertToTable(entities));
-            }
-        }
-        private static DataTable ConvertToTable(List<EventInfo> entities)
-        {
-            var table = new DataTable(typeof(EventInfo).Name);
-
-            table.Columns.Add("Level", typeof(string));
-            table.Columns.Add("Message", typeof(string));
-            table.Columns.Add("EventTime", typeof(DateTime));
-
-            foreach (var entity in entities)
-            {
-                var row = table.NewRow();
-                row["Level"] = entity.Level;
-                row["Message"] = entity.Message;
-                row["EventTime"] = entity.EventTime;
-                table.Rows.Add(row);
-            }
-            return table;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlParameterTest_DebugMode.bsl b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlParameterTest_DebugMode.bsl
deleted file mode 100644 (file)
index 44ce911..0000000
+++ /dev/null
@@ -1,2234 +0,0 @@
-Starting test 'TvpTest'
-Starting Test using AsyncDebugScope
-Using stored procedure False
-TestStream (Sync True DataLen 100000 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 0 OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 9000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 1000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 0 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False OLD False AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR False OLD False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True OLD False AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR True OLD False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW False) is OK
-TestXml (Sync True LimitLength True ) is OK
-TestXml (Sync True LimitLength False ) is OK
-TestStream (Sync True DataLen 100000 ParamLen -1 OLD False AVW True) is OK
-TestStream (Sync True DataLen 0 ParamLen -1 OLD False AVW True) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error False OLD False AVW True) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error True OLD False AVW True) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW True) is OK
-TestXml (Sync True LimitLength False ) is OK
-TestStream (Sync False DataLen 100000 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 0 OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 9000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 1000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 0 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False OLD False AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR False OLD False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True OLD False AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR True OLD False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW False) is OK
-TestXml (Sync False LimitLength True ) is OK
-TestXml (Sync False LimitLength False ) is OK
-TestStream (Sync False DataLen 100000 ParamLen -1 OLD False AVW True) is OK
-TestStream (Sync False DataLen 0 ParamLen -1 OLD False AVW True) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error False OLD False AVW True) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error True OLD False AVW True) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW True) is OK
-TestXml (Sync False LimitLength False ) is OK
-TestStream (Sync True DataLen 100000 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 0 OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 9000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 1000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 0 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False OLD True AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR False OLD True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True OLD True AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR True OLD True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD True AVW False) is OK
-TestStream (Sync False DataLen 100000 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 0 OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 9000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 1000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 0 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False OLD True AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR False OLD True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True OLD True AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR True OLD True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD True AVW False) is OK
-Using stored procedure True
-TestStream (Sync True DataLen 100000 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 0 OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 9000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 1000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 0 Error False OLD False AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False OLD False AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR False OLD False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True OLD False AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR True OLD False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW False) is OK
-TestXml (Sync True LimitLength True ) is OK
-TestXml (Sync True LimitLength False ) is OK
-TestStream (Sync True DataLen 100000 ParamLen -1 OLD False AVW True) is OK
-TestStream (Sync True DataLen 0 ParamLen -1 OLD False AVW True) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error False OLD False AVW True) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error True OLD False AVW True) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW True) is OK
-TestXml (Sync True LimitLength False ) is OK
-TestStream (Sync False DataLen 100000 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen -1 OLD False AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 9000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 1000 OLD False AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 0 OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 9000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 1000 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 0 Error False OLD False AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR False OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False OLD False AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR False OLD False) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR False OLD False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR True OLD False AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True OLD False AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR True OLD False) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR True OLD False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD False AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW False) is OK
-TestXml (Sync False LimitLength True ) is OK
-TestXml (Sync False LimitLength False ) is OK
-TestStream (Sync False DataLen 100000 ParamLen -1 OLD False AVW True) is OK
-TestStream (Sync False DataLen 0 ParamLen -1 OLD False AVW True) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error False OLD False AVW True) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error True OLD False AVW True) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR True OLD False AVW True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD False AVW True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD False AVW True) is OK
-TestXml (Sync False LimitLength False ) is OK
-TestStream (Sync True DataLen 100000 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 500 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 0 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync True DataLen 10000 ParamLen 0 OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 9000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 1000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen 0 Error False OLD True AVW False) is OK
-TestCustomStream (Sync True DataLen 10000 ParamLen -1 Error True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False OLD True AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR False OLD True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 100000 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 500 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 0 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True OLD True AVW False) is OK
-TestXml2Text (Sync True ParamLen -1 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 9000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 1000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync True ParamLen 0 NVARCHAR True OLD True) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync True DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD True AVW False) is OK
-TestStream (Sync False DataLen 100000 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 500 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen -1 OLD True AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 9000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 0 ParamLen 1000 OLD True AVW False) is OK
-TestStream (Sync False DataLen 10000 ParamLen 0 OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 9000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 1000 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen 0 Error False OLD True AVW False) is OK
-TestCustomStream (Sync False DataLen 10000 ParamLen -1 Error True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR False OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False OLD True AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR False OLD True) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR False OLD True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR False Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR False Error True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 100000 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 500 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen -1 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 9000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 0 ParamLen 1000 NVARCHAR True OLD True AVW False) is OK
-TestTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True OLD True AVW False) is OK
-TestXml2Text (Sync False ParamLen -1 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 9000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 1000 NVARCHAR True OLD True) is OK
-TestXml2Text (Sync False ParamLen 0 NVARCHAR True OLD True) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 9000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 1000 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen 0 NVARCHAR True Error False OLD True AVW False) is OK
-TestCustomTextReader (Sync False DataLen 10000 ParamLen -1 NVARCHAR True Error True OLD True AVW False) is OK
-Finished Test using AsyncDebugScope
-Test immediate cancel for binary stream
-PASS: Task is cancelled
-Test immediate cancel for text stream
-PASS: Task is cancelled
-Test immediate cancel for xml stream
-PASS: Task is cancelled
-Test command preparation PASS
-Test reuse of command after cancel
-PASS
-Test reuse of command after cancel
-PASS
-Test reuse of command after cancel
-PASS
-+++++++ Iteration 0 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 1 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 2 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 3 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 4 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 5 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 6 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 7 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 8 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 9 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 10 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 11 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 12 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 13 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 14 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 15 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 16 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 17 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 18 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 19 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 20 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 28
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 14
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 21 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 22 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 23 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 24 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 25 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Matches = 162
-------DbDataReader---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Matches = 162
-------DataTables---------
-SqlException. Error Code: 242
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 26 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 27 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[2]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[10]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[11]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=1, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=2, Column=9
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=10, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=11, Column=9
-Matches = 158
-------DbDataReader---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[2]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[10]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[11]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=1, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=2, Column=9
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=10, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=11, Column=9
-Matches = 158
-------DataTables---------
-SqlException. Error Code: 242
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8115
-------- Sort order + uniqueness #1: simple -------
--------------
-0  Z-value  3/1/2000 12:00:00 AM  5  
-1  X-value  1/1/2000 12:00:00 AM  7  
-
--------------
-------- Sort order + uniqueness #2: mixed order -------
--------------
-4  X-value  1/1/2000 12:00:00 AM  3  
-5  X-value  3/1/2000 12:00:00 AM  3  
-
--------------
-------- default column #1: outer subset -------
--------------
--1  Y-value  1/1/2000 12:00:00 AM  -1  
--1  Z-value  1/1/2000 12:00:00 AM  -1  
-
--------------
-------- default column #1: middle subset -------
--------------
-4  DEFUALT  1/1/2006 12:00:00 AM  3  
-5  DEFUALT  1/1/2006 12:00:00 AM  3  
-
--------------
-------- default column #1: all -------
--------------
--1  DEFUALT  1/1/2006 12:00:00 AM  -1  
--1  DEFUALT  1/1/2006 12:00:00 AM  -1  
-
--------------
-
-Starting test 'SqlVariantParam'
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlSingle:real
-SendVariantParam                         -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlSingle:real
-SendVariantParam                         -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantParam                         -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDouble:float
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDouble:float
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDouble:float
-SendVariantParam                         -> System.Data.SqlTypes.SqlDouble:float
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlDouble:float
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlDouble:float
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantParam                         -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantParam                         -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantParam                         -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantParam                         -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantParam                         -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantParam                         -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlInt32:int
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlInt32:int
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlInt32:int
-SendVariantParam                         -> System.Data.SqlTypes.SqlInt32:int
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlInt32:int
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlInt32:int
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantParam                         -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantParam                         -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantParam                         -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDecimal:numeric
-   --> ERROR: Expected type System.Data.SqlTypes.SqlMoney does not match actual type System.Data.SqlTypes.SqlDecimal
-   --> ERROR: Expected base type money does not match actual base type numeric
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDecimal:numeric
-   --> ERROR: Expected type System.Data.SqlTypes.SqlMoney does not match actual type System.Data.SqlTypes.SqlDecimal
-   --> ERROR: Expected base type money does not match actual base type numeric
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDecimal:numeric
-   --> ERROR: Expected type System.Data.SqlTypes.SqlMoney does not match actual type System.Data.SqlTypes.SqlDecimal
-   --> ERROR: Expected base type money does not match actual base type numeric
-SendVariantParam                         -> System.Data.SqlTypes.SqlMoney:money
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlMoney:money
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlMoney:money
-End test 'SqlVariantParam'
-
------------------------------- TestSimpleParameter_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test Simple Parameter [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-Test Simple Parameter [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataRecord Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-Test SqlDataRecord Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataReader Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-Test SqlDataReader Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataReader TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataReader TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleDataReader_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test Simple Data Reader [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleDataReader_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test Simple Data Reader [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From SqlDataReader [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From SqlDataReader [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataTable_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From Data Table [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataTable_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-SqlBulkCopy From Data Table [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From Data Row [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-SqlBulkCopy From Data Row [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleParameter_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Type[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Variant[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Type[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Variant[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Type[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Variant[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Type[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Variant[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Type[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Variant[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Type[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Variant[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleParameter_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleParameter_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSimpleParameter_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- TestSimpleDataReader_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- TestSimpleDataReader_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSimpleParameter_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSimpleParameter_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSimpleDataReader_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSimpleDataReader_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopyDataTable_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- TestSimpleParameter_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- TestSimpleDataReader_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- TestSimpleDataReader_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- SqlBulkCopyDataTable_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- SqlBulkCopyDataTable_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- SqlBulkCopyDataRow_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-Type        => Expected : Actual == System.TimeSpan : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 00:00:00] [Expected = -10675199.02:48:05.4775808]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 0 (""), row 1, column 1: The supplied value is not a valid instance of data type sql_variant. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
-The statement has been terminated.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSimpleParameter_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Specified cast is not valid.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSimpleDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSimpleParameter_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Specified cast is not valid.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSimpleDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-Starting 'OutputParameter' tests
-Test setting output SqlParameter to an invalid value
-Done
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlParameterTest_ReleaseMode.bsl b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlParameterTest_ReleaseMode.bsl
deleted file mode 100644 (file)
index c28acb4..0000000
+++ /dev/null
@@ -1,1773 +0,0 @@
-Starting test 'TvpTest'
-Starting Test using AsyncDebugScope
-Tests using AsyncDebugScope are only supported in Debug mode!
-Finished Test using AsyncDebugScope
-Test immediate cancel for binary stream
-PASS: Task is cancelled
-Test immediate cancel for text stream
-PASS: Task is cancelled
-Test immediate cancel for xml stream
-PASS: Task is cancelled
-Test command preparation PASS
-Test reuse of command after cancel
-PASS
-Test reuse of command after cancel
-PASS
-Test reuse of command after cancel
-PASS
-+++++++ Iteration 0 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 1 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 2 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 3 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 4 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 5 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 6 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 7 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 8 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 9 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 10 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 11 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 12 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 13 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 14 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 15 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 16 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 17 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 18 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 19 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 20 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 28
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 14
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 21 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 22 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 23 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 24 ++++++++
-SqlException creating objects: 1701
-SqlException dropping objects: 3701
-+++++++ Iteration 25 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Matches = 162
-------DbDataReader---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Matches = 162
-------DataTables---------
-SqlException. Error Code: 242
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 26 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Matches = 168
-------DbDataReader---------
-Matches = 168
-------DataTables---------
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 28
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-Matches = 14
-+++++++ Iteration 27 ++++++++
-------IEnumerable<SqlDataRecord>---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[2]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[10]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[11]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=1, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=2, Column=9
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=10, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=11, Column=9
-Matches = 158
-------DbDataReader---------
-Failed Row[0]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[1]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[2]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[4]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[5]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[8]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[9]Col[5] = 1/1/1753 12:00:00 AM: Invalid value for this metadata.
-Failed Row[10]Col[9] = -922337203685477: SqlDbType.SmallMoney overflow.  Value '-922337203685477.0000' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Failed Row[11]Col[9] = 922337203685477.5807: SqlDbType.SmallMoney overflow.  Value '922337203685477.5807' is out of range.  Must be between -214,748.3648 and 214,748.3647.
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=0, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=1, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=1, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=2, Column=9
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=4, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=5, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=8, Column=5
-Mismatch: Source = 1/1/1753 12:00:00 AM, result = , metadata=SteAttributeKey=SmallDateTime
-   Row=9, Column=5
-Mismatch: Source = -922337203685477, result = , metadata=SteAttributeKey=SmallMoney
-   Row=10, Column=9
-Mismatch: Source = 922337203685477.5807, result = , metadata=SteAttributeKey=SmallMoney
-   Row=11, Column=9
-Matches = 158
-------DataTables---------
-SqlException. Error Code: 242
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8152
-SqlException. Error Code: 8115
-------- Sort order + uniqueness #1: simple -------
--------------
-0  Z-value  3/1/2000 12:00:00 AM  5  
-1  X-value  1/1/2000 12:00:00 AM  7  
-
--------------
-------- Sort order + uniqueness #2: mixed order -------
--------------
-4  X-value  1/1/2000 12:00:00 AM  3  
-5  X-value  3/1/2000 12:00:00 AM  3  
-
--------------
-------- default column #1: outer subset -------
--------------
--1  Y-value  1/1/2000 12:00:00 AM  -1  
--1  Z-value  1/1/2000 12:00:00 AM  -1  
-
--------------
-------- default column #1: middle subset -------
--------------
-4  DEFUALT  1/1/2006 12:00:00 AM  3  
-5  DEFUALT  1/1/2006 12:00:00 AM  3  
-
--------------
-------- default column #1: all -------
--------------
--1  DEFUALT  1/1/2006 12:00:00 AM  -1  
--1  DEFUALT  1/1/2006 12:00:00 AM  -1  
-
--------------
-
-Starting test 'SqlVariantParam'
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlSingle:real
-SendVariantParam                         -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlSingle:real
-SendVariantParam                         -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlSingle:real
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlSingle:real
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantParam                         -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlString:nvarchar
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDouble:float
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDouble:float
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDouble:float
-SendVariantParam                         -> System.Data.SqlTypes.SqlDouble:float
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlDouble:float
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlDouble:float
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantParam                         -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlBinary:varbinary
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantParam                         -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlGuid:uniqueidentifier
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantParam                         -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantParam                         -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlBoolean:bit
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantParam                         -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlByte:tinyint
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantParam                         -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlInt16:smallint
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlInt32:int
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlInt32:int
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlInt32:int
-SendVariantParam                         -> System.Data.SqlTypes.SqlInt32:int
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlInt32:int
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlInt32:int
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantParam                         -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlInt64:bigint
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantParam                         -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlDecimal:numeric
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantParam                         -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlDateTime:datetime
-SendVariantBulkCopy[SqlDataReader]       -> System.Data.SqlTypes.SqlDecimal:numeric
-   --> ERROR: Expected type System.Data.SqlTypes.SqlMoney does not match actual type System.Data.SqlTypes.SqlDecimal
-   --> ERROR: Expected base type money does not match actual base type numeric
-SendVariantBulkCopy[DataTable]           -> System.Data.SqlTypes.SqlDecimal:numeric
-   --> ERROR: Expected type System.Data.SqlTypes.SqlMoney does not match actual type System.Data.SqlTypes.SqlDecimal
-   --> ERROR: Expected base type money does not match actual base type numeric
-SendVariantBulkCopy[DataRow]             -> System.Data.SqlTypes.SqlDecimal:numeric
-   --> ERROR: Expected type System.Data.SqlTypes.SqlMoney does not match actual type System.Data.SqlTypes.SqlDecimal
-   --> ERROR: Expected base type money does not match actual base type numeric
-SendVariantParam                         -> System.Data.SqlTypes.SqlMoney:money
-SendVariantTvp[SqlMetaData]              -> System.Data.SqlTypes.SqlMoney:money
-SendVariantTvp[SqlDataReader]            -> System.Data.SqlTypes.SqlMoney:money
-End test 'SqlVariantParam'
-
------------------------------- TestSimpleParameter_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: date value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Variant [type: date value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test Simple Parameter [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-Test Simple Parameter [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataRecord Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-Test SqlDataRecord Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataReader Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-Test SqlDataReader Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataReader TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test SqlDataReader TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleDataReader_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test Simple Data Reader [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleDataReader_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-Test Simple Data Reader [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From SqlDataReader [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : date
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From SqlDataReader [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataTable_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From Data Table [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataTable_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-SqlBulkCopy From Data Table [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378112000000000
-SqlBulkCopy From Data Row [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 12:00:00 AM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Variant [type: date value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == date : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = date]
-SqlBulkCopy From Data Row [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime2 value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleParameter_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime2 value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Type[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Variant[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Type[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Variant[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Type[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Variant[EXPECTED EXPECTION] The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Type[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant[EXPECTED EXPECTION] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Type[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Variant[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Type[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Variant[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Type[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Variant[EXPECTED EXPECTION] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Data Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type][EXPECTED ERROR]: VALUE MISMATCH - [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleDataReader_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 0 : 0
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetimeoffset value:1/1/0001 00:00:00 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 0 : 0
-
------------------------------- TestSimpleParameter_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleParameter_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleDataReader_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetimeoffset value:12/31/9999 23:59:59.9999999 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999999999
-
------------------------------- TestSimpleParameter_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSimpleParameter_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- TestSimpleDataReader_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- TestSimpleDataReader_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630823121999999999
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetimeoffset value:12/31/1999 23:59:59.9999999 -08:30:00] ------------------------------
-Type        => Expected : Actual == System.DateTimeOffset : System.DateTimeOffset
-Base Type   => Expected : Actual == datetimeoffset : datetimeoffset
-Value       => Expected : Actual == 630822815999999999 : 630822815999999999
-
------------------------------- TestSimpleParameter_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSimpleParameter_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSqlDataReader_TVP_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSimpleDataReader_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- TestSimpleDataReader_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime2
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopyDataTable_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopyDataTable_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual ==  : 
-Value       => Expected : Actual == 630192959999950000 : 630192959999950000
-
------------------------------- SqlBulkCopyDataRow_Variant [type: datetime2 value:1/1/1998 23:59:59.9950000] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == datetime2 : datetime
-Value       => Expected : Actual == 630192959999950000 : 630192959999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = datetime2]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 1/1/1998 11:59:59 PM] [Expected = 1/1/1998 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- TestSimpleDataReader_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
-The statement has been terminated.
-
------------------------------- SqlBulkCopyDataTable_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: smalldatetime value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- TestSimpleParameter_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- TestSimpleDataReader_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- TestSimpleDataReader_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting character string to smalldatetime data type.
-
------------------------------- SqlBulkCopyDataTable_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- SqlBulkCopyDataTable_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.ArgumentOutOfRangeException] The added or subtracted value results in an un-representable DateTime.
-Parameter name: value
-
------------------------------- SqlBulkCopyDataRow_Variant [type: smalldatetime value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == smalldatetime : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = smalldatetime]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSimpleParameter_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-Type        => Expected : Actual == System.TimeSpan : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 00:00:00] [Expected = -10675199.02:48:05.4775808]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:-10675199.02:48:05.4775808] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '-10675199.02:48:05.4775808' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.ArgumentException] Invalid value for this metadata.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 0 (""), row 1, column 1: The supplied value is not a valid instance of data type sql_variant. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
-The statement has been terminated.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.Data.SqlClient.SqlException] Conversion failed when converting date and/or time from character string.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:10675199.02:48:05.4775807] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.OverflowException] SqlDbType.Time overflow.  Value '10675199.02:48:05.4775807' is out of range.  Must be between 00:00:00.0000000 and 23:59:59.9999999.
-
------------------------------- TestSimpleParameter_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSimpleParameter_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSimpleParameter_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Specified cast is not valid.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataRecordParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-TestSqlDataReaderParameterToTVP_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSimpleDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataTable_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:1/1/0001 00:00:00] ------------------------------
-SqlBulkCopyDataRow_Variant>>> EXCEPTION: [System.Data.SqlTypes.SqlTypeException] SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
-
------------------------------- TestSimpleParameter_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSimpleParameter_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSimpleParameter_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test Simple Parameter [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-Test Simple Parameter [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataRecordParameterToTVP_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataRecordParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Specified cast is not valid.
-
------------------------------- TestSqlDataRecordParameterToTVP_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-Test SqlDataRecord Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReaderParameterToTVP_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-TestSqlDataReaderParameterToTVP_Type>>> EXCEPTION: [System.InvalidCastException] Failed to convert parameter value from a DateTime to a TimeSpan.
-
------------------------------- TestSqlDataReaderParameterToTVP_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-Test SqlDataReader Parameter To TVP [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- TestSqlDataReader_TVP_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSqlDataReader_TVP_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSqlDataReader_TVP_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSqlDataReader_TVP_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-TestSimpleDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- TestSimpleDataReader_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-TestSimpleDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual ==  : 
-SqlBulkCopySqlDataReader_Type>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopySqlDataReader_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.TimeSpan
-Base Type   => Expected : Actual == time : time
-SqlBulkCopySqlDataReader_Variant>>> EXCEPTION: [System.InvalidCastException] Unable to cast object of type 'System.TimeSpan' to type 'System.DateTime'.
-
------------------------------- SqlBulkCopyDataTable_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataTable_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataTable_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-SqlBulkCopy From Data Table [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-
------------------------------- SqlBulkCopyDataRow_Type [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-SqlBulkCopyDataRow_Type>>> EXCEPTION: [System.InvalidOperationException] The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
-
------------------------------- SqlBulkCopyDataRow_Variant [type: time value:12/31/9999 23:59:59.9999999] ------------------------------
-Type        => Expected : Actual == System.DateTime : System.DateTime
-Base Type   => Expected : Actual == time : datetime
-Value       => Expected : Actual == 3155378975999999999 : 3155378975999970000
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VARIANT BASE TYPE MISMATCH!!! [Actual = datetime] [Expected = time]
-SqlBulkCopy From Data Row [Variant Type]>>> ERROR: VALUE MISMATCH!!! [Actual = 12/31/9999 11:59:59 PM] [Expected = 12/31/9999 11:59:59 PM]
-Starting 'OutputParameter' tests
-Test setting output SqlParameter to an invalid value
-Done
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlVariantParam.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlVariantParam.cs
deleted file mode 100644 (file)
index b6eb3a9..0000000
+++ /dev/null
@@ -1,289 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Text;
-using System.Data;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.IO;
-using Microsoft.SqlServer.Server;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class SqlVariantParam
-    {
-        private static string s_connStr;
-
-        /// <summary>
-        /// Tests all SqlTypes inside sql_variant to server using sql_variant parameter, SqlBulkCopy, and TVP parameter with sql_variant inside.
-        /// </summary>
-        public static void SendAllSqlTypesInsideVariant(string connStr)
-        {
-            s_connStr = connStr;
-            Console.WriteLine("");
-            Console.WriteLine("Starting test 'SqlVariantParam'");
-            SendVariant(new SqlSingle((float)123.45), "System.Data.SqlTypes.SqlSingle", "real");
-            SendVariant(new SqlSingle((double)123.45), "System.Data.SqlTypes.SqlSingle", "real");
-            SendVariant(new SqlString("hello"), "System.Data.SqlTypes.SqlString", "nvarchar");
-            SendVariant(new SqlDouble((double)123.45), "System.Data.SqlTypes.SqlDouble", "float");
-            SendVariant(new SqlBinary(new byte[] { 0x00, 0x11, 0x22 }), "System.Data.SqlTypes.SqlBinary", "varbinary");
-            SendVariant(new SqlGuid(Guid.NewGuid()), "System.Data.SqlTypes.SqlGuid", "uniqueidentifier");
-            SendVariant(new SqlBoolean(true), "System.Data.SqlTypes.SqlBoolean", "bit");
-            SendVariant(new SqlBoolean(1), "System.Data.SqlTypes.SqlBoolean", "bit");
-            SendVariant(new SqlByte(1), "System.Data.SqlTypes.SqlByte", "tinyint");
-            SendVariant(new SqlInt16(1), "System.Data.SqlTypes.SqlInt16", "smallint");
-            SendVariant(new SqlInt32(1), "System.Data.SqlTypes.SqlInt32", "int");
-            SendVariant(new SqlInt64(1), "System.Data.SqlTypes.SqlInt64", "bigint");
-            SendVariant(new SqlDecimal(1234.123M), "System.Data.SqlTypes.SqlDecimal", "numeric");
-            SendVariant(new SqlDateTime(DateTime.Now), "System.Data.SqlTypes.SqlDateTime", "datetime");
-            SendVariant(new SqlMoney(123.123M), "System.Data.SqlTypes.SqlMoney", "money");
-            Console.WriteLine("End test 'SqlVariantParam'");
-        }
-        /// <summary>
-        /// Returns a SqlDataReader with embedded sql_variant column with paramValue inside.
-        /// </summary>
-        /// <param name="paramValue">object value to embed as sql_variant field value</param>
-        /// <param name="includeBaseType">Set to true to return optional BaseType column which extracts base type of sql_variant column.</param>
-        /// <returns></returns>
-        private static SqlDataReader GetReaderForVariant(object paramValue, bool includeBaseType)
-        {
-            SqlConnection conn = new SqlConnection(s_connStr);
-            conn.Open();
-            SqlCommand cmd = conn.CreateCommand();
-            cmd.CommandText = "select @p1 as f1";
-            if (includeBaseType)
-                cmd.CommandText += ", sql_variant_property(@p1,'BaseType') as BaseType";
-            cmd.Parameters.Add("@p1", SqlDbType.Variant);
-            cmd.Parameters["@p1"].Value = paramValue;
-            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
-            return dr;
-        }
-        /// <summary>
-        /// Verifies if SqlDataReader returns expected SqlType and base type.
-        /// </summary>
-        /// <param name="tag">Test tag to identify caller</param>
-        /// <param name="dr">SqlDataReader to verify</param>
-        /// <param name="expectedTypeName">Expected type name (SqlType)</param>
-        /// <param name="expectedBaseTypeName">Expected base type name (Sql Server type name)</param>
-        private static void VerifyReader(string tag, SqlDataReader dr, string expectedTypeName, string expectedBaseTypeName)
-        {
-            // select sql_variant_property(cast(cast(123.45 as money) as sql_variant),'BaseType' ) as f1
-            dr.Read();
-            string actualTypeName = dr.GetSqlValue(0).GetType().ToString();
-            string actualBaseTypeName = dr.GetString(1);
-            Console.WriteLine("{0,-40} -> {1}:{2}", tag, actualTypeName, actualBaseTypeName);
-            if (!actualTypeName.Equals(expectedTypeName))
-            {
-                Console.WriteLine("   --> ERROR: Expected type {0} does not match actual type {1}",
-                    expectedTypeName, actualTypeName);
-            }
-            if (!actualBaseTypeName.Equals(expectedBaseTypeName))
-            {
-                Console.WriteLine("   --> ERROR: Expected base type {0} does not match actual base type {1}",
-                    expectedBaseTypeName, actualBaseTypeName);
-            }
-        }
-        /// <summary>
-        /// Round trips a sql_variant to server and verifies result.
-        /// </summary>
-        /// <param name="paramValue">Value to send as sql_variant</param>
-        /// <param name="expectedTypeName">Expected SqlType name to round trip</param>
-        /// <param name="expectedBaseTypeName">Expected base type name (SQL Server base type inside sql_variant)</param>
-        private static void SendVariant(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            // Round trip using Bulk Copy, normal param, and TVP param.
-            SendVariantBulkCopy(paramValue, expectedTypeName, expectedBaseTypeName);
-            SendVariantParam(paramValue, expectedTypeName, expectedBaseTypeName);
-            SendVariantTvp(paramValue, expectedTypeName, expectedBaseTypeName);
-        }
-        /// <summary>
-        /// Round trip sql_variant value as normal parameter.
-        /// </summary>
-        private static void SendVariantParam(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            using (SqlDataReader dr = GetReaderForVariant(paramValue, true))
-            {
-                VerifyReader("SendVariantParam", dr, expectedTypeName, expectedBaseTypeName);
-            }
-        }
-        /// <summary>
-        /// Round trip sql_variant value using SqlBulkCopy.
-        /// </summary>
-        private static void SendVariantBulkCopy(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string bulkCopyTableName = DataTestUtility.GetUniqueNameForSqlServer("bulkDest");
-
-            // Fetch reader using type.
-            using (SqlDataReader dr = GetReaderForVariant(paramValue, false))
-            {
-                using (SqlConnection connBulk = new SqlConnection(s_connStr))
-                {
-                    connBulk.Open();
-
-                    ExecuteSQL(connBulk, "create table dbo.{0} (f1 sql_variant)", bulkCopyTableName);
-                    try
-                    {
-                        // Perform bulk copy to target.
-                        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connBulk))
-                        {
-                            bulkCopy.BulkCopyTimeout = 60;
-                            bulkCopy.BatchSize = 1;
-                            bulkCopy.DestinationTableName = bulkCopyTableName;
-                            bulkCopy.WriteToServer(dr);
-                        }
-
-                        // Verify target.
-                        using (SqlCommand cmd = connBulk.CreateCommand())
-                        {
-                            cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName);
-                            using (SqlDataReader drVerify = cmd.ExecuteReader())
-                            {
-                                VerifyReader("SendVariantBulkCopy[SqlDataReader]", drVerify, expectedTypeName, expectedBaseTypeName);
-                            }
-                        }
-
-                        // Truncate target table for next pass.
-                        ExecuteSQL(connBulk, "truncate table {0}", bulkCopyTableName);
-
-                        // Send using DataTable as source.
-                        DataTable t = new DataTable();
-                        t.Columns.Add("f1", typeof(object));
-                        t.Rows.Add(new object[] { paramValue });
-
-                        // Perform bulk copy to target.
-                        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connBulk))
-                        {
-                            bulkCopy.BulkCopyTimeout = 60;
-                            bulkCopy.BatchSize = 1;
-                            bulkCopy.DestinationTableName = bulkCopyTableName;
-                            bulkCopy.WriteToServer(t, DataRowState.Added);
-                        }
-
-                        // Verify target.
-                        using (SqlCommand cmd = connBulk.CreateCommand())
-                        {
-                            cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName);
-                            using (SqlDataReader drVerify = cmd.ExecuteReader())
-                            {
-                                VerifyReader("SendVariantBulkCopy[DataTable]", drVerify, expectedTypeName, expectedBaseTypeName);
-                            }
-                        }
-
-                        // Truncate target table for next pass.
-                        ExecuteSQL(connBulk, "truncate table {0}", bulkCopyTableName);
-
-                        // Send using DataRow as source.
-                        DataRow[] rowToSend = t.Select();
-
-                        // Perform bulk copy to target.
-                        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connBulk))
-                        {
-                            bulkCopy.BulkCopyTimeout = 60;
-                            bulkCopy.BatchSize = 1;
-                            bulkCopy.DestinationTableName = bulkCopyTableName;
-                            bulkCopy.WriteToServer(rowToSend);
-                        }
-
-                        // Verify target.
-                        using (SqlCommand cmd = connBulk.CreateCommand())
-                        {
-                            cmd.CommandText = string.Format("select f1, sql_variant_property(f1,'BaseType') as BaseType from {0}", bulkCopyTableName);
-                            using (SqlDataReader drVerify = cmd.ExecuteReader())
-                            {
-                                VerifyReader("SendVariantBulkCopy[DataRow]", drVerify, expectedTypeName, expectedBaseTypeName);
-                            }
-                        }
-                    }
-                    finally
-                    {
-                        // Cleanup target table.
-                        ExecuteSQL(connBulk, "drop table {0}", bulkCopyTableName);
-                    }
-                }
-            }
-        }
-        /// <summary>
-        /// Round trip sql_variant value using TVP.
-        /// </summary>
-        private static void SendVariantTvp(object paramValue, string expectedTypeName, string expectedBaseTypeName)
-        {
-            string tvpTypeName = DataTestUtility.GetUniqueNameForSqlServer("tvpVariant");
-
-            using (SqlConnection connTvp = new SqlConnection(s_connStr))
-            {
-                connTvp.Open();
-
-                ExecuteSQL(connTvp, "create type dbo.{0} as table (f1 sql_variant)", tvpTypeName);
-                try
-                {
-                    // Send TVP using SqlMetaData.
-                    SqlMetaData[] metadata = new SqlMetaData[1];
-                    metadata[0] = new SqlMetaData("f1", SqlDbType.Variant);
-                    SqlDataRecord[] record = new SqlDataRecord[1];
-                    record[0] = new SqlDataRecord(metadata);
-                    record[0].SetValue(0, paramValue);
-
-                    using (SqlCommand cmd = connTvp.CreateCommand())
-                    {
-                        cmd.CommandText = "select f1, sql_variant_property(f1,'BaseType') as BaseType from @tvpParam";
-                        SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", record);
-                        p.SqlDbType = SqlDbType.Structured;
-                        p.TypeName = string.Format("dbo.{0}", tvpTypeName);
-                        using (SqlDataReader dr = cmd.ExecuteReader())
-                        {
-                            VerifyReader("SendVariantTvp[SqlMetaData]", dr, expectedTypeName, expectedBaseTypeName);
-                        }
-                    }
-
-                    // Send TVP using SqlDataReader.
-                    using (SqlDataReader dr = GetReaderForVariant(paramValue, false))
-                    {
-                        using (SqlCommand cmd = connTvp.CreateCommand())
-                        {
-                            cmd.CommandText = "select f1, sql_variant_property(f1,'BaseType') as BaseType from @tvpParam";
-                            SqlParameter p = cmd.Parameters.AddWithValue("@tvpParam", dr);
-                            p.SqlDbType = SqlDbType.Structured;
-                            p.TypeName = string.Format("dbo.{0}", tvpTypeName);
-                            using (SqlDataReader dr2 = cmd.ExecuteReader())
-                            {
-                                VerifyReader("SendVariantTvp[SqlDataReader]", dr2, expectedTypeName, expectedBaseTypeName);
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    // Cleanup tvp type.
-                    ExecuteSQL(connTvp, "drop type {0}", tvpTypeName);
-                }
-            }
-        }
-        /// <summary>
-        /// Helper to execute t-sql with variable object name.
-        /// </summary>
-        /// <param name="conn"></param>
-        /// <param name="formatSql">Format string using {0} to designate where to place objectName</param>
-        /// <param name="objectName">Variable object name for t-sql</param>
-        private static void ExecuteSQL(SqlConnection conn, string formatSql, string objectName)
-        {
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                cmd.CommandText = string.Format(formatSql, objectName);
-                cmd.ExecuteNonQuery();
-            }
-        }
-        /// <summary>
-        /// Simple helper to execute t-sql.
-        /// </summary>
-        private static void ExecuteSQL(SqlConnection conn, string sql)
-        {
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                cmd.CommandText = sql;
-                cmd.ExecuteNonQuery();
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteAttribute.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteAttribute.cs
deleted file mode 100644 (file)
index 46eccb6..0000000
+++ /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.Collections.Generic;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class SteAttributeKey
-    {
-        public static readonly SteAttributeKey SqlDbType = new SteAttributeKey();
-        public static readonly SteAttributeKey MultiValued = new SteAttributeKey();
-        public static readonly SteAttributeKey Value = new SteAttributeKey();
-        public static readonly SteAttributeKey MaxLength = new SteAttributeKey();
-        public static readonly SteAttributeKey Precision = new SteAttributeKey();
-        public static readonly SteAttributeKey Scale = new SteAttributeKey();
-        public static readonly SteAttributeKey LocaleId = new SteAttributeKey();
-        public static readonly SteAttributeKey CompareOptions = new SteAttributeKey();
-        public static readonly SteAttributeKey TypeName = new SteAttributeKey();
-        public static readonly SteAttributeKey Type = new SteAttributeKey();
-        public static readonly SteAttributeKey Fields = new SteAttributeKey();
-        public static readonly SteAttributeKey Offset = new SteAttributeKey();
-        public static readonly SteAttributeKey Length = new SteAttributeKey();
-
-        public static readonly IList<SteAttributeKey> MetaDataKeys = new List<SteAttributeKey>(
-                new SteAttributeKey[] {
-                    SteAttributeKey.SqlDbType,
-                    SteAttributeKey.MultiValued,
-                    SteAttributeKey.MaxLength,
-                    SteAttributeKey.Precision,
-                    SteAttributeKey.Scale,
-                    SteAttributeKey.LocaleId,
-                    SteAttributeKey.CompareOptions,
-                    SteAttributeKey.TypeName,
-                    SteAttributeKey.Type,
-                    SteAttributeKey.Fields,
-                }
-            ).AsReadOnly();
-
-        public static IList<SteAttributeKey> ValueKeys = new List<SteAttributeKey>(
-                new SteAttributeKey[] { SteAttributeKey.Value }
-            ).AsReadOnly();
-    }
-
-    public class SteAttribute
-    {
-        private SteAttributeKey _key;
-        private object _value;
-
-        public SteAttribute(SteAttributeKey key, object value)
-        {
-            _key = key;
-            _value = value;
-        }
-
-        public SteAttributeKey Key
-        {
-            get
-            {
-                return _key;
-            }
-        }
-
-        public object Value
-        {
-            get
-            {
-                return _value;
-            }
-        }
-    }
-
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteParam.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteParam.cs
deleted file mode 100644 (file)
index c28b7d8..0000000
+++ /dev/null
@@ -1,70 +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.Data;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class SteParam
-    {
-        // Map values from a permutation into a parameter (doesn't currently map values)
-        public static void Map(StePermutation perm, SqlParameter param)
-        {
-            object attr;
-            bool didSetSqlDbType = false;
-            if (perm.TryGetValue(SteAttributeKey.SqlDbType, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                param.SqlDbType = (SqlDbType)attr;
-                didSetSqlDbType = true;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.MaxLength, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                param.Size = (int)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.Precision, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                param.Precision = (byte)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.Scale, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                param.Scale = (byte)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.LocaleId, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                param.LocaleId = (int)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.CompareOptions, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                param.CompareInfo = (SqlCompareOptions)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.TypeName, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                if (didSetSqlDbType && SqlDbType.Structured == param.SqlDbType)
-                {
-                    param.TypeName = (string)attr;
-                }
-                else
-                {
-                    // assume UdtType by default.
-                    //param.UdtTypeName = (string)attr;
-                    throw new NotSupportedException("SqlParameter.UdtTypeName is not supported");
-                }
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.Offset, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                param.Offset = (int)attr;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/StePermutationSet.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/StePermutationSet.cs
deleted file mode 100644 (file)
index d18afb7..0000000
+++ /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;
-using System.Collections;
-using System.Collections.Generic;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class StePermutation : Dictionary<SteAttributeKey, object>
-    {
-        public override string ToString()
-        {
-            System.Text.StringBuilder b = new System.Text.StringBuilder();
-            bool needSeparator = false;
-            foreach (KeyValuePair<SteAttributeKey, object> pair in this)
-            {
-                if (!needSeparator)
-                {
-                    needSeparator = true;
-                }
-                else
-                {
-                    b.Append(", ");
-                }
-                b.Append(pair.Key.GetType().Name);
-                b.Append("=");
-                b.Append(pair.Value.ToString());
-            }
-
-            return b.ToString();
-        }
-    }
-
-    public abstract class StePermutationGenerator : IEnumerable<StePermutation>
-    {
-        // standard GetEnumerator, implemented in terms of specialized enumerator
-        public IEnumerator<StePermutation> GetEnumerator()
-        {
-            return this.GetEnumerator(this.DefaultKeys);
-        }
-
-        IEnumerator IEnumerable.GetEnumerator()
-        {
-            return this.GetEnumerator(this.DefaultKeys);
-        }
-
-        public abstract IEnumerable<SteAttributeKey> DefaultKeys
-        {
-            get;
-        }
-
-        // specialized GetEnumerator where attribute keys can be restricted to only those desired
-        public abstract IEnumerator<StePermutation> GetEnumerator(IEnumerable<SteAttributeKey> keysOfInterest);
-    }
-
-
-    // Simple generator of permutations based on cross product of lists of keyed attributes
-    //  (iterates through combinations of picking one of each attribute in the set)
-    public class SteSimplePermutationGenerator : StePermutationGenerator
-    {
-        // Internal enumerator
-        private class SteSimplePermEnumerator : IEnumerator<StePermutation>
-        {
-            private enum LogicalPosition
-            {
-                BeforeElements,          // Position is prior to first element and there is at least one element
-                OnElement,         // Position is on an element
-                AfterElements             // Position is after final element
-            }
-
-            private SteSimplePermutationGenerator _parent;            // Source of enumeration elements
-            private List<SteAttributeKey> _keysOfInterest;    // attribute keys to use to generate permutations
-            private IEnumerator[] _position;          // One enumerator for each non-empty attribute list in parent
-            private LogicalPosition _logicalPosition;   // Logical positioning of self
-
-            // NOTE: enumerators in _position always point to valid attributes, to make code for Current be simple.
-            //  This means _logicalPosition is required to distinguish times when the overall enumerator should appear
-            //  to be positioned either before or after the elements.
-
-            public SteSimplePermEnumerator(SteSimplePermutationGenerator parent, IEnumerable<SteAttributeKey> keysOfInterest)
-            {
-                _parent = parent;
-
-                // prune keys to ones that are available
-                _keysOfInterest = new List<SteAttributeKey>();
-                foreach (SteAttributeKey key in keysOfInterest)
-                {
-                    ArrayList list;
-                    if (_parent.AttributeLists.TryGetValue(key, out list) && list.Count > 0)
-                    {
-                        _keysOfInterest.Add(key);
-                    }
-                }
-                _position = new IEnumerator[_keysOfInterest.Count];
-                Reset();
-            }
-
-            // Move to next position
-            public bool MoveNext()
-            {
-                if (LogicalPosition.BeforeElements == _logicalPosition)
-                {
-                    // contained enumerator already pointing to first element, so
-                    //  we just need to update logical position
-                    _logicalPosition = LogicalPosition.OnElement;
-                }
-                else if (LogicalPosition.OnElement == _logicalPosition)
-                {
-                    // Move by advancing each attribute list in turn until one
-                    //  arrives at a new value.  As each hits the end of the
-                    //  list, restart it and move it to the first element.
-                    bool foundOne = false;
-                    foreach (IEnumerator attributeList in _position)
-                    {
-                        if (!attributeList.MoveNext())
-                        {
-                            attributeList.Reset();
-                            attributeList.MoveNext();  // Since we don't have empty lists, this should always succeed.
-                        }
-                        else
-                        {
-                            foundOne = true;
-                            break;
-                        }
-                    }
-
-                    if (!foundOne)
-                    {
-                        _logicalPosition = LogicalPosition.AfterElements;
-                    }
-                }
-                // else logical position is after all elements, so we leave it there and don't do anything
-
-                return LogicalPosition.AfterElements != _logicalPosition;
-            }
-
-            // Standard enumerator "Current" property
-            //  Returns null if not currently on an element
-            //  Otherwise, builds a permutation based on current element of each contained enumerator
-            public StePermutation Current
-            {
-                get
-                {
-                    StePermutation result = null;
-                    if (LogicalPosition.OnElement == _logicalPosition)
-                    {
-                        result = new StePermutation();
-                        for (int i = 0; i < _position.Length; i++)
-                        {
-                            result.Add(_keysOfInterest[i], _position[i].Current);
-                        }
-                    }
-
-                    return result;
-                }
-            }
-
-            object IEnumerator.Current
-            {
-                get
-                {
-                    return this.Current;
-                }
-            }
-
-            // Standard enumerator restart method
-            public void Reset()
-            {
-                for (int i = 0; i < _keysOfInterest.Count; i++)
-                {
-                    ArrayList list = _parent.AttributeLists[_keysOfInterest[i]];
-                    _position[i] = list.GetEnumerator();
-                    if (!_position[i].MoveNext())
-                    {
-                        throw new ApplicationException("Internal error: No empty lists allowed at this point!");
-                    }
-                }
-
-                if (0 < _position.Length)
-                {
-                    _logicalPosition = LogicalPosition.BeforeElements;
-                }
-                else
-                {
-                    _logicalPosition = LogicalPosition.AfterElements;
-                }
-            }
-
-            public void Dispose()
-            {
-                _logicalPosition = LogicalPosition.AfterElements;
-                _position = null;
-            }
-        }
-
-        // permutationGenerator private fields
-        private Dictionary<SteAttributeKey, ArrayList> _permutationBase;
-
-        // generator's ctor
-        public SteSimplePermutationGenerator()
-        {
-            _permutationBase = new Dictionary<SteAttributeKey, ArrayList>();
-        }
-
-        // Default key list for generator
-        public override IEnumerable<SteAttributeKey> DefaultKeys
-        {
-            get
-            {
-                return _permutationBase.Keys;
-            }
-        }
-
-        // Add a new attribute to the set
-        public void Add(SteAttributeKey key, object attribute)
-        {
-            ArrayList targetList;
-            if (!_permutationBase.TryGetValue(key, out targetList))
-            {
-                targetList = new ArrayList();
-                _permutationBase.Add(key, targetList);
-            }
-
-            targetList.Add(attribute);
-        }
-
-        // specialized GetEnumerator where attribute keys can be restricted to only those desired
-        public override IEnumerator<StePermutation> GetEnumerator(IEnumerable<SteAttributeKey> keysOfInterest)
-        {
-            return new SteSimplePermEnumerator(this, keysOfInterest);
-        }
-
-        // Access to internal dictionary, just in case it's useful
-        public Dictionary<SteAttributeKey, ArrayList> AttributeLists
-        {
-            get
-            {
-                return _permutationBase;
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteTypeBoundaries.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteTypeBoundaries.cs
deleted file mode 100644 (file)
index 4713d7c..0000000
+++ /dev/null
@@ -1,715 +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;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.SqlTypes;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public abstract class SteTypeBoundaries : StePermutationGenerator
-    {
-        // Use this marker for attribute value to indicate the attribute is not used
-        // (ex. option where Decimal parameter's Scale property should not be set at all)
-        public static object s_doNotUseMarker = new object();
-    }
-
-    // simple types can just wrap a simple permutation generator
-    public class SteSimpleTypeBoundaries : SteTypeBoundaries
-    {
-        private static readonly byte[] s_theBigByteArray = CreateByteArray(1000000);
-        private static readonly byte[] s_moderateSizeByteArray = CreateByteArray(8000);
-        private static readonly string s_moderateSizeString = CreateString(8000);
-        private static readonly char[] s_moderateSizeCharArray = s_moderateSizeString.ToCharArray();
-
-        // Class members
-        public static readonly IList<SteSimpleTypeBoundaries> s_allTypes;
-        public static readonly IList<SteSimpleTypeBoundaries> s_allTypesExceptUdts;
-        public static readonly IList<SteSimpleTypeBoundaries> s_udtsOnly;
-        static SteSimpleTypeBoundaries()
-        {
-            List<SteSimpleTypeBoundaries> list = new List<SteSimpleTypeBoundaries>();
-
-            // DevNote: Don't put null value attributes first -- it confuses DataTable generation for SteStructuredTypeBoundaries
-
-            // BigInt
-            SteSimplePermutationGenerator type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.BigInt);
-            type.Add(SteAttributeKey.Value, (long)0);
-            type.Add(SteAttributeKey.Value, long.MaxValue);
-            type.Add(SteAttributeKey.Value, long.MinValue);
-            type.Add(SteAttributeKey.Value, new SqlInt64(long.MaxValue));
-            type.Add(SteAttributeKey.Value, new SqlInt64(long.MinValue));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Binary types
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Binary);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.VarBinary);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Image);
-            type.Add(SteAttributeKey.MaxLength, 1);    // a small value
-            type.Add(SteAttributeKey.MaxLength, 40);   // Somewhere in the middle
-            type.Add(SteAttributeKey.MaxLength, 8000); // Couple values around maximum tds length
-            type.Add(SteAttributeKey.Value, CreateByteArray(0));
-            type.Add(SteAttributeKey.Value, CreateByteArray(1));
-            type.Add(SteAttributeKey.Value, CreateByteArray(50));
-            type.Add(SteAttributeKey.Value, s_moderateSizeByteArray);
-            type.Add(SteAttributeKey.Value, new SqlBytes(CreateByteArray(0)));
-            type.Add(SteAttributeKey.Value, new SqlBytes(CreateByteArray(1)));
-            type.Add(SteAttributeKey.Value, new SqlBytes(CreateByteArray(40)));
-            type.Add(SteAttributeKey.Value, new SqlBytes(s_moderateSizeByteArray));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            type.Add(SteAttributeKey.Offset, s_doNotUseMarker);
-            type.Add(SteAttributeKey.Offset, -1);
-            type.Add(SteAttributeKey.Offset, 0);
-            type.Add(SteAttributeKey.Offset, 10);
-            type.Add(SteAttributeKey.Offset, 8000);
-            type.Add(SteAttributeKey.Offset, int.MaxValue);
-            type.Add(SteAttributeKey.Length, 0);
-            type.Add(SteAttributeKey.Length, 40);
-            type.Add(SteAttributeKey.Length, 8000);
-            type.Add(SteAttributeKey.Length, 1000000);
-            type.Add(SteAttributeKey.Length, -1);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Byte
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.TinyInt);
-            type.Add(SteAttributeKey.Value, byte.MaxValue);
-            type.Add(SteAttributeKey.Value, byte.MinValue);
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Character (ANSI)
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Char);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Text);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.VarChar);
-            type.Add(SteAttributeKey.MaxLength, 1);
-            type.Add(SteAttributeKey.MaxLength, 30);
-            type.Add(SteAttributeKey.MaxLength, 8000);
-            type.Add(SteAttributeKey.Value, CreateString(1));
-            type.Add(SteAttributeKey.Value, CreateString(20));
-            type.Add(SteAttributeKey.Value, s_moderateSizeString);
-            type.Add(SteAttributeKey.Value, CreateString(1).ToCharArray());
-            type.Add(SteAttributeKey.Value, CreateString(25).ToCharArray());
-            type.Add(SteAttributeKey.Value, s_moderateSizeCharArray);
-            type.Add(SteAttributeKey.Value, new SqlChars(CreateString(1).ToCharArray()));
-            type.Add(SteAttributeKey.Value, new SqlChars(CreateString(30).ToCharArray()));
-            type.Add(SteAttributeKey.Value, new SqlChars(s_moderateSizeCharArray));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Character (UNICODE)
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.NChar);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.NText);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.NVarChar);
-            type.Add(SteAttributeKey.MaxLength, 1);
-            type.Add(SteAttributeKey.MaxLength, 35);
-            type.Add(SteAttributeKey.MaxLength, 4000);
-            type.Add(SteAttributeKey.Value, CreateString(1));
-            type.Add(SteAttributeKey.Value, CreateString(15));
-            type.Add(SteAttributeKey.Value, s_moderateSizeString);
-            type.Add(SteAttributeKey.Value, CreateString(1).ToCharArray());
-            type.Add(SteAttributeKey.Value, CreateString(20).ToCharArray());
-            type.Add(SteAttributeKey.Value, s_moderateSizeCharArray);
-            type.Add(SteAttributeKey.Value, new SqlChars(CreateString(1).ToCharArray()));
-            type.Add(SteAttributeKey.Value, new SqlChars(CreateString(25).ToCharArray()));
-            type.Add(SteAttributeKey.Value, new SqlChars(s_moderateSizeCharArray));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // DateTime
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.DateTime);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.SmallDateTime);
-            type.Add(SteAttributeKey.Value, new DateTime(1753, 1, 1));
-            type.Add(SteAttributeKey.Value, new SqlDateTime(new DateTime(1753, 1, 1)));  // min SqlDateTime
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Decimal
-            //  the TVP test isn't robust in the face of OverflowExceptions on input, so a number of these
-            //  values are commented out and other numbers substituted.
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Decimal);
-            type.Add(SteAttributeKey.Precision, (byte)38);
-            type.Add(SteAttributeKey.Scale, (byte)0);
-            type.Add(SteAttributeKey.Scale, (byte)10);
-            type.Add(SteAttributeKey.Value, (decimal)0);
-            type.Add(SteAttributeKey.Value, decimal.MaxValue / 10000000000);
-            type.Add(SteAttributeKey.Value, new SqlDecimal(0));
-            type.Add(SteAttributeKey.Value, ((SqlDecimal)1234567890123456.789012345678M) * 100); // Bigger than a Decimal
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Float
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Float);
-            type.Add(SteAttributeKey.Value, (double)0);
-            type.Add(SteAttributeKey.Value, double.MaxValue);
-            type.Add(SteAttributeKey.Value, double.MinValue);
-            type.Add(SteAttributeKey.Value, new SqlDouble(double.MaxValue));
-            type.Add(SteAttributeKey.Value, new SqlDouble(double.MinValue));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Int
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Int);
-            type.Add(SteAttributeKey.Value, (int)0);
-            type.Add(SteAttributeKey.Value, int.MaxValue);
-            type.Add(SteAttributeKey.Value, int.MinValue);
-            type.Add(SteAttributeKey.Value, new SqlInt32(int.MaxValue));
-            type.Add(SteAttributeKey.Value, new SqlInt32(int.MinValue));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Money types
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Money);
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.SmallMoney);
-            type.Add(SteAttributeKey.Value, (decimal)0);
-            type.Add(SteAttributeKey.Value, (decimal)unchecked(((long)0x8000000000000000L) / 10000));
-            type.Add(SteAttributeKey.Value, (decimal)0x7FFFFFFFFFFFFFFFL / 10000);
-            type.Add(SteAttributeKey.Value, new decimal(-214748.3648)); // smallmoney min
-            type.Add(SteAttributeKey.Value, new decimal(214748.3647)); // smallmoney max
-            type.Add(SteAttributeKey.Value, new SqlMoney(((decimal)int.MaxValue) / 10000));
-            type.Add(SteAttributeKey.Value, new SqlMoney(((decimal)int.MinValue) / 10000));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // Real
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.Real);
-            type.Add(SteAttributeKey.Value, (float)0);
-            type.Add(SteAttributeKey.Value, float.MaxValue);
-            type.Add(SteAttributeKey.Value, float.MinValue);
-            type.Add(SteAttributeKey.Value, new SqlSingle(float.MaxValue));
-            type.Add(SteAttributeKey.Value, new SqlSingle(float.MinValue));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // SmallInt
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.SmallInt);
-            type.Add(SteAttributeKey.Value, (short)0);
-            type.Add(SteAttributeKey.Value, short.MaxValue);
-            type.Add(SteAttributeKey.Value, short.MinValue);
-            type.Add(SteAttributeKey.Value, new SqlInt16(short.MaxValue));
-            type.Add(SteAttributeKey.Value, new SqlInt16(short.MinValue));
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // UniqueIdentifier
-            type = new SteSimplePermutationGenerator();
-            type.Add(SteAttributeKey.SqlDbType, SqlDbType.UniqueIdentifier);
-            type.Add(SteAttributeKey.Value, new Guid());
-            type.Add(SteAttributeKey.Value, null);
-            type.Add(SteAttributeKey.Value, DBNull.Value);
-            list.Add(new SteSimpleTypeBoundaries(type));
-
-            // UDT
-            // UDTs aren's supported in all table scenarios, so make a separate list
-            // that doesn't include them.
-            s_allTypesExceptUdts = new List<SteSimpleTypeBoundaries>(list).AsReadOnly();
-
-           //type = new SteSimplePermutationGenerator();
-           //type.Add(SteAttributeKey.SqlDbType, SqlDbType.Udt);
-           //type.Add(SteAttributeKey.TypeName, "dbo.WeakAddress");
-           //type.Add(SteAttributeKey.Type, typeof(WeakAddress));
-           //type.Add(SteAttributeKey.Value, new WeakAddress("", ""));
-           //type.Add(SteAttributeKey.Value, new WeakAddress(CreateString(22), ""));
-           //type.Add(SteAttributeKey.Value, new WeakAddress(ModerateSizeString, ""));
-           //type.Add(SteAttributeKey.Value, null);
-           //type.Add(SteAttributeKey.Value, DBNull.Value);
-           //
-           //SteSimpleTypeBoundaries udt = new SteSimpleTypeBoundaries(type);
-           //list.Add(udt);
-           //
-           //AllTypes = list.AsReadOnly();
-           //
-           //list = new List<SteSimpleTypeBoundaries>();
-           //list.Add(udt);
-           //UdtsOnly = list.AsReadOnly();
-        }
-
-        private SteSimplePermutationGenerator _generator;
-
-        public SteSimpleTypeBoundaries(SteSimplePermutationGenerator generator)
-        {
-            _generator = generator;
-        }
-
-        public override IEnumerable<SteAttributeKey> DefaultKeys
-        {
-            get
-            {
-                return _generator.DefaultKeys;
-            }
-        }
-
-        public override IEnumerator<StePermutation> GetEnumerator(IEnumerable<SteAttributeKey> keysOfInterest)
-        {
-            return _generator.GetEnumerator(keysOfInterest);
-        }
-
-        private const string __prefix = "Char: ";
-        public static string CreateString(int size)
-        {
-            System.Text.StringBuilder b = new System.Text.StringBuilder();
-            b.Append(__prefix);
-            for (int i = 0; i < s_theBigByteArray.Length && b.Length < size; i++)
-            {
-                b.Append(s_theBigByteArray[i]);
-            }
-
-            if (b.Length > size)
-            {
-                b.Remove(size, b.Length - size);
-            }
-
-            return b.ToString();
-        }
-
-        public static byte[] CreateByteArray(int size)
-        {
-            byte[] result = new byte[size];
-
-            //
-            // Leave a marker of three 0s, followed by the cycle count
-            int cycleCount = 0;
-            byte cycleStep = 0;
-            for (int i = 0; i < result.Length; i++)
-            {
-                if (cycleStep < 3)
-                {
-                    result[i] = 0;
-                }
-                else if (3 == cycleStep)
-                {
-                    result[i] = (byte)cycleCount;
-                }
-                else
-                {
-                    result[i] = cycleStep;
-                }
-                if (cycleStep == byte.MaxValue)
-                {
-                    cycleCount++;
-                    cycleStep = 0;
-                }
-                else
-                {
-                    cycleStep++;
-                }
-            }
-
-            return result;
-        }
-    }
-
-
-    // Structured type boundary value generator
-    public class SteStructuredTypeBoundaries : SteTypeBoundaries
-    {
-        private class SteStructuredTypeBoundariesEnumerator : IEnumerator<StePermutation>
-        {
-            private enum LogicalPosition
-            {
-                BeforeElements,          // Position is prior to first element and there is at least one element
-                OnElement,         // Position is on an element
-                AfterElements             // Position is after final element
-            }
-
-
-            // Value list can be static, since it'll only ever be used in one way.
-            private static IList<SteAttributeKey> __valueKey = new List<SteAttributeKey>(new SteAttributeKey[] { SteAttributeKey.Value });
-
-            private SteStructuredTypeBoundaries _parent;
-            private bool _isMultiValued;
-            private IList<SteAttributeKey> _metaDataKeysOfInterest; // metadata keys that should be used
-            private object[][] _separateValueList;  // use the value list separately?
-            private IList<IEnumerator<StePermutation>> _fieldEnumerators; // List of enumerators over subordinate types
-            private bool[] _completed;         // Which enumerators have already completed?
-            private LogicalPosition _logicalPosition;   // Logical positioning of self
-            private int _typeNumber;        // used to uniquely separate each type for this session
-            private string _typeNameBase;
-            private StePermutation _current;
-            private StePermutation _rowCountColumn;
-
-            public SteStructuredTypeBoundariesEnumerator(
-                            SteStructuredTypeBoundaries parent, IEnumerable<SteAttributeKey> keysOfInterest, bool isMultiValued)
-            {
-                _parent = parent;
-                _typeNameBase = "SteStructType" + Guid.NewGuid();
-                _isMultiValued = isMultiValued;
-                _current = null;
-
-                // Separate values from everything else, so we can generate a complete table per permutation based on said values.
-                bool usesValues = false;
-                _metaDataKeysOfInterest = new List<SteAttributeKey>();
-                foreach (SteAttributeKey key in keysOfInterest)
-                {
-                    if (SteAttributeKey.Value == key)
-                    {
-                        usesValues = true;
-                    }
-                    else
-                    {
-                        _metaDataKeysOfInterest.Add(key);
-                    }
-                }
-
-                if (usesValues)
-                {
-                    if (_isMultiValued)
-                    {
-                        CreateSeparateValueList();
-                    }
-                    else
-                    {
-                        _metaDataKeysOfInterest.Add(SteAttributeKey.Value);
-                    }
-                }
-
-                // set up rowcount column
-                _rowCountColumn = new StePermutation();
-                if (0 <= _metaDataKeysOfInterest.IndexOf(SteAttributeKey.SqlDbType))
-                {
-                    _rowCountColumn.Add(SteAttributeKey.SqlDbType, SqlDbType.Int);
-                }
-
-                Reset();
-            }
-
-            public StePermutation Current
-            {
-                get
-                {
-                    return _current;
-                }
-            }
-
-            object IEnumerator.Current
-            {
-                get
-                {
-                    return this.Current;
-                }
-            }
-
-            public void Dispose()
-            {
-                _logicalPosition = LogicalPosition.AfterElements;
-                _fieldEnumerators = null;
-            }
-
-            public bool UseSeparateValueList
-            {
-                get
-                {
-                    return null != _separateValueList;
-                }
-            }
-
-            public object[][] SeparateValues
-            {
-                get
-                {
-                    return _separateValueList;
-                }
-            }
-
-            public bool MoveNext()
-            {
-                bool result = false;
-                if (LogicalPosition.BeforeElements == _logicalPosition)
-                {
-                    _logicalPosition = LogicalPosition.OnElement;
-                    result = true;
-                }
-                else if (LogicalPosition.OnElement == _logicalPosition)
-                {
-                    for (int i = 0; i < _fieldEnumerators.Count; i++)
-                    {
-                        IEnumerator<StePermutation> field = _fieldEnumerators[i];
-                        if (!field.MoveNext())
-                        {
-                            field.Reset();
-                            field.MoveNext();
-                            _completed[i] = true;
-                        }
-                        else if (!_completed[i])
-                        {
-                            result = true;
-                            break;
-                        }
-                    }
-                }
-
-                if (result)
-                {
-                    if (LogicalPosition.OnElement == _logicalPosition)
-                    {
-                        List<StePermutation> fields = new List<StePermutation>();
-                        foreach (IEnumerator<StePermutation> field in _fieldEnumerators)
-                        {
-                            fields.Add(field.Current);
-                        }
-                        fields.Add(_rowCountColumn);
-
-                        _current = CreateTopLevelPermutation(fields);
-                    }
-                }
-
-
-                return result;
-            }
-
-            public void Reset()
-            {
-                _fieldEnumerators = new List<IEnumerator<StePermutation>>();
-                foreach (SteSimpleTypeBoundaries columnBounds in _parent.ColumnTypes)
-                {
-                    IEnumerator<StePermutation> fieldPermutations = columnBounds.GetEnumerator(_metaDataKeysOfInterest);
-
-                    // Ignore empty lists
-                    if (fieldPermutations.MoveNext())
-                    {
-                        _fieldEnumerators.Add(fieldPermutations);
-                    }
-                }
-
-                if (0 < _fieldEnumerators.Count)
-                {
-                    _logicalPosition = LogicalPosition.BeforeElements;
-                    _completed = new bool[_fieldEnumerators.Count];
-                }
-                else
-                {
-                    _logicalPosition = LogicalPosition.AfterElements;
-                }
-            }
-
-            private void CreateSeparateValueList()
-            {
-                int childColumnCount = _parent.ColumnTypes.Count;
-                int columnCount = childColumnCount + 1;
-                IEnumerator<StePermutation>[] valueSources = new IEnumerator<StePermutation>[childColumnCount];
-                ArrayList[] valueList = new ArrayList[childColumnCount];
-                int i = 0;
-                foreach (SteSimpleTypeBoundaries field in _parent.ColumnTypes)
-                {
-                    valueSources[i] = field.GetEnumerator(__valueKey);
-                    valueList[i] = new ArrayList();
-                    i++;
-                }
-
-                // Loop over the permutation enumerators until they all complete at least once
-                //  Restart enumerators that complete before the others do
-                int completedColumns = 0;
-
-                // Array to track columns that have already completed once
-                bool[] isColumnComplete = new bool[childColumnCount];
-                for (i = 0; i < childColumnCount; i++)
-                {
-                    isColumnComplete[i] = false;
-                }
-
-                // The main value-accumulation loop
-                while (completedColumns < childColumnCount)
-                {
-                    for (i = 0; i < childColumnCount; i++)
-                    {
-                        if (!valueSources[i].MoveNext())
-                        {
-                            // update column completion, if it's the first time for this column
-                            if (!isColumnComplete[i])
-                            {
-                                completedColumns++;
-                                isColumnComplete[i] = true;
-                            }
-
-                            // restart column, and make sure there's at least one value
-                            valueSources[i].Reset();
-                            if (!valueSources[i].MoveNext())
-                            {
-                                throw new InvalidOperationException("Separate value list, but no values for column " + i);
-                            }
-                        }
-                        valueList[i].Add(valueSources[i].Current[SteAttributeKey.Value]);
-                    }
-                }
-
-                // pivot values into final list
-                int rowCount = valueList[0].Count;
-                object[][] separateValues = new object[rowCount][];
-                for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
-                {
-                    separateValues[rowIndex] = new object[columnCount];
-                    for (int columnIndex = 0; columnIndex < childColumnCount; columnIndex++)
-                    {
-                        separateValues[rowIndex][columnIndex] = valueList[columnIndex][rowIndex];
-                    }
-                    separateValues[rowIndex][childColumnCount] = rowIndex;
-                }
-                _separateValueList = separateValues;
-
-            }
-
-            private StePermutation CreateTopLevelPermutation(IList<StePermutation> fields)
-            {
-                StePermutation perm = new StePermutation();
-                if (0 <= _metaDataKeysOfInterest.IndexOf(SteAttributeKey.SqlDbType))
-                {
-                    perm.Add(SteAttributeKey.SqlDbType, SqlDbType.Structured);
-                }
-
-                if (0 <= _metaDataKeysOfInterest.IndexOf(SteAttributeKey.MultiValued))
-                {
-                    perm.Add(SteAttributeKey.MultiValued, _isMultiValued);
-                }
-
-                if (0 <= _metaDataKeysOfInterest.IndexOf(SteAttributeKey.MaxLength))
-                {
-                    perm.Add(SteAttributeKey.MaxLength, -1);
-                }
-
-                if (0 <= _metaDataKeysOfInterest.IndexOf(SteAttributeKey.TypeName))
-                {
-                    perm.Add(SteAttributeKey.TypeName, _typeNameBase + _typeNumber);
-                    _typeNumber++;
-                }
-
-                if (0 <= _metaDataKeysOfInterest.IndexOf(SteAttributeKey.Fields))
-                {
-                    perm.Add(SteAttributeKey.Fields, fields);
-                }
-
-                if (0 <= _metaDataKeysOfInterest.IndexOf(SteAttributeKey.Value))
-                {
-                    if (!UseSeparateValueList)
-                    {
-                        throw new NotSupportedException("Integrated values not yet supported by test framework.");
-                    }
-
-                    perm.Add(SteAttributeKey.Value, _separateValueList);
-                }
-
-                return perm;
-            }
-        }
-
-        // class members
-        public static readonly IList<SteStructuredTypeBoundaries> AllTypes;
-        public static readonly SteStructuredTypeBoundaries AllColumnTypes;
-        public static readonly SteStructuredTypeBoundaries AllColumnTypesExceptUdts;
-        public static readonly SteStructuredTypeBoundaries UdtsOnly;
-        static SteStructuredTypeBoundaries()
-        {
-            AllColumnTypesExceptUdts = new SteStructuredTypeBoundaries(SteSimpleTypeBoundaries.s_allTypesExceptUdts, true);
-            AllColumnTypes = new SteStructuredTypeBoundaries(SteSimpleTypeBoundaries.s_allTypes, true);
-            UdtsOnly = new SteStructuredTypeBoundaries(SteSimpleTypeBoundaries.s_udtsOnly, true);
-
-            AllTypes = new List<SteStructuredTypeBoundaries>();
-            AllTypes.Add(AllColumnTypes);
-            AllTypes.Add(AllColumnTypesExceptUdts);
-            AllTypes.Add(UdtsOnly);
-        }
-
-        // instance fields
-        private IList<SteSimpleTypeBoundaries> _columnTypes;
-        private bool _isMultiValued;
-
-        // ctor
-        public SteStructuredTypeBoundaries(IList<SteSimpleTypeBoundaries> columnTypes, bool isMultiValued)
-        {
-            _columnTypes = columnTypes;
-            _isMultiValued = true;
-        }
-
-        private IList<SteSimpleTypeBoundaries> ColumnTypes
-        {
-            get
-            {
-                return _columnTypes;
-            }
-        }
-
-        public override IEnumerable<SteAttributeKey> DefaultKeys
-        {
-            get
-            {
-                List<SteAttributeKey> result = new List<SteAttributeKey>();
-                foreach (SteSimpleTypeBoundaries column in _columnTypes)
-                {
-                    foreach (SteAttributeKey columnKey in column.DefaultKeys)
-                    {
-                        if (0 > result.IndexOf(columnKey))
-                        {
-                            result.Add(columnKey);
-                        }
-                    }
-                }
-
-                if (0 > result.IndexOf(SteAttributeKey.SqlDbType))
-                {
-                    result.Add(SteAttributeKey.SqlDbType);
-                }
-                if (0 > result.IndexOf(SteAttributeKey.Value))
-                {
-                    result.Add(SteAttributeKey.Value);
-                }
-                if (0 > result.IndexOf(SteAttributeKey.MaxLength))
-                {
-                    result.Add(SteAttributeKey.MaxLength);
-                }
-                if (0 > result.IndexOf(SteAttributeKey.TypeName))
-                {
-                    result.Add(SteAttributeKey.TypeName);
-                }
-                if (0 > result.IndexOf(SteAttributeKey.Fields))
-                {
-                    result.Add(SteAttributeKey.Fields);
-                }
-                return result;
-            }
-        }
-
-        public override IEnumerator<StePermutation> GetEnumerator(IEnumerable<SteAttributeKey> keysOfInterest)
-        {
-            return new SteStructuredTypeBoundariesEnumerator(this, keysOfInterest, _isMultiValued);
-        }
-
-        public static object[][] GetSeparateValues(IEnumerator<StePermutation> enumerator)
-        {
-            SteStructuredTypeBoundariesEnumerator myEnum = enumerator as SteStructuredTypeBoundariesEnumerator;
-            if (null != myEnum)
-            {
-                return myEnum.SeparateValues;
-            }
-            else
-            {
-                return null;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/StreamInputParam.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/StreamInputParam.cs
deleted file mode 100644 (file)
index f5d389b..0000000
+++ /dev/null
@@ -1,771 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Text;
-using System.Data;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class StreamInputParam
-    {
-        private static Random s_rand = new Random(9999);
-        private static string s_connStr = null;
-        private static bool s_useSP = false;
-
-        internal class CustomStreamException : Exception
-        {
-        }
-
-        internal class CustomStream : Stream
-        {
-            byte[] _data;
-            bool _sync;
-            int _pos = 0;
-            int _errorPos = 0;
-
-            Random r = new Random(8888);
-
-            public CustomStream(byte[] data, bool sync, int errorPos)
-            {
-                _data = data;
-                _sync = sync;
-                _errorPos = errorPos;
-            }
-
-            public override bool CanRead
-            {
-                get { return true; }
-            }
-
-            public override bool CanSeek
-            {
-                get { return false; }
-            }
-
-            public override bool CanWrite
-            {
-                get { return false; }
-            }
-
-            public override void Flush()
-            {
-                throw new NotImplementedException();
-            }
-
-            public override long Length
-            {
-                get { throw new NotImplementedException(); }
-            }
-
-            public override long Position
-            {
-                get
-                {
-                    throw new NotImplementedException();
-                }
-                set
-                {
-                    throw new NotImplementedException();
-                }
-            }
-
-            private int ReadInternal(byte[] buffer, int offset, int count)
-            {
-                Debug.Assert(count > 0, "Count <= 0 ");
-                if (_pos == _data.Length)
-                {
-                    return 0;
-                }
-                int nRead;
-                if (_data.Length == _pos - 1)
-                {
-                    nRead = 1;
-                }
-                else
-                {
-                    nRead = 1 + r.Next(Math.Min(count, _data.Length - _pos) - 1);
-                }
-                if (_errorPos >= _pos && _errorPos < _pos + nRead)
-                    throw new CustomStreamException();
-                Array.Copy(_data, _pos, buffer, offset, nRead);
-                _pos += nRead;
-                return nRead;
-            }
-
-            public override int Read(byte[] buffer, int offset, int count)
-            {
-                Debug.Assert(_sync, "Custom stream reader: Sync read in non-sync mode");
-                return ReadInternal(buffer, offset, count);
-            }
-
-            public override Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken)
-            {
-                Debug.Assert(!_sync, "Custom stream reader: Async read in sync mode");
-                TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
-                tcs.SetResult(ReadInternal(buffer, offset, count));
-                return tcs.Task;
-            }
-
-            public override long Seek(long offset, SeekOrigin origin)
-            {
-                throw new NotImplementedException();
-            }
-
-            public override void SetLength(long value)
-            {
-                throw new NotImplementedException();
-            }
-
-            public override void Write(byte[] buffer, int offset, int count)
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        private static void AssertEqual(byte[] ret, byte[] val, int len)
-        {
-            if (len > 0)
-                len = Math.Min(len, val.Length);
-            else
-                len = val.Length;
-            Debug.Assert(ret != null && ret.Length == len, "Length not equal");
-            for (int i = 0; i < len; i++)
-                Debug.Assert(val[i] == ret[i], "Data not equal");
-        }
-
-        private static void TestStream(int dataLen, bool sync, bool oldTypes, int paramLen, bool addWithValue = false)
-        {
-            byte[] val = new byte[dataLen];
-            s_rand.NextBytes(val);
-            TestStreamHelper(val, new MemoryStream(val, false), sync, oldTypes, paramLen, false, addWithValue);
-            Console.WriteLine("TestStream (Sync {0} DataLen {1} ParamLen {2} OLD {3} AVW {4}) is OK", sync, dataLen, paramLen, oldTypes, addWithValue);
-        }
-
-        private static void TestCustomStream(int dataLen, bool sync, bool oldTypes, int paramLen, bool error, bool addWithValue = false)
-        {
-            byte[] val = new byte[dataLen];
-            s_rand.NextBytes(val);
-            TestStreamHelper(val, new CustomStream(val, sync || oldTypes, error ? dataLen / 2 : -1), sync, oldTypes, paramLen, error, addWithValue);
-            Console.WriteLine("TestCustomStream (Sync {0} DataLen {1} ParamLen {2} Error {3} OLD {4} AVW {5}) is OK", sync, dataLen, paramLen, error, oldTypes, addWithValue);
-        }
-
-        private static void TestStreamHelper(byte[] val, object stream, bool sync, bool oldTypes, int paramLen, bool expectException, bool addWithValue)
-        {
-            using (SqlConnection conn = new SqlConnection(s_connStr))
-            {
-                conn.Open();
-                (new SqlCommand("create table #blobs (id INT, blob VARBINARY(MAX))", conn)).ExecuteNonQuery();
-                try
-                {
-                    SqlCommand ins;
-                    if (!s_useSP)
-                    {
-                        ins = new SqlCommand("insert into #blobs (id,blob) values (1,@blob)", conn);
-                    }
-                    else
-                    {
-                        new SqlCommand("create procedure #myProc (@blob varbinary(MAX)) as begin insert into #blobs values (1, @blob) end", conn).ExecuteNonQuery();
-                        ins = new SqlCommand("#myProc", conn);
-                        ins.CommandType = CommandType.StoredProcedure;
-                    }
-                    if (addWithValue)
-                    {
-                        ins.Parameters.AddWithValue("@blob", stream);
-                    }
-                    else
-                    {
-                        ins.Parameters.Add("@blob", oldTypes ? SqlDbType.Image : SqlDbType.VarBinary, paramLen);
-                        ins.Parameters["@blob"].Direction = ParameterDirection.Input;
-                        ins.Parameters["@blob"].Value = stream;
-                    }
-                    bool exc = false;
-                    if (sync)
-                    {
-                        try
-                        {
-                            ins.ExecuteNonQuery();
-                        }
-                        catch (CustomStreamException)
-                        {
-                            exc = true;
-                        }
-                    }
-                    else
-                    {
-                        try
-                        {
-                            ins.ExecuteNonQueryAsync().Wait();
-                        }
-                        catch (AggregateException ae)
-                        {
-                            if (ae.InnerException is CustomStreamException)
-                            {
-                                exc = true;
-                            }
-                            else
-                            {
-                                throw;
-                            }
-                        }
-                    }
-                    Debug.Assert(exc == expectException, "Exception!=Expectation");
-
-                    byte[] back = (new SqlCommand("select blob from #blobs where id=1", conn)).ExecuteScalar() as byte[];
-                    if (!expectException)
-                    {
-                        AssertEqual(back, val, paramLen);
-                    }
-                }
-                finally
-                {
-                    (new SqlCommand("drop table #blobs", conn)).ExecuteNonQuery();
-                    if (s_useSP)
-                    {
-                        (new SqlCommand("drop procedure #myProc", conn)).ExecuteNonQuery();
-                    }
-                }
-            }
-        }
-
-        private static string _xmlstr = null;
-
-        private static string XmlStr
-        {
-            get
-            {
-                if (_xmlstr == null)
-                {
-                    int N = 10000;
-                    XmlDocument doc = new XmlDocument();
-                    XmlNode root = doc.AppendChild(doc.CreateElement("root"));
-                    for (int i = 0; i < N; i++)
-                        root.AppendChild(doc.CreateElement("e" + i.ToString()));
-                    _xmlstr = doc.OuterXml;
-                }
-                return _xmlstr;
-            }
-        }
-
-        private static void TestXml2Text(bool sync, bool oldTypes, int paramLen, bool nvarchar)
-        {
-            TestTextWrite(XmlStr, XmlReader.Create(new StringReader(XmlStr)), sync, oldTypes, paramLen, nvarchar, false, false);
-            Console.WriteLine("TestXml2Text (Sync {0} ParamLen {1} NVARCHAR {2} OLD {3}) is OK", sync, paramLen, nvarchar, oldTypes);
-        }
-
-        private static void TestTextReader(int dataLen, bool sync, bool oldTypes, int paramLen, bool nvarchar, bool addWithValue = false)
-        {
-            StringBuilder sb = new StringBuilder();
-            for (int i = 0; i < dataLen; i++)
-                sb.Append((char)('A' + s_rand.Next(20)));
-            string s = sb.ToString();
-            TestTextWrite(s, new StringReader(s), sync, oldTypes, paramLen, nvarchar, false, addWithValue);
-            Console.WriteLine("TestTextReader (Sync {0} DataLen {1} ParamLen {2} NVARCHAR {3} OLD {4} AVW {5}) is OK", sync, dataLen, paramLen, nvarchar, oldTypes, addWithValue);
-        }
-
-        private static void TestCustomTextReader(int dataLen, bool sync, bool oldTypes, int paramLen, bool nvarchar, bool error, bool addWithValue = false)
-        {
-            StringBuilder sb = new StringBuilder();
-            for (int i = 0; i < dataLen; i++)
-                sb.Append((char)('A' + s_rand.Next(20)));
-            string s = sb.ToString();
-            TestTextWrite(s, new StreamReader(
-                                    new CustomStream(Encoding.Unicode.GetBytes(s), sync || oldTypes, error ? dataLen : -1),
-                                    Encoding.Unicode),
-                                    sync, oldTypes, paramLen, nvarchar, error, addWithValue);
-            Console.WriteLine("TestCustomTextReader (Sync {0} DataLen {1} ParamLen {2} NVARCHAR {3} Error {4} OLD {5} AVW {6}) is OK", sync, dataLen, paramLen, nvarchar, error, oldTypes, addWithValue);
-        }
-
-        private static void TestTextWrite(string s, object reader, bool sync, bool oldTypes, int paramLen, bool nvarchar, bool expectException, bool addWithValue)
-        {
-            using (SqlConnection conn = new SqlConnection(s_connStr))
-            {
-                conn.Open();
-
-                (new SqlCommand(string.Format("create table #blobs (id INT, blob {0}(MAX))", nvarchar ? "NVARCHAR" : "VARCHAR"), conn)).ExecuteNonQuery();
-                try
-                {
-                    SqlCommand ins;
-                    if (!s_useSP)
-                    {
-                        ins = new SqlCommand("insert into #blobs (id,blob) values (1,@blob)", conn);
-                    }
-                    else
-                    {
-                        new SqlCommand(
-                            string.Format("create procedure #myProc (@blob {0}(MAX)) as begin insert into #blobs values (1, @blob) end", nvarchar ? "NVARCHAR" : "VARCHAR"),
-                            conn).ExecuteNonQuery();
-                        ins = new SqlCommand("#myProc", conn);
-                        ins.CommandType = CommandType.StoredProcedure;
-                    }
-                    if (addWithValue)
-                    {
-                        ins.Parameters.AddWithValue("@blob", reader);
-                    }
-                    else
-                    {
-                        ins.Parameters.Add("@blob", nvarchar ?
-                                                       (oldTypes ? SqlDbType.NText : SqlDbType.NVarChar) :
-                                                       (oldTypes ? SqlDbType.Text : SqlDbType.VarChar), paramLen);
-                        ins.Parameters["@blob"].Direction = ParameterDirection.Input;
-                        ins.Parameters["@blob"].Value = reader;
-                    }
-
-                    bool exc = false;
-                    if (sync)
-                    {
-                        try
-                        {
-                            ins.ExecuteNonQuery();
-                        }
-                        catch (CustomStreamException)
-                        {
-                            exc = true;
-                        }
-                    }
-                    else
-                    {
-                        try
-                        {
-                            ins.ExecuteNonQueryAsync().Wait();
-                        }
-                        catch (AggregateException ae)
-                        {
-                            if (ae.InnerException is CustomStreamException)
-                            {
-                                exc = true;
-                            }
-                            else
-                            {
-                                throw;
-                            }
-                        }
-                    }
-                    Debug.Assert(exc == expectException, "Exception!=Expectation");
-
-                    string back = (new SqlCommand("select blob from #blobs where id=1", conn)).ExecuteScalar() as string;
-                    if (paramLen > 0)
-                    {
-                        s = s.Substring(0, Math.Min(paramLen, s.Length));
-                    }
-                    if (!expectException)
-                    {
-                        Debug.Assert(back == s, "Strings are not equal");
-                    }
-                }
-                finally
-                {
-                    (new SqlCommand("drop table #blobs", conn)).ExecuteNonQuery();
-                    if (s_useSP)
-                    {
-                        (new SqlCommand("drop procedure #myProc", conn)).ExecuteNonQuery();
-                    }
-                }
-            }
-        }
-
-        private static void TestXML(bool sync, bool lengthLimited, bool addWithValue = false)
-        {
-
-            using (SqlConnection conn = new SqlConnection(s_connStr))
-            {
-                conn.Open();
-
-                (new SqlCommand("create table #blobs (id INT, blob XML)", conn)).ExecuteNonQuery();
-                try
-                {
-                    SqlCommand ins;
-                    if (!s_useSP)
-                    {
-                        ins = new SqlCommand("insert into #blobs (id,blob) values (1,@blob)", conn);
-                    }
-                    else
-                    {
-                        new SqlCommand("create procedure #myProc (@blob XML) as begin insert into #blobs values (1, @blob) end", conn).ExecuteNonQuery();
-                        ins = new SqlCommand("#myProc", conn);
-                        ins.CommandType = CommandType.StoredProcedure;
-                    }
-
-                    StringBuilder comment = new StringBuilder();
-                    if (lengthLimited)
-                    {
-                        comment.Append("<!-- ");
-                        int N = s_rand.Next(100);
-                        for (int i = 0; i < N; i++)
-                            comment.Append(i.ToString());
-                        comment.Append("-->");
-                    }
-                    XmlReader reader = XmlReader.Create(new StringReader(XmlStr + comment.ToString()));
-
-                    if (addWithValue)
-                    {
-                        ins.Parameters.AddWithValue("@blob", reader);
-                    }
-                    else
-                    {
-                        ins.Parameters.Add("@blob", SqlDbType.Xml, lengthLimited ? XmlStr.Length : -1);
-                        ins.Parameters["@blob"].Direction = ParameterDirection.Input;
-                        ins.Parameters["@blob"].Value = reader;
-                    }
-                    if (sync)
-                    {
-                        ins.ExecuteNonQuery();
-                    }
-                    else
-                    {
-                        ins.ExecuteNonQueryAsync().Wait();
-                    }
-                    string back = (new SqlCommand("select blob from #blobs where id=1", conn)).ExecuteScalar() as string;
-                    Debug.Assert(back == XmlStr, "String!=xml");
-                    if (back != XmlStr)
-                    {
-                        Console.WriteLine("[{0}]", back);
-                        Console.WriteLine("[{0}]", XmlStr);
-                    }
-                }
-                finally
-                {
-                    (new SqlCommand("drop table #blobs", conn)).ExecuteNonQuery();
-                    if (s_useSP)
-                    {
-                        (new SqlCommand("drop procedure #myProc", conn)).ExecuteNonQuery();
-                    }
-                }
-                Console.WriteLine("TestXml (Sync {0} LimitLength {1} ) is OK", sync, lengthLimited);
-            }
-        }
-
-        private static void ImmediateCancelBin()
-        {
-            Console.WriteLine("Test immediate cancel for binary stream");
-            CancellationTokenSource cts = new CancellationTokenSource();
-            using (SqlConnection conn = new SqlConnection(s_connStr))
-            {
-                conn.OpenAsync().Wait();
-                using (SqlCommand cmd = conn.CreateCommand())
-                {
-                    cmd.CommandText = "create table #blobs (Id int, blob varbinary(max))";
-                    cmd.ExecuteNonQuery();
-                    Random rand = new Random(10000);
-                    int dataSize = 10000000;
-                    byte[] data = new byte[dataSize];
-                    rand.NextBytes(data);
-                    MemoryStream ms = new MemoryStream(data, false);
-                    cmd.CommandText = "insert into #blobs (Id, blob) values (1, @blob)";
-                    cmd.Parameters.Add("@blob", SqlDbType.VarBinary, dataSize);
-                    cmd.Parameters["@blob"].Direction = ParameterDirection.Input;
-                    cmd.Parameters["@blob"].Value = ms;
-                    Task t = cmd.ExecuteNonQueryAsync(cts.Token);
-                    if (!t.IsCompleted)
-                        cts.Cancel();
-                    try
-                    {
-                        t.Wait();
-                        Console.WriteLine("FAIL: Expected AggregateException on Task wait for Cancelled Task!");
-                        Console.WriteLine("t.Status: " + t.Status);
-                    }
-                    catch (AggregateException ae)
-                    {
-                        if (ae.InnerException is InvalidOperationException)
-                        {
-                            Console.WriteLine("PASS: Task is cancelled");
-                        }
-                        else
-                        {
-                            throw ae.InnerException;
-                        }
-                    }
-                    finally
-                    {
-                        ms.Close();
-                    }
-                }
-            }
-        }
-
-        private static void ImmediateCancelText()
-        {
-            Console.WriteLine("Test immediate cancel for text stream");
-            CancellationTokenSource cts = new CancellationTokenSource();
-            using (SqlConnection conn = new SqlConnection(s_connStr))
-            {
-                conn.OpenAsync().Wait();
-                using (SqlCommand cmd = conn.CreateCommand())
-                {
-                    cmd.CommandText = "create table #blobs (Id int, blob varchar(max))";
-                    cmd.ExecuteNonQuery();
-                    StringBuilder sb = new StringBuilder();
-                    for (int i = 0; i < 1000000; i++)
-                        sb.Append(i);
-                    cmd.CommandText = "insert into #blobs (Id, blob) values (1, @blob)";
-                    cmd.Parameters.Add("@blob", SqlDbType.VarChar, -1);
-                    cmd.Parameters["@blob"].Direction = ParameterDirection.Input;
-                    cmd.Parameters["@blob"].Value = new StringReader(sb.ToString());
-                    Task t = cmd.ExecuteNonQueryAsync(cts.Token);
-                    if (!t.IsCompleted)
-                        cts.Cancel();
-                    try
-                    {
-                        t.Wait();
-                        Console.WriteLine("FAIL: Expected AggregateException on Task wait for Cancelled Task!");
-                        Console.WriteLine("t.Status: " + t.Status);
-                    }
-                    catch (AggregateException ae)
-                    {
-                        if (ae.InnerException is InvalidOperationException)
-                        {
-                            Console.WriteLine("PASS: Task is cancelled");
-                        }
-                        else
-                        {
-                            throw ae.InnerException;
-                        }
-                    }
-                }
-            }
-        }
-
-        private static void ImmediateCancelXml()
-        {
-            Console.WriteLine("Test immediate cancel for xml stream");
-            CancellationTokenSource cts = new CancellationTokenSource();
-            using (SqlConnection conn = new SqlConnection(s_connStr))
-            {
-                conn.OpenAsync().Wait();
-                using (SqlCommand cmd = conn.CreateCommand())
-                {
-                    cmd.CommandText = "create table #blobs (Id int, blob xml)";
-                    cmd.ExecuteNonQuery();
-                    cmd.CommandText = "insert into #blobs (Id, blob) values (1, @blob)";
-                    cmd.Parameters.Add("@blob", SqlDbType.Xml, -1);
-                    cmd.Parameters["@blob"].Direction = ParameterDirection.Input;
-                    cmd.Parameters["@blob"].Value = XmlReader.Create(new StringReader(XmlStr));
-                    Task t = cmd.ExecuteNonQueryAsync(cts.Token);
-                    if (!t.IsCompleted)
-                        cts.Cancel();
-                    try
-                    {
-                        t.Wait();
-                        Console.WriteLine("FAIL: Expected AggregateException on Task wait for Cancelled Task!");
-                        Console.WriteLine("t.Status: " + t.Status);
-                    }
-                    catch (AggregateException ae)
-                    {
-                        if (ae.InnerException is InvalidOperationException)
-                        {
-                            Console.WriteLine("PASS: Task is cancelled");
-                        }
-                        else
-                        {
-                            throw ae.InnerException;
-                        }
-                    }
-                }
-            }
-        }
-
-        private static void PrepareCommand()
-        {
-            Console.Write("Test command preparation ");
-            using (SqlConnection conn = new SqlConnection(s_connStr))
-            {
-                conn.Open();
-                using (SqlCommand cmd = conn.CreateCommand())
-                {
-                    cmd.CommandText = "create table #blobs (Id int, blob varbinary(max))";
-                    cmd.ExecuteNonQuery();
-                    Random rand = new Random(10000);
-                    int dataSize = 100000;
-                    byte[] data = new byte[dataSize];
-                    rand.NextBytes(data);
-                    MemoryStream ms = new MemoryStream(data, false);
-
-                    cmd.CommandText = "insert into #blobs (Id, blob) values (1, @blob)";
-
-                    cmd.Parameters.Add("@blob", SqlDbType.VarBinary, dataSize);
-                    cmd.Parameters["@blob"].Direction = ParameterDirection.Input;
-                    cmd.Parameters["@blob"].Value = ms;
-                    cmd.Prepare();
-                    cmd.ExecuteNonQuery();
-                    conn.Close();
-                    ms.Close();
-                }
-            }
-            Console.WriteLine("PASS");
-        }
-
-        private static void CommandReuse()
-        {
-            foreach (var func in new Func<SqlCommand, CancellationToken, Task>[] {
-                    (cmd,token) => cmd.ExecuteNonQueryAsync(token),
-                    (cmd,token) => cmd.ExecuteReaderAsync(token),
-                    (cmd,token) => cmd.ExecuteXmlReaderAsync(token)
-            })
-            {
-                CancellationTokenSource cts = new CancellationTokenSource();
-                using (SqlConnection conn = new SqlConnection(s_connStr))
-                {
-                    conn.OpenAsync().Wait();
-                    Console.WriteLine("Test reuse of command after cancel");
-                    using (SqlCommand cmd = conn.CreateCommand())
-                    {
-                        cmd.CommandText = "create table #blobs (Id int, blob varbinary(max))";
-                        cmd.ExecuteNonQuery();
-                        Random rand = new Random(10000);
-                        int dataSize = 100000;
-                        byte[] binarydata = new byte[dataSize];
-                        rand.NextBytes(binarydata);
-                        MemoryStream ms = new MemoryStream(binarydata, false);
-                        cmd.CommandText = "insert into #blobs (Id, blob) values (1, @blob)";
-
-                        cmd.Parameters.Add("@blob", SqlDbType.VarBinary, dataSize);
-                        cmd.Parameters["@blob"].Direction = ParameterDirection.Input;
-                        cmd.Parameters["@blob"].Value = ms;
-
-                        Task t = func(cmd, cts.Token);
-                        if (!t.IsCompleted)
-                        {
-                            cts.Cancel();
-                        }
-
-                        try
-                        {
-                            t.Wait();
-                            throw new Exception("Expected AggregateException on Task wait for Cancelled Task!");
-                        }
-                        catch (AggregateException ae)
-                        {
-                            if (!ae.InnerException.Message.Contains("Operation cancelled by user."))
-                            {
-                                Console.WriteLine("Unexpected exception message: " + ae.InnerException.Message);
-                            }
-                        }
-                        finally
-                        {
-                            ms.Close();
-                        }
-                        cmd.Parameters.Clear();
-                        cmd.CommandText = "select 'PASS'";
-                        Console.WriteLine(cmd.ExecuteScalar());
-                    }
-                }
-            }
-        }
-
-        internal static void Run(string connection)
-        {
-            s_connStr = connection;
-            s_useSP = false;
-            Console.WriteLine("Starting Test using AsyncDebugScope");
-#if DEBUG
-            do
-            {
-                Console.WriteLine("Using stored procedure {0}", s_useSP);
-                bool oldTypes = false;
-                do
-                {
-                    using (AsyncDebugScope debugScope = new AsyncDebugScope())
-                    {
-                        for (int run = 0; run < 2; run++)
-                        {
-                            bool sync = (run == 0);
-                            if (run == 2)
-                            {
-                                debugScope.ForceAsyncWriteDelay = 1;
-                            }
-
-                            TestStream(100000, sync, oldTypes, -1);
-
-                            TestStream(10000, sync, oldTypes, 9000);
-                            TestStream(10000, sync, oldTypes, 1000);
-                            TestStream(500, sync, oldTypes, 9000);
-                            TestStream(500, sync, oldTypes, 1000);
-                            TestStream(0, sync, oldTypes, -1);
-                            TestStream(0, sync, oldTypes, 9000);
-                            TestStream(0, sync, oldTypes, 1000);
-                            TestStream(10000, sync, oldTypes, 0);
-
-                            TestCustomStream(10000, sync, oldTypes, -1, error: false);
-                            TestCustomStream(10000, sync, oldTypes, 9000, error: false);
-                            TestCustomStream(10000, sync, oldTypes, 1000, error: false);
-                            TestCustomStream(10000, sync, oldTypes, 0, error: false);
-                            TestCustomStream(10000, sync, oldTypes, -1, error: true);
-
-                            bool nvarchar = false;
-                            do
-                            {
-
-                                TestTextReader(100000, sync, oldTypes, -1, nvarchar);
-
-                                TestTextReader(10000, sync, oldTypes, 9000, nvarchar);
-                                TestTextReader(10000, sync, oldTypes, 1000, nvarchar);
-                                TestTextReader(500, sync, oldTypes, 9000, nvarchar);
-                                TestTextReader(500, sync, oldTypes, 1000, nvarchar);
-                                TestTextReader(0, sync, oldTypes, -1, nvarchar);
-                                TestTextReader(0, sync, oldTypes, 9000, nvarchar);
-                                TestTextReader(0, sync, oldTypes, 1000, nvarchar);
-                                TestTextReader(10000, sync, oldTypes, 0, nvarchar);
-
-                                TestXml2Text(sync, oldTypes, -1, nvarchar);
-                                TestXml2Text(sync, oldTypes, 1000000, nvarchar);
-                                TestXml2Text(sync, oldTypes, 9000, nvarchar);
-                                TestXml2Text(sync, oldTypes, 1000, nvarchar);
-                                TestXml2Text(sync, oldTypes, 0, nvarchar);
-
-                                TestCustomTextReader(10000, sync, oldTypes, -1, nvarchar, error: false);
-                                TestCustomTextReader(10000, sync, oldTypes, 9000, nvarchar, error: false);
-                                TestCustomTextReader(10000, sync, oldTypes, 1000, nvarchar, error: false);
-                                TestCustomTextReader(10000, sync, oldTypes, 0, nvarchar, error: false);
-                                TestCustomTextReader(10000, sync, oldTypes, -1, nvarchar, error: true);
-
-
-                                nvarchar = !nvarchar;
-                            } while (nvarchar);
-
-                            if (!oldTypes)
-                            {
-                                TestXML(sync, true);
-                                TestXML(sync, false);
-
-                                TestStream(100000, sync, oldTypes, -1, addWithValue: true);
-                                TestStream(0, sync, oldTypes, -1, addWithValue: true);
-
-                                TestCustomStream(10000, sync, oldTypes, -1, error: false, addWithValue: true);
-                                TestCustomStream(10000, sync, oldTypes, -1, error: true, addWithValue: true);
-
-                                TestTextReader(100000, sync, oldTypes, -1, nvarchar: true, addWithValue: true);
-                                TestTextReader(0, sync, oldTypes, -1, nvarchar: true, addWithValue: true);
-
-                                TestCustomTextReader(10000, sync, oldTypes, -1, nvarchar: true, error: false, addWithValue: true);
-                                TestCustomTextReader(10000, sync, oldTypes, -1, nvarchar: true, error: true, addWithValue: true);
-
-                                TestXML(sync, lengthLimited: false, addWithValue: true);
-                            }
-                        }
-                    }
-
-                    oldTypes = !oldTypes;
-                } while (oldTypes);
-                s_useSP = !s_useSP;
-            } while (s_useSP);
-#else
-            Console.WriteLine("Tests using AsyncDebugScope are only supported in Debug mode!");
-#endif
-            Console.WriteLine("Finished Test using AsyncDebugScope");
-
-            ImmediateCancelBin();
-            ImmediateCancelText();
-            ImmediateCancelXml();
-            PrepareCommand();
-            CommandReuse();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs
deleted file mode 100644 (file)
index c603bd8..0000000
+++ /dev/null
@@ -1,1732 +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;
-using System.Collections.Generic;
-using System.IO;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Globalization;
-using System.Reflection;
-using System.Text;
-using System.Transactions;
-
-using Microsoft.SqlServer.Server;
-using Xunit;
-using System.Threading.Tasks;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class TvpTest
-    {
-        private const string TvpName = "@tvp";
-        private static readonly IList<SteAttributeKey> BoundariesTestKeys = new List<SteAttributeKey>(
-                new SteAttributeKey[] {
-                    SteAttributeKey.SqlDbType,
-                    SteAttributeKey.MultiValued,
-                    SteAttributeKey.MaxLength,
-                    SteAttributeKey.Precision,
-                    SteAttributeKey.Scale,
-                    SteAttributeKey.LocaleId,
-                    SteAttributeKey.CompareOptions,
-                    SteAttributeKey.TypeName,
-                    SteAttributeKey.Type,
-                    SteAttributeKey.Fields,
-                    SteAttributeKey.Value
-                }).AsReadOnly();
-
-        // data value and server consts
-        private string _connStr;
-
-        [ActiveIssue("https://github.com/dotnet/corefx/issues/27858", TestPlatforms.AnyUnix)]
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestMain()
-        {
-            Assert.True(RunTestCoreAndCompareWithBaseline());
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestPacketNumberWraparound()
-        {
-            // this test uses a specifically crafted sql record enumerator and data to put the TdsParserStateObject.WritePacket(byte,bool)
-            // into a state where it can't differentiate between a packet in the middle of a large packet-set after a byte counter wraparound
-            // and the first packet of the connection and in doing so trips over a check for packet length from the input which has been
-            // forced to tell it that there is no output buffer space left, this causes an uncancellable infinite loop
-
-            // if the enumerator is completely read to the end then the bug is no longer present and the packet creation task returns,
-            // if the timeout occurs it is probable (but not absolute) that the write is stuck
-
-            var enumerator = new WraparoundRowEnumerator(1000000);
-
-            Stopwatch stopwatch = new Stopwatch();
-            stopwatch.Start();
-            int returned = Task.WaitAny(
-                Task.Factory.StartNew(
-                    () => RunPacketNumberWraparound(enumerator),
-                    TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning
-                ),
-                Task.Delay(TimeSpan.FromSeconds(60))
-            );
-            stopwatch.Stop();
-            if (enumerator.MaxCount != enumerator.Count)
-            {
-                Console.WriteLine($"enumerator.Count={enumerator.Count}, enumerator.MaxCount={enumerator.MaxCount}, elapsed={stopwatch.Elapsed.TotalSeconds}");
-            }
-            Assert.True(enumerator.MaxCount == enumerator.Count);
-        }
-
-
-        public TvpTest()
-        {
-            _connStr = DataTestUtility.TcpConnStr;
-        }
-
-        private void RunTest()
-        {
-            Console.WriteLine("Starting test \'TvpTest\'");
-            StreamInputParam.Run(_connStr);
-            ColumnBoundariesTest();
-            QueryHintsTest();
-            SqlVariantParam.SendAllSqlTypesInsideVariant(_connStr);
-            DateTimeVariantTest.TestAllDateTimeWithDataTypeAndVariant(_connStr);
-            OutputParameter.Run(_connStr);
-        }
-
-        private bool RunTestCoreAndCompareWithBaseline()
-        {
-            string outputPath = "SqlParameterTest.out";
-#if DEBUG
-            string baselinePath = "SqlParameterTest_DebugMode.bsl";
-#else
-            string baselinePath = "SqlParameterTest_ReleaseMode.bsl";
-#endif
-
-            var fstream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
-            var swriter = new StreamWriter(fstream, Encoding.UTF8);
-            // Convert all string writes of '\n' to '\r\n' so output files can be 'text' not 'binary'
-            var twriter = new CarriageReturnLineFeedReplacer(swriter);
-            Console.SetOut(twriter); // "redirect" Console.Out
-
-            // Run Test
-            RunTest();
-
-            Console.Out.Flush();
-            Console.Out.Dispose();
-
-            // Recover the standard output stream
-            StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
-            standardOutput.AutoFlush = true;
-            Console.SetOut(standardOutput);
-
-            // Compare output file
-            var comparisonResult = FindDiffFromBaseline(baselinePath, outputPath);
-
-            if (string.IsNullOrEmpty(comparisonResult))
-            {
-                return true;
-            }
-
-            Console.WriteLine("Test Failed!");
-            Console.WriteLine("Please compare baseline : {0} with output :{1}", Path.GetFullPath(baselinePath), Path.GetFullPath(outputPath));
-            Console.WriteLine("Comparison Results : ");
-            Console.WriteLine(comparisonResult);
-            return false;
-        }
-
-        private string FindDiffFromBaseline(string baselinePath, string outputPath)
-        {
-            var expectedLines = File.ReadAllLines(baselinePath);
-            var outputLines = File.ReadAllLines(outputPath);
-
-            var comparisonSb = new StringBuilder();
-
-            // Start compare results
-            var expectedLength = expectedLines.Length;
-            var outputLength = outputLines.Length;
-            var findDiffLength = Math.Min(expectedLength, outputLength);
-
-            // Find diff for each lines
-            for (var lineNo = 0; lineNo < findDiffLength; lineNo++)
-            {
-                if (!expectedLines[lineNo].Equals(outputLines[lineNo]))
-                {
-                    comparisonSb.AppendFormat("** DIFF at line {0} \n", lineNo);
-                    comparisonSb.AppendFormat("A : {0} \n", outputLines[lineNo]);
-                    comparisonSb.AppendFormat("E : {0} \n", expectedLines[lineNo]);
-                }
-            }
-
-            var startIndex = findDiffLength - 1;
-            if (startIndex < 0)
-                startIndex = 0;
-
-            if (findDiffLength < expectedLength)
-            {
-                comparisonSb.AppendFormat("** MISSING \n");
-                for (var lineNo = startIndex; lineNo < expectedLength; lineNo++)
-                {
-                    comparisonSb.AppendFormat("{0} : {1}", lineNo, expectedLines[lineNo]);
-                }
-            }
-            if (findDiffLength < outputLength)
-            {
-                comparisonSb.AppendFormat("** EXTRA \n");
-                for (var lineNo = startIndex; lineNo < outputLength; lineNo++)
-                {
-                    comparisonSb.AppendFormat("{0} : {1}", lineNo, outputLines[lineNo]);
-                }
-            }
-
-            return comparisonSb.ToString();
-        }
-
-        private sealed class CarriageReturnLineFeedReplacer : TextWriter
-        {
-            private TextWriter _output;
-            private int _lineFeedCount;
-            private bool _hasCarriageReturn;
-
-            internal CarriageReturnLineFeedReplacer(TextWriter output)
-            {
-                if (output == null)
-                    throw new ArgumentNullException(nameof(output));
-
-                _output = output;
-            }
-
-            public int LineFeedCount
-            {
-                get { return _lineFeedCount; }
-            }
-
-            public override Encoding Encoding
-            {
-                get { return _output.Encoding; }
-            }
-
-            public override IFormatProvider FormatProvider
-            {
-                get { return _output.FormatProvider; }
-            }
-
-            public override string NewLine
-            {
-                get { return _output.NewLine; }
-                set { _output.NewLine = value; }
-            }
-
-            protected override void Dispose(bool disposing)
-            {
-                if (disposing)
-                {
-                    ((IDisposable)_output).Dispose();
-                }
-                _output = null;
-            }
-
-            public override void Flush()
-            {
-                _output.Flush();
-            }
-
-            public override void Write(char value)
-            {
-                if ('\n' == value)
-                {
-                    _lineFeedCount++;
-                    if (!_hasCarriageReturn)
-                    {   // X'\n'Y -> X'\r\n'Y
-                        _output.Write('\r');
-                    }
-                }
-                _hasCarriageReturn = '\r' == value;
-                _output.Write(value);
-            }
-        }
-
-        #region Main test methods
-        private void ColumnBoundariesTest()
-        {
-            IEnumerator<StePermutation> boundsMD = SteStructuredTypeBoundaries.AllColumnTypesExceptUdts.GetEnumerator(
-                        BoundariesTestKeys);
-
-            TestTVPPermutations(SteStructuredTypeBoundaries.AllColumnTypesExceptUdts, false);
-            //Console.WriteLine("+++++++++++  UDT TVP tests ++++++++++++++");
-            //TestTVPPermutations(SteStructuredTypeBoundaries.UdtsOnly, true);
-        }
-
-        private void TestTVPPermutations(SteStructuredTypeBoundaries bounds, bool runOnlyDataRecordTest)
-        {
-            IEnumerator<StePermutation> boundsMD = bounds.GetEnumerator(BoundariesTestKeys);
-
-            object[][] baseValues = SteStructuredTypeBoundaries.GetSeparateValues(boundsMD);
-            IList<DataTable> dtList = GenerateDataTables(baseValues);
-
-            TransactionOptions opts = new TransactionOptions();
-            opts.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
-
-            // for each unique pattern of metadata
-            int iter = 0;
-            while (boundsMD.MoveNext())
-            {
-                Console.WriteLine("+++++++ Iteration {0} ++++++++", iter);
-                StePermutation tvpPerm = boundsMD.Current;
-
-                // Set up base command
-                SqlCommand cmd;
-                SqlParameter param;
-                cmd = new SqlCommand(GetProcName(tvpPerm));
-                cmd.CommandType = CommandType.StoredProcedure;
-                param = cmd.Parameters.Add(TvpName, SqlDbType.Structured);
-                param.TypeName = GetTypeName(tvpPerm);
-
-                // set up the server
-                try
-                {
-                    CreateServerObjects(tvpPerm);
-                }
-                catch (SqlException se)
-                {
-                    Console.WriteLine("SqlException creating objects: {0}", se.Number);
-                    DropServerObjects(tvpPerm);
-                    iter++;
-                    continue;
-                }
-
-                // Send list of SqlDataRecords as value
-                Console.WriteLine("------IEnumerable<SqlDataRecord>---------");
-                try
-                {
-                    param.Value = CreateListOfRecords(tvpPerm, baseValues);
-                    ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
-                }
-                catch (ArgumentException ae)
-                {
-                    // some argument exceptions expected and should be swallowed
-                    Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
-                }
-
-                if (!runOnlyDataRecordTest)
-                {
-                    // send DbDataReader
-                    Console.WriteLine("------DbDataReader---------");
-                    try
-                    {
-                        param.Value = new TvpRestartableReader(CreateListOfRecords(tvpPerm, baseValues));
-                        ExecuteAndVerify(cmd, tvpPerm, baseValues, null);
-                    }
-                    catch (ArgumentException ae)
-                    {
-                        // some argument exceptions expected and should be swallowed
-                        Console.WriteLine("Argument exception in value setup: {0}", ae.Message);
-                    }
-
-                    // send datasets
-                    Console.WriteLine("------DataTables---------");
-                    foreach (DataTable d in dtList)
-                    {
-                        param.Value = d;
-                        ExecuteAndVerify(cmd, tvpPerm, null, d);
-                    }
-                }
-
-                // And clean up
-                DropServerObjects(tvpPerm);
-
-                iter++;
-            }
-        }
-
-        private void QueryHintsTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                Guid randomizer = Guid.NewGuid();
-                string typeName = string.Format("dbo.[QHint_{0}]", randomizer);
-                string procName = string.Format("dbo.[QHint_Proc_{0}]", randomizer);
-                string createTypeSql = string.Format(
-                        "CREATE TYPE {0} AS TABLE("
-                            + " c1 Int DEFAULT -1,"
-                            + " c2 NVarChar(40) DEFAULT N'DEFUALT',"
-                            + " c3 DateTime DEFAULT '1/1/2006',"
-                            + " c4 Int DEFAULT -1)",
-                            typeName);
-                string createProcSql = string.Format(
-                        "CREATE PROC {0}(@tvp {1} READONLY) AS SELECT TOP(2) * FROM @tvp ORDER BY c1", procName, typeName);
-                string dropSql = string.Format("DROP PROC {0}; DROP TYPE {1}", procName, typeName);
-
-                try
-                {
-                    SqlCommand cmd = new SqlCommand(createTypeSql, conn);
-                    cmd.ExecuteNonQuery();
-
-                    cmd.CommandText = createProcSql;
-                    cmd.ExecuteNonQuery();
-
-                    cmd.CommandText = procName;
-                    cmd.CommandType = CommandType.StoredProcedure;
-                    SqlParameter param = cmd.Parameters.Add("@tvp", SqlDbType.Structured);
-
-                    SqlMetaData[] columnMetadata;
-                    List<SqlDataRecord> rows = new List<SqlDataRecord>();
-                    SqlDataRecord record;
-
-                    Console.WriteLine("------- Sort order + uniqueness #1: simple -------");
-                    columnMetadata = new SqlMetaData[] {
-                            new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 0),
-                            new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 1),
-                            new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
-                            new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
-                        };
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(0, "Z-value", DateTime.Parse("03/01/2000"), 5);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(1, "Y-value", DateTime.Parse("02/01/2000"), 6);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(1, "X-value", DateTime.Parse("01/01/2000"), 7);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 8);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(1, "X-value", DateTime.Parse("04/01/2000"), 4);
-                    rows.Add(record);
-
-                    param.Value = rows;
-                    using (SqlDataReader rdr = cmd.ExecuteReader())
-                    {
-                        WriteReader(rdr);
-                    }
-                    rows.Clear();
-
-                    Console.WriteLine("------- Sort order + uniqueness #2: mixed order -------");
-                    columnMetadata = new SqlMetaData[] {
-                            new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Descending, 3),
-                            new SqlMetaData("", SqlDbType.NVarChar, 40, false, true, SortOrder.Descending, 0),
-                            new SqlMetaData("", SqlDbType.DateTime, false, true, SortOrder.Ascending, 2),
-                            new SqlMetaData("", SqlDbType.Int, false, true, SortOrder.Ascending, 1),
-                        };
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    param.Value = rows;
-                    using (SqlDataReader rdr = cmd.ExecuteReader())
-                    {
-                        WriteReader(rdr);
-                    }
-                    rows.Clear();
-
-                    Console.WriteLine("------- default column #1: outer subset -------");
-                    columnMetadata = new SqlMetaData[] {
-                            new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.NVarChar, 40, false, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.DateTime, false, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
-                        };
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    param.Value = rows;
-                    using (SqlDataReader rdr = cmd.ExecuteReader())
-                    {
-                        WriteReader(rdr);
-                    }
-                    rows.Clear();
-
-                    Console.WriteLine("------- default column #1: middle subset -------");
-                    columnMetadata = new SqlMetaData[] {
-                            new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.Int, false, false, SortOrder.Unspecified, -1),
-                        };
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    param.Value = rows;
-                    using (SqlDataReader rdr = cmd.ExecuteReader())
-                    {
-                        WriteReader(rdr);
-                    }
-                    rows.Clear();
-
-                    Console.WriteLine("------- default column #1: all -------");
-                    columnMetadata = new SqlMetaData[] {
-                            new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.NVarChar, 40, true, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.DateTime, true, false, SortOrder.Unspecified, -1),
-                            new SqlMetaData("", SqlDbType.Int, true, false, SortOrder.Unspecified, -1),
-                        };
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 1);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Z-value", DateTime.Parse("01/01/2000"), 2);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(6, "Y-value", DateTime.Parse("02/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(5, "X-value", DateTime.Parse("03/01/2000"), 3);
-                    rows.Add(record);
-
-                    record = new SqlDataRecord(columnMetadata);
-                    record.SetValues(4, "X-value", DateTime.Parse("01/01/2000"), 3);
-                    rows.Add(record);
-
-                    param.Value = rows;
-                    using (SqlDataReader rdr = cmd.ExecuteReader())
-                    {
-                        WriteReader(rdr);
-                    }
-                    rows.Clear();
-
-                }
-                catch (Exception e)
-                {
-                    Console.WriteLine(e.Message);
-                }
-                finally
-                {
-                    SqlCommand cmd = new SqlCommand(dropSql, conn);
-                    cmd.ExecuteNonQuery();
-                }
-
-            }
-        }
-
-        private static async Task RunPacketNumberWraparound(WraparoundRowEnumerator enumerator)
-        {
-            using (var connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (var cmd = new SqlCommand("unimportant")
-            {
-                CommandType = System.Data.CommandType.StoredProcedure,
-                Connection = connection,
-            })
-            {
-                await cmd.Connection.OpenAsync();
-                cmd.Parameters.Add(new SqlParameter("@rows", SqlDbType.Structured)
-                {
-                    TypeName = "unimportant",
-                    Value = enumerator,
-                });
-                try
-                {
-                    await cmd.ExecuteNonQueryAsync();
-                }
-                catch (Exception)
-                {
-                    // ignore the errors caused by the sproc and table type not existing
-                }
-            }
-        }
-        #endregion
-
-        #region Utility Methods
-
-        private bool AllowableDifference(string source, object result, StePermutation metadata)
-        {
-            object value;
-            bool returnValue = false;
-
-            // turn result into a string
-            string resultStr = null;
-            if (result.GetType() == typeof(string))
-            {
-                resultStr = (string)result;
-            }
-            else if (result.GetType() == typeof(char[]))
-            {
-                resultStr = new string((char[])result);
-            }
-            else if (result.GetType() == typeof(SqlChars))
-            {
-                resultStr = new string(((SqlChars)result).Value);
-            }
-
-            if (resultStr != null)
-            {
-                if (source.Equals(resultStr))
-                {
-                    returnValue = true;
-                }
-                else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
-                {
-                    int maxLength = (int)value;
-
-                    if (maxLength < source.Length &&
-                            source.Substring(0, maxLength).Equals(resultStr))
-                    {
-                        returnValue = true;
-                    }
-                    // Check for length extension due to fixed-length type
-                    else if (maxLength > source.Length &&
-                                resultStr.Length == maxLength &&
-                                metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
-                                value != SteTypeBoundaries.s_doNotUseMarker &&
-                                (SqlDbType.Char == ((SqlDbType)value) ||
-                                  SqlDbType.NChar == ((SqlDbType)value)))
-                    {
-                        returnValue = true;
-                    }
-                }
-            }
-
-            return returnValue;
-        }
-
-        private bool AllowableDifference(byte[] source, object result, StePermutation metadata)
-        {
-            object value;
-            bool returnValue = false;
-
-            // turn result into byte array
-            byte[] resultBytes = null;
-            if (result.GetType() == typeof(byte[]))
-            {
-                resultBytes = (byte[])result;
-            }
-            else if (result.GetType() == typeof(SqlBytes))
-            {
-                resultBytes = ((SqlBytes)result).Value;
-            }
-
-            if (resultBytes != null)
-            {
-                if (source.Equals(resultBytes) || resultBytes.Length == source.Length)
-                {
-                    returnValue = true;
-                }
-                else if (metadata.TryGetValue(SteAttributeKey.MaxLength, out value) && value != SteTypeBoundaries.s_doNotUseMarker)
-                {
-                    int maxLength = (int)value;
-
-                    // allowable max-length adjustments
-                    if (maxLength == resultBytes.Length)
-                    {  // a bit optimistic, but what the heck.
-                        // truncation
-                        if (maxLength <= source.Length)
-                        {
-                            returnValue = true;
-                        }
-                        // Check for length extension due to fixed-length type
-                        else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) && value != SteTypeBoundaries.s_doNotUseMarker &&
-                                (SqlDbType.Binary == ((SqlDbType)value)))
-                        {
-                            returnValue = true;
-                        }
-                    }
-                }
-            }
-
-            return returnValue;
-        }
-
-        private bool AllowableDifference(SqlDecimal source, object result, StePermutation metadata)
-        {
-            object value;
-            object value2;
-            bool returnValue = false;
-
-            // turn result into SqlDecimal
-            SqlDecimal resultValue = SqlDecimal.Null;
-            if (result.GetType() == typeof(SqlDecimal))
-            {
-                resultValue = (SqlDecimal)result;
-            }
-            else if (result.GetType() == typeof(decimal))
-            {
-                resultValue = new SqlDecimal((decimal)result);
-            }
-            else if (result.GetType() == typeof(SqlMoney))
-            {
-                resultValue = new SqlDecimal(((SqlMoney)result).Value);
-            }
-
-            if (!resultValue.IsNull)
-            {
-                if (source.Equals(resultValue))
-                {
-                    returnValue = true;
-                }
-                else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
-                        SteTypeBoundaries.s_doNotUseMarker != value &&
-                        (SqlDbType.SmallMoney == (SqlDbType)value ||
-                         SqlDbType.Money == (SqlDbType)value))
-                {
-                    // Some server conversions seem to lose the decimal places
-                    // TODO: Investigate and validate that this is acceptable!
-                    SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, source.Precision, 0);
-                    if (tmp.Equals(resultValue))
-                    {
-                        returnValue = true;
-                    }
-                    else
-                    {
-                        tmp = SqlDecimal.ConvertToPrecScale(resultValue, resultValue.Precision, 0);
-                        returnValue = tmp.Equals(source);
-                    }
-                }
-                // check if value was altered by precision/scale conversion
-                else if (metadata.TryGetValue(SteAttributeKey.SqlDbType, out value) &&
-                        SteTypeBoundaries.s_doNotUseMarker != value &&
-                        SqlDbType.Decimal == (SqlDbType)value)
-                {
-                    if (metadata.TryGetValue(SteAttributeKey.Scale, out value) &&
-                            metadata.TryGetValue(SteAttributeKey.Precision, out value2) &&
-                            SteTypeBoundaries.s_doNotUseMarker != value &&
-                            SteTypeBoundaries.s_doNotUseMarker != value2)
-                    {
-                        SqlDecimal tmp = SqlDecimal.ConvertToPrecScale(source, (byte)value2, (byte)value);
-
-                        returnValue = tmp.Equals(resultValue);
-                    }
-
-                    // check if value was changed to 1 by the restartable reader
-                    //   due to exceeding size limits of System.Decimal
-                    if (resultValue == (SqlDecimal)1M)
-                    {
-                        try
-                        {
-                            decimal dummy = source.Value;
-                        }
-                        catch (OverflowException)
-                        {
-                            returnValue = true;
-                        }
-                    }
-                }
-            }
-
-            return returnValue;
-        }
-
-
-        private bool CompareValue(object result, object source, StePermutation metadata)
-        {
-            bool isMatch = false;
-            if (!IsNull(source))
-            {
-                if (!IsNull(result))
-                {
-                    if (source.Equals(result) || result.Equals(source))
-                    {
-                        isMatch = true;
-                    }
-                    else
-                    {
-                        switch (Type.GetTypeCode(source.GetType()))
-                        {
-                            case TypeCode.String:
-                                isMatch = AllowableDifference((string)source, result, metadata);
-                                break;
-                            case TypeCode.Object:
-                                {
-                                    if (source is char[])
-                                    {
-                                        source = new string((char[])source);
-                                        isMatch = AllowableDifference((string)source, result, metadata);
-                                    }
-                                    else if (source is byte[])
-                                    {
-                                        isMatch = AllowableDifference((byte[])source, result, metadata);
-                                    }
-                                    else if (source is SqlBytes)
-                                    {
-                                        isMatch = AllowableDifference(((SqlBytes)source).Value, result, metadata);
-                                    }
-                                    else if (source is SqlChars)
-                                    {
-                                        source = new string(((SqlChars)source).Value);
-                                        isMatch = AllowableDifference((string)source, result, metadata);
-                                    }
-                                    else if (source is SqlInt64 && result is long)
-                                    {
-                                        isMatch = result.Equals(((SqlInt64)source).Value);
-                                    }
-                                    else if (source is SqlInt32 && result is int)
-                                    {
-                                        isMatch = result.Equals(((SqlInt32)source).Value);
-                                    }
-                                    else if (source is SqlInt16 && result is short)
-                                    {
-                                        isMatch = result.Equals(((SqlInt16)source).Value);
-                                    }
-                                    else if (source is SqlSingle && result is float)
-                                    {
-                                        isMatch = result.Equals(((SqlSingle)source).Value);
-                                    }
-                                    else if (source is SqlDouble && result is double)
-                                    {
-                                        isMatch = result.Equals(((SqlDouble)source).Value);
-                                    }
-                                    else if (source is SqlDateTime && result is DateTime)
-                                    {
-                                        isMatch = result.Equals(((SqlDateTime)source).Value);
-                                    }
-                                    else if (source is SqlMoney)
-                                    {
-                                        isMatch = AllowableDifference(new SqlDecimal(((SqlMoney)source).Value), result, metadata);
-                                    }
-                                    else if (source is SqlDecimal)
-                                    {
-                                        isMatch = AllowableDifference((SqlDecimal)source, result, metadata);
-                                    }
-                                }
-                                break;
-                            case TypeCode.Decimal:
-                                if (result is SqlDecimal || result is decimal || result is SqlMoney)
-                                {
-                                    isMatch = AllowableDifference(new SqlDecimal((decimal)source), result, metadata);
-                                }
-                                break;
-                            default:
-                                break;
-                        }
-                    }
-                }
-            }
-            else
-            {
-                if (IsNull(result))
-                {
-                    isMatch = true;
-                }
-            }
-
-            if (!isMatch)
-            {
-                ReportMismatch(source, result, metadata);
-            }
-            return isMatch;
-        }
-
-        private IList<SqlDataRecord> CreateListOfRecords(StePermutation tvpPerm, object[][] baseValues)
-        {
-            IList<StePermutation> fields = GetFields(tvpPerm);
-            SqlMetaData[] fieldMetadata = new SqlMetaData[fields.Count];
-            int i = 0;
-            foreach (StePermutation perm in fields)
-            {
-                fieldMetadata[i] = PermToSqlMetaData(perm);
-                i++;
-            }
-
-            List<SqlDataRecord> records = new List<SqlDataRecord>(baseValues.Length);
-            for (int rowOrd = 0; rowOrd < baseValues.Length; rowOrd++)
-            {
-                object[] row = baseValues[rowOrd];
-                SqlDataRecord rec = new SqlDataRecord(fieldMetadata);
-                records.Add(rec); // Call SetValue *after* Add to ensure record is put in list
-                for (int colOrd = 0; colOrd < row.Length; colOrd++)
-                {
-                    // Set value in try-catch to prevent some errors from aborting run.
-                    try
-                    {
-                        rec.SetValue(colOrd, row[colOrd]);
-                    }
-                    catch (OverflowException oe)
-                    {
-                        Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], oe.Message);
-                    }
-                    catch (ArgumentException ae)
-                    {
-                        Console.WriteLine("Failed Row[{0}]Col[{1}] = {2}: {3}", rowOrd, colOrd, row[colOrd], ae.Message);
-                    }
-                }
-            }
-
-            return records;
-        }
-
-        private DataTable CreateNewTable(object[] row, ref Type[] lastRowTypes)
-        {
-            DataTable dt = new DataTable();
-            for (int i = 0; i < row.Length; i++)
-            {
-                object value = row[i];
-                Type t;
-                if ((null == value || DBNull.Value == value))
-                {
-                    if (lastRowTypes[i] == null)
-                    {
-                        return null;
-                    }
-                    else
-                    {
-                        t = lastRowTypes[i];
-                    }
-                }
-                else
-                {
-                    t = value.GetType();
-                }
-
-                dt.Columns.Add(new DataColumn("Col" + i + "_" + t.Name, t));
-                lastRowTypes[i] = t;
-            }
-
-            return dt;
-        }
-
-        // create table type and proc that uses that type at the server
-        private void CreateServerObjects(StePermutation tvpPerm)
-        {
-
-            // Create the table type tsql
-            StringBuilder tsql = new StringBuilder();
-            tsql.Append("CREATE TYPE ");
-            tsql.Append(GetTypeName(tvpPerm));
-            tsql.Append(" AS TABLE(");
-            bool addSeparator = false;
-            int colOrdinal = 1;
-            foreach (StePermutation perm in GetFields(tvpPerm))
-            {
-                if (addSeparator)
-                {
-                    tsql.Append(", ");
-                }
-                else
-                {
-                    addSeparator = true;
-                }
-
-                // column name
-                tsql.Append("column");
-                tsql.Append(colOrdinal);
-                tsql.Append(" ");
-
-                // column type
-                SqlDbType dbType = (SqlDbType)perm[SteAttributeKey.SqlDbType];
-                switch (dbType)
-                {
-                    case SqlDbType.BigInt:
-                        tsql.Append("Bigint");
-                        break;
-                    case SqlDbType.Binary:
-                        tsql.Append("Binary(");
-                        object maxLenObj = perm[SteAttributeKey.MaxLength];
-                        int maxLen;
-                        if (maxLenObj == SteTypeBoundaries.s_doNotUseMarker)
-                        {
-                            maxLen = 8000;
-                        }
-                        else
-                        {
-                            maxLen = (int)maxLenObj;
-                        }
-                        tsql.Append(maxLen);
-                        tsql.Append(")");
-                        break;
-                    case SqlDbType.Bit:
-                        tsql.Append("Bit");
-                        break;
-                    case SqlDbType.Char:
-                        tsql.Append("Char(");
-                        tsql.Append(perm[SteAttributeKey.MaxLength]);
-                        tsql.Append(")");
-                        break;
-                    case SqlDbType.DateTime:
-                        tsql.Append("DateTime");
-                        break;
-                    case SqlDbType.Decimal:
-                        tsql.Append("Decimal(");
-                        tsql.Append(perm[SteAttributeKey.Precision]);
-                        tsql.Append(", ");
-                        tsql.Append(perm[SteAttributeKey.Scale]);
-                        tsql.Append(")");
-                        break;
-                    case SqlDbType.Float:
-                        tsql.Append("Float");
-                        break;
-                    case SqlDbType.Image:
-                        tsql.Append("Image");
-                        break;
-                    case SqlDbType.Int:
-                        tsql.Append("Int");
-                        break;
-                    case SqlDbType.Money:
-                        tsql.Append("Money");
-                        break;
-                    case SqlDbType.NChar:
-                        tsql.Append("NChar(");
-                        tsql.Append(perm[SteAttributeKey.MaxLength]);
-                        tsql.Append(")");
-                        break;
-                    case SqlDbType.NText:
-                        tsql.Append("NText");
-                        break;
-                    case SqlDbType.NVarChar:
-                        tsql.Append("NVarChar(");
-                        tsql.Append(perm[SteAttributeKey.MaxLength]);
-                        tsql.Append(")");
-                        break;
-                    case SqlDbType.Real:
-                        tsql.Append("Real");
-                        break;
-                    case SqlDbType.UniqueIdentifier:
-                        tsql.Append("UniqueIdentifier");
-                        break;
-                    case SqlDbType.SmallDateTime:
-                        tsql.Append("SmallDateTime");
-                        break;
-                    case SqlDbType.SmallInt:
-                        tsql.Append("SmallInt");
-                        break;
-                    case SqlDbType.SmallMoney:
-                        tsql.Append("SmallMoney");
-                        break;
-                    case SqlDbType.Text:
-                        tsql.Append("Text");
-                        break;
-                    case SqlDbType.Timestamp:
-                        tsql.Append("Timestamp");
-                        break;
-                    case SqlDbType.TinyInt:
-                        tsql.Append("TinyInt");
-                        break;
-                    case SqlDbType.VarBinary:
-                        tsql.Append("VarBinary(");
-                        tsql.Append(perm[SteAttributeKey.MaxLength]);
-                        tsql.Append(")");
-                        break;
-                    case SqlDbType.VarChar:
-                        tsql.Append("VarChar(");
-                        tsql.Append(perm[SteAttributeKey.MaxLength]);
-                        tsql.Append(")");
-                        break;
-                    case SqlDbType.Variant:
-                        tsql.Append("Variant");
-                        break;
-                    case SqlDbType.Xml:
-                        tsql.Append("Xml");
-                        break;
-                    case SqlDbType.Udt:
-                        string typeName = (string)perm[SteAttributeKey.TypeName];
-                        tsql.Append(typeName);
-                        break;
-                    case SqlDbType.Structured:
-                        throw new NotSupportedException("Not supported");
-                }
-
-                colOrdinal++;
-            }
-
-            tsql.Append(")");
-
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                // execute it to create the type
-                SqlCommand cmd = new SqlCommand(tsql.ToString(), conn);
-                cmd.ExecuteNonQuery();
-
-                // and create the proc that uses the type
-                cmd.CommandText = string.Format("CREATE PROC {0}(@tvp {1} READONLY) AS SELECT * FROM @tvp order by {2}",
-                        GetProcName(tvpPerm), GetTypeName(tvpPerm), colOrdinal - 1);
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private bool DoesRowMatchMetadata(object[] row, DataTable table)
-        {
-            bool result = true;
-            if (row.Length != table.Columns.Count)
-            {
-                result = false;
-            }
-            else
-            {
-                for (int i = 0; i < row.Length; i++)
-                {
-                    if (null != row[i] && DBNull.Value != row[i] && row[i].GetType() != table.Columns[i].DataType)
-                    {
-                        result = false;
-                    }
-                }
-            }
-            return result;
-        }
-
-        private void DropServerObjects(StePermutation tvpPerm)
-        {
-            string dropText = "DROP PROC " + GetProcName(tvpPerm) + "; DROP TYPE " + GetTypeName(tvpPerm);
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                SqlCommand cmd = new SqlCommand(dropText, conn);
-                try
-                {
-                    cmd.ExecuteNonQuery();
-                }
-                catch (SqlException e)
-                {
-                    Console.WriteLine("SqlException dropping objects: {0}", e.Number);
-                }
-            }
-        }
-
-        private void ExecuteAndVerify(SqlCommand cmd, StePermutation tvpPerm, object[][] objValues, DataTable dtValues)
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-                cmd.Connection = conn;
-                //                cmd.Transaction = conn.BeginTransaction();
-
-                // and run the command
-                try
-                {
-                    using (SqlDataReader rdr = cmd.ExecuteReader())
-                    {
-                        VerifyColumnBoundaries(rdr, GetFields(tvpPerm), objValues, dtValues);
-                    }
-                }
-                catch (SqlException se)
-                {
-                    Console.WriteLine("SqlException. Error Code: {0}", se.Number);
-                }
-                catch (InvalidOperationException ioe)
-                {
-                    Console.WriteLine("InvalidOp: {0}", ioe.Message);
-                }
-                catch (ArgumentException ae)
-                {
-                    Console.WriteLine("ArgumentException: {0}", ae.Message);
-                }
-
-                // And clean up. If an error is thrown, the connection being recycled
-                //  will roll back the transaction
-                if (null != cmd.Transaction)
-                {
-                    //                    cmd.Transaction.Rollback();
-                }
-            }
-        }
-
-        private IList<DataTable> GenerateDataTables(object[][] values)
-        {
-            List<DataTable> dtList = new List<DataTable>();
-            Type[] valueTypes = new Type[values[0].Length];
-            foreach (object[] row in values)
-            {
-                DataTable targetTable = null;
-                if (0 < dtList.Count)
-                {
-                    // shortcut for matching last table (most common scenario)
-                    if (DoesRowMatchMetadata(row, dtList[dtList.Count - 1]))
-                    {
-                        targetTable = dtList[dtList.Count - 1];
-                    }
-                    else
-                    {
-                        foreach (DataTable candidate in dtList)
-                        {
-                            if (DoesRowMatchMetadata(row, candidate))
-                            {
-                                targetTable = candidate;
-                                break;
-                            }
-                        }
-                    }
-                }
-
-                if (null == targetTable)
-                {
-                    targetTable = CreateNewTable(row, ref valueTypes);
-                    if (null != targetTable)
-                    {
-                        dtList.Add(targetTable);
-                    }
-                }
-
-                if (null != targetTable)
-                {
-                    targetTable.Rows.Add(row);
-                }
-            }
-
-            return dtList;
-        }
-
-        private IList<StePermutation> GetFields(StePermutation tvpPerm)
-        {
-            return (IList<StePermutation>)tvpPerm[SteAttributeKey.Fields];
-        }
-
-        private string GetProcName(StePermutation tvpPerm)
-        {
-            return "dbo.[Proc_" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
-        }
-
-        private string GetTypeName(StePermutation tvpPerm)
-        {
-            return "dbo.[" + (string)tvpPerm[SteAttributeKey.TypeName] + "]";
-        }
-
-        private bool IsNull(object value)
-        {
-            return null == value ||
-                    DBNull.Value == value ||
-                    (value is INullable &&
-                     ((INullable)value).IsNull);
-        }
-
-        private SqlMetaData PermToSqlMetaData(StePermutation perm)
-        {
-            object attr;
-            SqlDbType sqlDbType;
-            int maxLength = 0;
-            byte precision = 0;
-            byte scale = 0;
-            string typeName = null;
-            Type type = null;
-            long localeId = 0;
-            SqlCompareOptions opts = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
-            if (perm.TryGetValue(SteAttributeKey.SqlDbType, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                sqlDbType = (SqlDbType)attr;
-            }
-            else
-            {
-                throw new InvalidOperationException("PermToSqlMetaData: No SqlDbType available!");
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.MaxLength, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                maxLength = (int)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.Precision, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                precision = (byte)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.Scale, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                scale = (byte)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.LocaleId, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                localeId = (int)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.CompareOptions, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                opts = (SqlCompareOptions)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.TypeName, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                typeName = (string)attr;
-            }
-
-            if (perm.TryGetValue(SteAttributeKey.Type, out attr) && (attr != SteTypeBoundaries.s_doNotUseMarker))
-            {
-                type = (Type)attr;
-            }
-
-            //if (SqlDbType.Udt == sqlDbType)
-            //{
-            //    return new SqlMetaData("", sqlDbType, type, typeName);
-            //}
-            //else
-            //{
-            return new SqlMetaData("", sqlDbType, maxLength, precision, scale, localeId, opts, type);
-            //}
-        }
-
-        private void ReportMismatch(object source, object result, StePermutation perm)
-        {
-            if (null == source)
-            {
-                source = "(null)";
-            }
-            if (null == result)
-            {
-                result = "(null)";
-            }
-            Console.WriteLine("Mismatch: Source = {0}, result = {1}, metadata={2}", source, result, perm.ToString());
-        }
-
-        private void VerifyColumnBoundaries(SqlDataReader rdr, IList<StePermutation> fieldMetaData, object[][] values, DataTable dt)
-        {
-            int rowOrd = 0;
-            int matches = 0;
-            while (rdr.Read())
-            {
-                for (int columnOrd = 0; columnOrd < rdr.FieldCount; columnOrd++)
-                {
-                    object value;
-                    // Special case to handle decimal values that may be too large for GetValue
-                    if (!rdr.IsDBNull(columnOrd) && rdr.GetFieldType(columnOrd) == typeof(decimal))
-                    {
-                        value = rdr.GetSqlValue(columnOrd);
-                    }
-                    else
-                    {
-                        value = rdr.GetValue(columnOrd);
-                    }
-                    if (null != values)
-                    {
-                        if (CompareValue(value, values[rowOrd][columnOrd], fieldMetaData[columnOrd]))
-                        {
-                            matches++;
-                        }
-                        else
-                        {
-                            Console.WriteLine("   Row={0}, Column={1}", rowOrd, columnOrd);
-                        }
-                    }
-                    else
-                    {
-                        if (CompareValue(value, dt.Rows[rowOrd][columnOrd], fieldMetaData[columnOrd]))
-                        {
-                            matches++;
-                        }
-                        else
-                        {
-                            Console.WriteLine("   Row={0}, Column={1}", rowOrd, columnOrd);
-                        }
-                    }
-                }
-                rowOrd++;
-            }
-
-            Console.WriteLine("Matches = {0}", matches);
-        }
-
-        private void WriteReader(SqlDataReader rdr)
-        {
-            int colCount = rdr.FieldCount;
-
-            do
-            {
-                Console.WriteLine("-------------");
-                while (rdr.Read())
-                {
-                    for (int i = 0; i < colCount; i++)
-                    {
-                        Console.Write("{0}  ", rdr.GetValue(i));
-                    }
-                    Console.WriteLine();
-                }
-                Console.WriteLine();
-                Console.WriteLine("-------------");
-            }
-            while (rdr.NextResult());
-        }
-
-        private void DumpSqlParam(SqlParameter param)
-        {
-            Console.WriteLine("Parameter {0}", param.ParameterName);
-            Console.WriteLine("  IsNullable: {0}", param.IsNullable);
-            Console.WriteLine("  LocaleId: {0}", param.LocaleId);
-            Console.WriteLine("  Offset: {0}", param.Offset);
-            Console.WriteLine("  CompareInfo: {0}", param.CompareInfo);
-            Console.WriteLine("  DbType: {0}", param.DbType);
-            Console.WriteLine("  Direction: {0}", param.Direction);
-            Console.WriteLine("  Precision: {0}", param.Precision);
-            Console.WriteLine("  Scale: {0}", param.Scale);
-            Console.WriteLine("  Size: {0}", param.Size);
-            Console.WriteLine("  SqlDbType: {0}", param.SqlDbType);
-            Console.WriteLine("  TypeName: {0}", param.TypeName);
-            //Console.WriteLine("  UdtTypeName: {0}", param.UdtTypeName);
-            Console.WriteLine("  XmlSchemaCollectionDatabase: {0}", param.XmlSchemaCollectionDatabase);
-            Console.WriteLine("  XmlSchemaCollectionName: {0}", param.XmlSchemaCollectionName);
-            Console.WriteLine("  XmlSchemaCollectionSchema: {0}", param.XmlSchemaCollectionOwningSchema);
-        }
-
-
-        #endregion
-    }
-
-    internal class TvpRestartableReader : DbDataReader
-    {
-        private IList<SqlDataRecord> _sourceData;
-        int _currentRow;
-
-        internal TvpRestartableReader(IList<SqlDataRecord> source) : base()
-        {
-            _sourceData = source;
-            Restart();
-        }
-
-        public void Restart()
-        {
-            _currentRow = -1;
-        }
-
-        public override int Depth
-        {
-            get { return 0; }
-        }
-
-        public override int FieldCount
-        {
-            get { return _sourceData[_currentRow].FieldCount; }
-        }
-
-        public override bool HasRows
-        {
-            get { return _sourceData.Count > 0; }
-        }
-
-        public override bool IsClosed
-        {
-            get { return false; }
-        }
-
-        public override int RecordsAffected
-        {
-            get { return 0; }
-        }
-
-        public override object this[int ordinal]
-        {
-            get { return GetValue(ordinal); }
-        }
-
-        public override object this[string name]
-        {
-            get { return GetValue(GetOrdinal(name)); }
-        }
-
-        public override void Close()
-        {
-            _currentRow = _sourceData.Count;
-        }
-
-        public override string GetDataTypeName(int ordinal)
-        {
-            return _sourceData[_currentRow].GetDataTypeName(ordinal);
-        }
-
-        public override IEnumerator GetEnumerator()
-        {
-            return _sourceData.GetEnumerator();
-        }
-
-        public override Type GetFieldType(int ordinal)
-        {
-            return _sourceData[_currentRow].GetFieldType(ordinal);
-        }
-
-        public override string GetName(int ordinal)
-        {
-            return _sourceData[_currentRow].GetName(ordinal);
-        }
-
-        public override int GetOrdinal(string name)
-        {
-            return _sourceData[_currentRow].GetOrdinal(name);
-        }
-
-        public override DataTable GetSchemaTable()
-        {
-            SqlDataRecord rec = _sourceData[0];
-
-            DataTable schemaTable = new DataTable();
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnName, typeof(string)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(int)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ColumnSize, typeof(int)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericPrecision, typeof(short)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NumericScale, typeof(short)));
-
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.DataType, typeof(System.Type)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.NonVersionedProviderType, typeof(int)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.ProviderType, typeof(int)));
-
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsLong, typeof(bool)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.AllowDBNull, typeof(bool)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(bool)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(bool)));
-
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsUnique, typeof(bool)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.IsKey, typeof(bool)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.IsHidden, typeof(bool)));
-
-            schemaTable.Columns.Add(new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(string)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(string)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseTableName, typeof(string)));
-            schemaTable.Columns.Add(new DataColumn(SchemaTableColumn.BaseColumnName, typeof(string)));
-
-            for (int i = 0; i < rec.FieldCount; i++)
-            {
-                DataRow row = schemaTable.NewRow();
-                SqlMetaData md = rec.GetSqlMetaData(i);
-                row[SchemaTableColumn.ColumnName] = md.Name;
-                row[SchemaTableColumn.ColumnOrdinal] = i;
-                row[SchemaTableColumn.ColumnSize] = md.MaxLength;
-                row[SchemaTableColumn.NumericPrecision] = md.Precision;
-                row[SchemaTableColumn.NumericScale] = md.Scale;
-                row[SchemaTableColumn.DataType] = rec.GetFieldType(i);
-                row[SchemaTableOptionalColumn.ProviderSpecificDataType] = rec.GetFieldType(i);
-                row[SchemaTableColumn.NonVersionedProviderType] = (int)md.SqlDbType;
-                row[SchemaTableColumn.ProviderType] = (int)md.SqlDbType;
-                row[SchemaTableColumn.IsLong] = md.MaxLength == SqlMetaData.Max || md.MaxLength > 8000;
-                row[SchemaTableColumn.AllowDBNull] = true;
-                row[SchemaTableOptionalColumn.IsReadOnly] = true;
-                row[SchemaTableOptionalColumn.IsRowVersion] = md.SqlDbType == SqlDbType.Timestamp;
-                row[SchemaTableColumn.IsUnique] = false;
-                row[SchemaTableColumn.IsKey] = false;
-                row[SchemaTableOptionalColumn.IsAutoIncrement] = false;
-                row[SchemaTableOptionalColumn.IsHidden] = false;
-                row[SchemaTableOptionalColumn.BaseCatalogName] = null;
-                row[SchemaTableColumn.BaseSchemaName] = null;
-                row[SchemaTableColumn.BaseTableName] = null;
-                row[SchemaTableColumn.BaseColumnName] = md.Name;
-                schemaTable.Rows.Add(row);
-            }
-
-            return schemaTable;
-        }
-
-        public override bool GetBoolean(int ordinal)
-        {
-            return _sourceData[_currentRow].GetBoolean(ordinal);
-        }
-
-        public override byte GetByte(int ordinal)
-        {
-            return _sourceData[_currentRow].GetByte(ordinal);
-        }
-
-        public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            return _sourceData[_currentRow].GetBytes(ordinal, dataOffset, buffer, bufferOffset, length);
-        }
-
-        public override char GetChar(int ordinal)
-        {
-            return _sourceData[_currentRow].GetChar(ordinal);
-        }
-
-        public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
-        {
-            return _sourceData[_currentRow].GetChars(ordinal, dataOffset, buffer, bufferOffset, length);
-        }
-
-        public override DateTime GetDateTime(int ordinal)
-        {
-            return _sourceData[_currentRow].GetDateTime(ordinal);
-        }
-
-        public override decimal GetDecimal(int ordinal)
-        {
-            // DataRecord may have illegal values for Decimal...
-            decimal result;
-            try
-            {
-                result = _sourceData[_currentRow].GetDecimal(ordinal);
-            }
-            catch (OverflowException)
-            {
-                result = (decimal)1;
-            }
-            return result;
-        }
-
-        public override double GetDouble(int ordinal)
-        {
-            return _sourceData[_currentRow].GetDouble(ordinal);
-        }
-
-        public override float GetFloat(int ordinal)
-        {
-            return _sourceData[_currentRow].GetFloat(ordinal);
-        }
-
-        public override Guid GetGuid(int ordinal)
-        {
-            return _sourceData[_currentRow].GetGuid(ordinal);
-        }
-
-        public override short GetInt16(int ordinal)
-        {
-            return _sourceData[_currentRow].GetInt16(ordinal);
-        }
-
-        public override int GetInt32(int ordinal)
-        {
-            return _sourceData[_currentRow].GetInt32(ordinal);
-        }
-
-        public override long GetInt64(int ordinal)
-        {
-            return _sourceData[_currentRow].GetInt64(ordinal);
-        }
-
-        public override string GetString(int ordinal)
-        {
-            return _sourceData[_currentRow].GetString(ordinal);
-        }
-
-        public override object GetValue(int ordinal)
-        {
-            return _sourceData[_currentRow].GetValue(ordinal);
-        }
-
-        public override int GetValues(object[] values)
-        {
-            return _sourceData[_currentRow].GetValues(values);
-        }
-
-        public override bool IsDBNull(int ordinal)
-        {
-            return _sourceData[_currentRow].IsDBNull(ordinal);
-        }
-
-        public override bool NextResult()
-        {
-            Close();
-            return false;
-        }
-
-        public override bool Read()
-        {
-            _currentRow++;
-
-            return _currentRow < _sourceData.Count;
-        }
-    }
-
-    internal class WraparoundRowEnumerator : IEnumerable<SqlDataRecord>, IEnumerator<SqlDataRecord>
-    {
-        private int _count;
-        private int _maxCount;
-        private SqlDataRecord _record;
-
-        public WraparoundRowEnumerator(int maxCount)
-        {
-            _maxCount = maxCount;
-            _record = new SqlDataRecord(new SqlMetaData("someData", SqlDbType.VarBinary, 8000));
-
-            // 56 31 0 0 is result of calling BitConverter.GetBytes((int)7992)
-            // The rest of the bytes are just padding to get 56, 31, 0, 0 to be in bytes 8-11 of TdsParserStatObject._outBuff after the 256th packet
-            _record.SetBytes(
-                0,
-                0,
-                new byte[] { 1, 2, 56, 31, 0, 0, 7, 8, 9, 10, 11, 12, 13, 14 },
-                0,
-                14);
-
-            // change any of the 56 31 0 0 bytes and this program completes as expected in a couple seconds
-        }
-
-        public bool MoveNext()
-        {
-            _count++;
-            return _count < _maxCount;
-        }
-
-        public SqlDataRecord Current => _record;
-
-        object IEnumerator.Current => Current;
-
-        public int Count { get => this._count; set => this._count = value; }
-        public int MaxCount { get => this._maxCount; set => this._maxCount = value; }
-
-        public IEnumerator<SqlDataRecord> GetEnumerator() => this;
-
-        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
-
-        public void Dispose() { }
-        public void Reset() { }
-
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/RandomStressTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/RandomStressTest.cs
deleted file mode 100644 (file)
index dffd112..0000000
+++ /dev/null
@@ -1,362 +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.Generic;
-using System.Text;
-using System.IO;
-using System.Threading;
-using System.Diagnostics;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class RandomStressTest
-    {
-        private static readonly TimeSpan TimeLimitDefault = new TimeSpan(0, 0, 10);
-        private const int ThreadCountDefault = 4;
-        private const int IterationsPerTableDefault = 50;
-
-        private const int MaxColumns = 5000;
-        private const int MaxRows = 100;
-        private const int MaxTotal = MaxColumns * 10;
-
-        private string[] _connectionStrings;
-        private string _operationCanceledErrorMessage;
-        private string _severeErrorMessage;
-
-        private SqlRandomTypeInfoCollection _katmaiTypes;
-        private ManualResetEvent _endEvent;
-        private int _runningThreads;
-
-        private long _totalValues;
-        private long _totalTables;
-        private long _totalIterations;
-        private long _totalTicks;
-        private RandomizerPool _randPool;
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestMain()
-        {
-            _operationCanceledErrorMessage = SystemDataResourceManager.Instance.SQL_OperationCancelled;
-            _severeErrorMessage = SystemDataResourceManager.Instance.SQL_SevereError;
-
-            // pure random
-            _randPool = new RandomizerPool();
-
-            SqlConnectionStringBuilder regularConnectionString = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-
-            regularConnectionString.MultipleActiveResultSets = false;
-
-            List<string> connStrings = new List<string>();
-            connStrings.Add(regularConnectionString.ToString());
-
-            connStrings.Add(regularConnectionString.ToString());
-
-            regularConnectionString.MultipleActiveResultSets = true;
-            connStrings.Add(regularConnectionString.ToString());
-
-            _connectionStrings = connStrings.ToArray();
-
-            _katmaiTypes = SqlRandomTypeInfoCollection.CreateSql2008Collection();
-            _endEvent = new ManualResetEvent(false);
-
-            if (_randPool.ReproMode)
-            {
-                _runningThreads = 1;
-                TestThread();
-            }
-            else
-            {
-                for (int tcount = 0; tcount < ThreadCountDefault; tcount++)
-                {
-                    Thread t = new Thread(TestThread);
-                    t.Start();
-                }
-            }
-        }
-
-        private void NextConnection(ref SqlConnection con, Randomizer rand)
-        {
-            if (con != null)
-            {
-                con.Close();
-            }
-
-            string connString = _connectionStrings[rand.Next(_connectionStrings.Length)];
-
-            con = new SqlConnection(connString);
-            con.Open();
-        }
-
-        private void TestThread()
-        {
-            try
-            {
-                using (var rootScope = _randPool.RootScope<SqlRandomizer>())
-                {
-                    Stopwatch watch = new Stopwatch();
-                    SqlConnection con = null;
-                    try
-                    {
-                        NextConnection(ref con, rootScope.Current);
-
-                        if (_randPool.ReproMode)
-                        {
-                            using (var testScope = rootScope.NewScope<SqlRandomizer>())
-                            {
-                                // run only once if repro file is provided
-                                RunTest(con, testScope, _katmaiTypes, watch);
-                            }
-                        }
-                        else
-                        {
-                            while (watch.Elapsed < TimeLimitDefault)
-                            {
-                                using (var testScope = rootScope.NewScope<SqlRandomizer>())
-                                {
-                                    RunTest(con, testScope, _katmaiTypes, watch);
-                                }
-
-                                if (rootScope.Current.Next(100) == 0)
-                                {
-                                    // replace the connection
-                                    NextConnection(ref con, rootScope.Current);
-                                }
-                            }
-                        }
-                    }
-                    finally
-                    {
-                        if (con != null)
-                        {
-                            con.Close();
-                        }
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                Console.WriteLine(e);
-            }
-            finally
-            {
-                if (Interlocked.Decrement(ref _runningThreads) == 0)
-                    _endEvent.Set();
-            }
-        }
-
-        private void RunTest(SqlConnection con, RandomizerPool.Scope<SqlRandomizer> testScope, SqlRandomTypeInfoCollection types, Stopwatch watch)
-        {
-            Exception pendingException = null;
-            string tempTableName = null;
-
-            try
-            {
-                // select number of columns to use and null bitmap to test
-                int columnsCount, rowsCount;
-                testScope.Current.NextTableDimentions(MaxRows, MaxColumns, MaxTotal, out rowsCount, out columnsCount);
-                SqlRandomTable table = SqlRandomTable.Create(testScope.Current, types, columnsCount, rowsCount, createPrimaryKeyColumn: true);
-
-                long total = (long)rowsCount * columnsCount;
-                Interlocked.Add(ref _totalValues, total);
-                Interlocked.Increment(ref _totalTables);
-
-                tempTableName = SqlRandomizer.GenerateUniqueTempTableNameForSqlServer();
-                table.GenerateTableOnServer(con, tempTableName);
-
-                long prevTicks = watch.ElapsedTicks;
-                watch.Start();
-
-                if (_randPool.ReproMode)
-                {
-                    // perform one iteration only
-                    using (var iterationScope = testScope.NewScope<SqlRandomizer>())
-                    {
-                        RunTestIteration(con, iterationScope.Current, table, tempTableName);
-                        Interlocked.Increment(ref _totalIterations);
-                    }
-                }
-                else
-                {
-                    // continue with normal loop
-                    for (int i = 0; i < IterationsPerTableDefault && watch.Elapsed < TimeLimitDefault; i++)
-                    {
-                        using (var iterationScope = testScope.NewScope<SqlRandomizer>())
-                        {
-                            RunTestIteration(con, iterationScope.Current, table, tempTableName);
-                            Interlocked.Increment(ref _totalIterations);
-                        }
-                    }
-                }
-
-                watch.Stop();
-                Interlocked.Add(ref _totalTicks, watch.ElapsedTicks - prevTicks);
-            }
-            catch (Exception e)
-            {
-                pendingException = e;
-                throw;
-            }
-            finally
-            {
-                // keep the temp table for troubleshooting if debugger is attached
-                // the thread is going down anyway and connection will be closed
-                if (pendingException == null && tempTableName != null)
-                {
-                    // destroy the temp table to free resources on the server
-                    SqlCommand cmd = con.CreateCommand();
-                    cmd.CommandType = CommandType.Text;
-                    cmd.CommandText = "DROP TABLE " + tempTableName;
-                    try
-                    {
-                        cmd.ExecuteNonQuery();
-                    }
-                    catch
-                    {
-                    }
-                }
-            }
-        }
-
-        private void RunTestIteration(SqlConnection con, SqlRandomizer rand, SqlRandomTable table, string tableName)
-        {
-            // random list of columns
-            int columnCount = table.Columns.Count;
-            int[] columnIndices = rand.NextIndices(columnCount);
-            int selectedCount = rand.NextIntInclusive(1, maxValueInclusive: columnCount);
-
-            StringBuilder selectBuilder = new StringBuilder();
-            table.GenerateSelectFromTableTSql(tableName, selectBuilder, columnIndices, 0, selectedCount);
-            SqlCommand cmd = con.CreateCommand();
-            cmd.CommandType = CommandType.Text;
-            cmd.CommandText = selectBuilder.ToString();
-
-            bool cancel = rand.Next(100) == 0; // in 1% of the cases, call Cancel
-
-            if (cancel)
-            {
-                int cancelAfterMilliseconds = rand.Next(5);
-                int cancelAfterSpinCount = rand.Next(1000);
-
-                ThreadPool.QueueUserWorkItem((object state) =>
-                    {
-                        for (int i = 0; cancel && i < cancelAfterMilliseconds; i++)
-                        {
-                            Thread.Sleep(1);
-                        }
-                        if (cancel && cancelAfterSpinCount > 0)
-                        {
-                            SpinWait.SpinUntil(() => false, new TimeSpan(cancelAfterSpinCount));
-                        }
-                        if (cancel)
-                        {
-                            cmd.Cancel();
-                        }
-                    });
-            }
-
-            int readerRand = rand.NextIntInclusive(0, maxValueInclusive: 256);
-            CommandBehavior readerBehavior = CommandBehavior.Default;
-            if (readerRand % 10 == 0)
-                readerBehavior = CommandBehavior.SequentialAccess;
-            try
-            {
-                using (SqlDataReader reader = cmd.ExecuteReader(readerBehavior))
-                {
-                    int row = 0;
-                    while (reader.Read())
-                    {
-                        int rowRand = rand.NextIntInclusive();
-                        if (rowRand % 1000 == 0)
-                        {
-                            // abandon this reader
-                            break;
-                        }
-                        else if (rowRand % 25 == 0)
-                        {
-                            // skip the row
-                            row++;
-                            continue;
-                        }
-
-                        IList<object> expectedRow = table[row];
-                        for (int c = 0; c < reader.FieldCount; c++)
-                        {
-                            if (rand.NextIntInclusive(0, maxValueInclusive: 10) == 0)
-                            {
-                                // skip the column
-                                continue;
-                            }
-
-                            int expectedTableColumn = columnIndices[c];
-                            object expectedValue = expectedRow[expectedTableColumn];
-                            if (table.Columns[expectedTableColumn].CanCompareValues)
-                            {
-                                Assert.True(expectedValue != null, "FAILED: Null is expected with CanCompareValues");
-
-                                // read the value same way it was written
-                                object actualValue = table.Columns[expectedTableColumn].Read(reader, c, expectedValue.GetType());
-                                Assert.True(table.Columns[expectedTableColumn].CompareValues(expectedValue, actualValue),
-                                    string.Format("FAILED: Data Comparison Failure:\n{0}", table.Columns[expectedTableColumn].BuildErrorMessage(expectedValue, actualValue)));
-                            }
-                        }
-
-                        row++;
-                    }
-                }
-
-                // keep last - this will stop the cancel task, if it is still active
-                cancel = false;
-            }
-            catch (SqlException e)
-            {
-                if (!cancel)
-                    throw;
-
-                bool expected = false;
-
-                foreach (SqlError error in e.Errors)
-                {
-                    if (error.Message == _operationCanceledErrorMessage)
-                    {
-                        // ignore this one - expected if canceled
-                        expected = true;
-                        break;
-                    }
-                    else if (error.Message == _severeErrorMessage)
-                    {
-                        // A severe error occurred on the current command.  The results, if any, should be discarded.
-                        expected = true;
-                        break;
-                    }
-                }
-
-                if (!expected)
-                {
-                    // rethrow to the user
-                    foreach (SqlError error in e.Errors)
-                    {
-                        Console.WriteLine("{0} {1}", error.Number, error.Message);
-                    }
-                    throw;
-                }
-            }
-            catch (InvalidOperationException e)
-            {
-                bool expected = false;
-
-                if (e.Message == _operationCanceledErrorMessage)
-                {
-                    // "Operation canceled" exception is raised as a SqlException (as one of SqlError objects) and as InvalidOperationException
-                    expected = true;
-                }
-
-                if (!expected)
-                {
-                    throw;
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/Randomizer.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/Randomizer.cs
deleted file mode 100644 (file)
index f1456cc..0000000
+++ /dev/null
@@ -1,472 +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.Threading;
-using System.Runtime.Serialization;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// Random number generator that tracks information necessary to reproduce a sequence of random numbers. To save the current state,
-    /// tests should query the CurrentState property before execution of the test case that uses random.
-    /// In addition, the test needs to capture the current state of random instance before setup steps, if random is used during setup.
-    ///
-    /// This class also provides more helper methods, like create numbers with high probability for low numbers.
-    ///
-    /// Use the CurrentState property to save repro information, and, when crash is detected, dump the state to file or log
-    /// with its ToString method. The performance of CurrentState has been optimized to ensure it does not affect the overall performance
-    /// of the test app. But, the CurrentState.ToString is not optimum, so use it only when crash is detected.
-    ///
-    /// For easy Random scope and repro management, see also RandomizerScope class.
-    ///
-    /// Note: instances of this class are not thread-safe!
-    /// <example>
-    /// To remember the current state of Randomizer, use randomizerInstance.CurrentState method before its first use!
-    /// To recreate the randomizer object from its log, use Randomizer.Create(state) method.
-    /// </example>
-    /// </summary>
-    public class Randomizer
-    {
-        /// <summary>
-        /// counter used to prevent same seed generation for multi-threaded operations
-        /// </summary>
-        private static int s_seedCounter;
-
-        /// <summary>
-        /// Generates a seed value based on current ticks count (Environment.TickCount) XORed with
-        /// incrementing counter to prevent duplicates if called within the interval of the 500 milliseconds
-        /// (time resolution of OS ticks). This method is thread-safe!
-        /// </summary>
-        public static int CreateSeed()
-        {
-            return Environment.TickCount ^ Interlocked.Increment(ref s_seedCounter);
-        }
-
-        /// <summary>
-        /// encapsulate the randomizer state which is a byte array within the read-only structure
-        /// </summary>
-        /// <remarks>Keep it immutable - randomizer pool creates shallow copies of the state struct only!</remarks>
-        public struct State
-        {
-            internal readonly Type _randomizerType;
-            internal readonly byte[] _binState;
-
-            internal State(Type randType, byte[] binState)
-            {
-                _binState = binState;
-                _randomizerType = randType;
-            }
-
-            private const char Separator = ':';
-
-            /// <summary>
-            /// Creates human-readable string representation of the state.
-            /// Use it only when you need to dump the rand state to the file or log.
-            /// </summary>
-            public override string ToString()
-            {
-                if (_binState == null && _randomizerType == null)
-                    return string.Empty;
-
-                return string.Format("{0}{1}{2}", _randomizerType.FullName, Separator, Convert.ToBase64String(_binState));
-            }
-
-            /// <summary>
-            /// recreates the state instance from string, generated by ToString()
-            /// </summary>
-            public static State Parse(string strState)
-            {
-                if (string.IsNullOrEmpty(strState))
-                    return State.Empty;
-
-                string[] items = strState.Split(new char[] { Separator }, 2);
-                return new State(
-                    Type.GetType(items[0]),
-                    Convert.FromBase64String(items[1]));
-            }
-
-            /// <summary>
-            /// represents an empty randomizer state, it cannot be used to create a randomizer!
-            /// </summary>
-            public static readonly State Empty = new State(null, null);
-        }
-
-        /// <summary>
-        /// creates a new randomizer from seed
-        /// Target Randomizer implementation must have an explicit c-tor that accepts seed only!
-        /// </summary>
-        public static RandomizerType Create<RandomizerType>(int seed)
-            where RandomizerType : Randomizer, new()
-        {
-            if (typeof(RandomizerType) == typeof(Randomizer))
-            {
-                // optimization for Randomizer itself to avoid reflection call
-                return (RandomizerType)new Randomizer(seed);
-            }
-            else
-            {
-                return (RandomizerType)Activator.CreateInstance(typeof(RandomizerType), new object[] { seed });
-            }
-        }
-
-        /// <summary>
-        /// Recreates randomizer from the state, state must not be empty!
-        /// Target Randomizer implementation must have an explicit c-tor that accepts state only and calls into base c-tor(state)!
-        /// </summary>
-        public static RandomizerType Create<RandomizerType>(State state)
-            where RandomizerType : Randomizer, new()
-        {
-            if (typeof(RandomizerType) == typeof(Randomizer))
-            {
-                // optimization for Randomizer itself to avoid redundant construction
-                return (RandomizerType)new Randomizer(state);
-            }
-            else
-            {
-                return (RandomizerType)Activator.CreateInstance(typeof(RandomizerType), new object[] { state });
-            }
-        }
-
-        /// <summary>
-        /// Used to create an instance of randomizer from its state. Use Create static method to create the instance.
-        /// </summary>
-        /// <remarks>when overriding Randomizer, explicitly define a new protected constructor that accepts state only</remarks>
-        protected Randomizer(State state)
-        {
-            Deserialize(state);
-        }
-
-        /// <summary>
-        /// gets the current state of the Randomizer
-        /// To trace it, you can use state.ToString() method.
-        /// </summary>
-        public State GetCurrentState()
-        {
-            byte[] binState = new byte[BinaryStateSize];
-            int offset;
-            Serialize(binState, out offset);
-            return new State(GetType(), binState);
-        }
-
-        /// <summary>
-        /// returns size needed to serialize the randomizer state, override this method to reserve space for custom fields.
-        /// </summary>
-        protected virtual int BinaryStateSize
-        {
-            get
-            {
-                return BinaryStateSizeRandom;
-            }
-        }
-
-        /// <summary>
-        /// this method is used to serialize the state, binState size must be BinaryStateSize
-        /// </summary>
-        /// <remarks>
-        /// call base.Serialize first when overriding this method and use the nextOffset to write custom data
-        /// </remarks>
-        /// <remarks>
-        /// For fast performance, avoid using MemoryStream/BinaryReader or reflection/serialization. I measured the difference between several implementations and found that:
-        /// * Difference in time performance between using plain byte array versus MemoryStream with BinaryReader is ~ 1/10!
-        /// * Difference between this implementation and serialization via .NET Serialization is ~1/100!
-        /// </remarks>
-        protected virtual void Serialize(byte[] binState, out int nextOffset)
-        {
-            nextOffset = 0;
-            SerializeInt(_inext, binState, ref nextOffset);
-            SerializeInt(_inextp, binState, ref nextOffset);
-
-            Buffer.BlockCopy(_seedArray, 0, binState, nextOffset, 4 * _seedArray.Length);
-            nextOffset += 4 * _seedArray.Length;
-        }
-
-        private void Deserialize(State state)
-        {
-            if (state._randomizerType != GetType())
-                throw new ArgumentException("Type mismatch!");
-
-            int offset;
-            Deserialize(state._binState, out offset);
-        }
-
-        /// <summary>
-        /// this method is used to deserialize the randomizer from its binary state, binState size is BinaryStateSize
-        /// </summary>
-        /// <remarks>
-        /// call base.Deserialize first when overriding this method and use the nextOffset to read custom data
-        /// </remarks>
-        protected internal virtual void Deserialize(byte[] binState, out int nextOffset)
-        {
-            if (binState == null)
-                throw new ArgumentNullException("empty state should not be used to create an instance of randomizer!");
-            if (binState.Length != BinaryStateSize)
-                throw new ArgumentNullException("wrong size of the state binary data");
-
-            nextOffset = 0;
-            _inext = DeserializeInt(binState, ref nextOffset);
-            _inextp = DeserializeInt(binState, ref nextOffset);
-
-            Buffer.BlockCopy(binState, nextOffset, _seedArray, 0, 4 * _seedArray.Length);
-            nextOffset += 4 * _seedArray.Length;
-        }
-
-        /// <summary>
-        /// helper method to serialize int field
-        /// </summary>
-        protected static void SerializeInt(int val, byte[] buf, ref int offset)
-        {
-            uint uval = unchecked((uint)val);
-            buf[offset++] = (byte)((uval & 0x000000FF));
-            buf[offset++] = (byte)((uval & 0x0000FF00) >> 8);
-            buf[offset++] = (byte)((uval & 0x00FF0000) >> 16);
-            buf[offset++] = (byte)((uval & 0xFF000000) >> 24);
-        }
-
-        /// <summary>
-        /// helper method to deserialize int field
-        /// </summary>
-        protected static int DeserializeInt(byte[] buf, ref int offset)
-        {
-            uint uval = 0;
-            uval |= (uint)(0X000000FF & buf[offset++]);
-            uval |= (uint)(0X0000FF00 & (buf[offset++] << 8));
-            uval |= (uint)(0X00FF0000 & (buf[offset++] << 16));
-            uval |= (uint)(0XFF000000 & (buf[offset++] << 24));
-            return unchecked((int)uval);
-        }
-
-
-        /// <summary>
-        /// deserialization constructor
-        /// </summary>
-        public Randomizer(StreamingContext context)
-        {
-            string base64State = GetCurrentState().ToString();
-            int offset;
-            Deserialize(Convert.FromBase64String(base64State), out offset);
-        }
-
-
-        /// <summary>
-        /// use this method to create seeds for nested randomizers out of current one
-        /// </summary>
-        public int NextSeed()
-        {
-            return Next();
-        }
-
-        #region DO NOT CHANGE BEYOND THIS POINT
-        // The code below was copied from https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Random.cs
-        // I copy-pasted the source instead of inheritance to get super-fast performance on state management (see State Management section above)
-        // which is 100 times faster than using Reflection. See remarks on Serialize method for more details.
-
-        //
-        // Private Constants
-        //
-        private const int MBIG = int.MaxValue;
-        private const int MSEED = 161803398;
-        private const int MZ = 0;
-
-
-        //
-        // Member Variables - make sure to update state size and update serialization code when adding more members
-        //
-        private const int BinaryStateSizeRandom = 4 + 4 + 56 * 4;
-        private int _inext;
-        private int _inextp;
-        private int[] _seedArray = new int[56];
-
-        //
-        // Public Constants
-        //
-
-        //
-        // Native Declarations
-        //
-
-        //
-        // Constructors
-        //
-
-        public Randomizer()
-            : this(CreateSeed())
-        {
-        }
-
-        public Randomizer(int Seed)
-        {
-            int ii;
-            int mj, mk;
-
-            //Initialize our Seed array.
-            //This algorithm comes from Numerical Recipes in C (2nd Ed.)
-            int subtraction = (Seed == int.MinValue) ? int.MaxValue : Math.Abs(Seed);
-            mj = MSEED - subtraction;
-            _seedArray[55] = mj;
-            mk = 1;
-            for (int i = 1; i < 55; i++)
-            {  //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
-                ii = (21 * i) % 55;
-                _seedArray[ii] = mk;
-                mk = mj - mk;
-                if (mk < 0) mk += MBIG;
-                mj = _seedArray[ii];
-            }
-            for (int k = 1; k < 5; k++)
-            {
-                for (int i = 1; i < 56; i++)
-                {
-                    _seedArray[i] -= _seedArray[1 + (i + 30) % 55];
-                    if (_seedArray[i] < 0) _seedArray[i] += MBIG;
-                }
-            }
-            _inext = 0;
-            _inextp = 21;
-            Seed = 1;
-        }
-
-        //
-        // Package Private Methods
-        //
-
-        /*====================================Sample====================================
-        **Action: Return a new random number [0..1) and reSeed the Seed array.
-        **Returns: A double [0..1)
-        **Arguments: None
-        **Exceptions: None
-        ==============================================================================*/
-        protected virtual double Sample()
-        {
-            //Including this division at the end gives us significantly improved
-            //random number distribution.
-            return (InternalSample() * (1.0 / MBIG));
-        }
-
-        private int InternalSample()
-        {
-            int retVal;
-            int locINext = _inext;
-            int locINextp = _inextp;
-
-            if (++locINext >= 56) locINext = 1;
-            if (++locINextp >= 56) locINextp = 1;
-
-            retVal = _seedArray[locINext] - _seedArray[locINextp];
-
-            if (retVal == MBIG) retVal--;
-            if (retVal < 0) retVal += MBIG;
-
-            _seedArray[locINext] = retVal;
-
-            _inext = locINext;
-            _inextp = locINextp;
-
-            return retVal;
-        }
-
-        //
-        // Public Instance Methods
-        //
-
-
-        /*=====================================Next=====================================
-        **Returns: An int [0..int.MaxValue)
-        **Arguments: None
-        **Exceptions: None.
-        ==============================================================================*/
-        public virtual int Next()
-        {
-            return InternalSample();
-        }
-
-        private double GetSampleForLargeRange()
-        {
-            // The distribution of double value returned by Sample
-            // is not distributed well enough for a large range.
-            // If we use Sample for a range [int.MinValue..int.MaxValue)
-            // We will end up getting even numbers only.
-
-            int result = InternalSample();
-            // Note we can't use addition here. The distribution will be bad if we do that.
-            bool negative = (InternalSample() % 2 == 0) ? true : false;  // decide the sign based on second sample
-            if (negative)
-            {
-                result = -result;
-            }
-            double d = result;
-            d += (int.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
-            d /= 2 * (uint)int.MaxValue - 1;
-            return d;
-        }
-
-
-        /*=====================================Next=====================================
-        **Returns: An int [minvalue..maxvalue)
-        **Arguments: minValue -- the least legal value for the Random number.
-        **           maxValue -- One greater than the greatest legal return value.
-        **Exceptions: None.
-        ==============================================================================*/
-        public virtual int Next(int minValue, int maxValue)
-        {
-            if (minValue > maxValue)
-            {
-                throw new ArgumentOutOfRangeException("minValue > maxValue");
-            }
-
-            long range = (long)maxValue - minValue;
-            if (range <= (long)int.MaxValue)
-            {
-                return ((int)(Sample() * range) + minValue);
-            }
-            else
-            {
-                return (int)((long)(GetSampleForLargeRange() * range) + minValue);
-            }
-        }
-
-
-        /*=====================================Next=====================================
-        **Returns: An int [0..maxValue)
-        **Arguments: maxValue -- One more than the greatest legal return value.
-        **Exceptions: None.
-        ==============================================================================*/
-        public virtual int Next(int maxValue)
-        {
-            if (maxValue < 0)
-            {
-                throw new ArgumentOutOfRangeException("maxValue < 0");
-            }
-            return (int)(Sample() * maxValue);
-        }
-
-
-        /*=====================================Next=====================================
-        **Returns: A double [0..1)
-        **Arguments: None
-        **Exceptions: None
-        ==============================================================================*/
-        public virtual double NextDouble()
-        {
-            return Sample();
-        }
-
-
-        /*==================================NextBytes===================================
-        **Action:  Fills the byte array with random bytes [0..0x7f].  The entire array is filled.
-        **Returns:Void
-        **Arguments:  buffer -- the array to be filled.
-        **Exceptions: None
-        ==============================================================================*/
-        public virtual void NextBytes(byte[] buffer)
-        {
-            if (buffer == null) throw new ArgumentNullException(nameof(buffer));
-            for (int i = 0; i < buffer.Length; i++)
-            {
-                buffer[i] = (byte)(InternalSample() % (byte.MaxValue + 1));
-            }
-        }
-
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/RandomizerPool.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/RandomizerPool.cs
deleted file mode 100644 (file)
index abadc0d..0000000
+++ /dev/null
@@ -1,365 +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.Collections.Generic;
-using System.Threading;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// Enables test app to run in dual mode: regular and repro. Typical usage pattern is:
-    ///
-    /// RandomizerPool pool = new RandomizerPool(ReproFile); // for repro
-    /// RandomizerPool pool = new RandomizerPool(seed); // for deterministic generation with constant seed (useful for unit tests or perf tests)
-    /// RandomizerPool pool = new RandomizerPool(); // for generation with random seeds (for stress tests)
-    ///
-    /// try
-    /// {
-    ///     for (outer test loop counter)
-    ///     {
-    ///         using (Scope rootScope = pool.RootScope())
-    ///         {
-    ///             GlobalSetup(rootScope.Current);
-    ///
-    ///             if pool.ReproMode, set loop counter to 1
-    ///             foreach (inner test loop counter)
-    ///             {
-    ///                 using (Scope localScope = rootScope.NewScope())
-    ///                 {
-    ///                     RunLocalSetup(localScope.Current);
-    ///
-    ///                     foreach (inner test loop counter)
-    ///                     {
-    ///                         using (Scope testCaseScope = localScope.NewScope())
-    ///                         {
-    ///                             RunIteration(testCaseScope.Current);
-    ///                         }
-    ///                     }
-    ///                 }
-    ///             }
-    ///         }
-    ///     }
-    /// }
-    /// catch (Exception)
-    /// {
-    ///     string tempFile = Path.GetRandomFileName() + ".repro"; // or any other place to place repro files
-    ///     // dumps the latest scope created on the current thread to the file
-    ///     pool.SaveLastThreadScopeRepro(tempFile)
-    /// }
-    /// </summary>
-    public sealed class RandomizerPool
-    {
-        /// <summary>
-        /// holds repro states captured from repro file or null in case of regular test run
-        /// </summary>
-        private readonly Randomizer.State[] _reproStates;
-
-        /// <summary>
-        /// this seed is used create root scope randomizer objects, it increments every use
-        /// </summary>
-        /// <remarks>use Interlocked methods to access this instance to ensure multi-threading safety</remarks>
-        private int _rootScopeNextSeed;
-
-        /// <summary>
-        /// indication whether to use random seeds for root scopes or fixed ones
-        /// </summary>
-        private readonly bool _rootScopeNextSeedUsed;
-
-        /// <summary>
-        /// generates next root scope seed
-        /// </summary>
-        private int NextRootSeed()
-        {
-            // at least one repro state must present in repro file
-            // thus, root scopes will be generated the first state, and not with seed
-            if (_reproStates != null)
-                throw new InvalidOperationException("");
-
-            if (_rootScopeNextSeedUsed)
-                return Interlocked.Increment(ref _rootScopeNextSeed);
-            else
-                return Randomizer.CreateSeed();
-        }
-
-        /// <summary>
-        /// creates randomizer pool with random seeds, useful for stress testing
-        /// </summary>
-        public RandomizerPool()
-        {
-            _reproStates = null;
-            _rootScopeNextSeedUsed = false;
-        }
-
-        /// <summary>
-        /// creates randomizer pool with fixed master seed, use it to make the test run deterministic
-        /// </summary>
-        public RandomizerPool(int masterSeed)
-        {
-            _reproStates = null;
-            _rootScopeNextSeed = masterSeed;
-            _rootScopeNextSeedUsed = true;
-        }
-
-        /// <summary>
-        /// create randomizer pool from repro file
-        /// </summary>
-        public RandomizerPool(string reproFile)
-        {
-            if (string.IsNullOrEmpty(reproFile))
-                throw new ArgumentNullException("Invalid repro file");
-
-            _rootScopeNextSeedUsed = false;
-
-            using (StreamReader reproStream = new StreamReader(new FileStream(reproFile, FileMode.Open)))
-            {
-                _reproStates = LoadFromStream(reproStream);
-            }
-        }
-
-
-        /// <summary>
-        /// helper method to load repro states from stream
-        /// </summary>
-        private static Randomizer.State[] LoadFromStream(StreamReader reproStream)
-        {
-            var reproStack = new List<Randomizer.State>();
-
-            string reproStateStr = reproStream.ReadLine();
-            do
-            {
-                Randomizer.State state = Randomizer.State.Parse(reproStateStr);
-                reproStack.Add(state);
-                reproStateStr = reproStream.ReadLine();
-            } while (reproStateStr != null);
-
-            return reproStack.ToArray();
-        }
-
-        /// <summary>
-        /// Indicator whether the pool is running in repro mode.
-        /// </summary>
-        public bool ReproMode
-        {
-            get
-            {
-                return _reproStates != null;
-            }
-        }
-
-        /// <summary>
-        /// Create the root scope of the randomizer, this method is thread safe!
-        /// Note that scopes themselves are NOT thread-safe, while the pool is.
-        /// </summary>
-        public Scope<RandomizerType> RootScope<RandomizerType>()
-            where RandomizerType : Randomizer, new()
-        {
-            return new Scope<RandomizerType>(this, null);
-        }
-
-        /// <summary>
-        /// helper method called from the scope c-tor to construct the new scope
-        /// </summary>
-        private void CreateScopeRandomizer<RandomizerType>(IScope parentScope, out Randomizer.State[] scopeStates, out RandomizerType current)
-            where RandomizerType : Randomizer, new()
-        {
-            Randomizer.State[] parentStates = parentScope != null ? parentScope.GetStates() : null;
-            int newLength = parentStates != null ? parentStates.Length + 1 : 1;
-
-            scopeStates = new Randomizer.State[newLength];
-            if (parentStates != null)
-            {
-                // clone the states from the parent scope first. Note that it creates shallow copy of the state only.
-                // this is OK since Randomizer.State is immutable
-                Array.Copy(parentStates, scopeStates, newLength - 1);
-            }
-
-            // select the randomizer and state for the new scope
-            if (_reproStates != null && newLength <= _reproStates.Length)
-            {
-                // repro mode
-                Randomizer.State reproState = _reproStates[newLength - 1];
-                current = Randomizer.Create<RandomizerType>(reproState);
-                scopeStates[newLength - 1] = reproState;
-            }
-            else
-            {
-                // either generation more or repro state did not capture this depth, thus create random randomizer
-                // to make the scope generation deterministic, use the parent scope randomizer or the pool's one for roots
-                int seed;
-                if (parentScope != null)
-                {
-                    seed = parentScope.Current.NextSeed();
-                }
-                else
-                {
-                    seed = NextRootSeed();
-                }
-
-                current = Randomizer.Create<RandomizerType>(seed);
-                scopeStates[newLength - 1] = current.GetCurrentState();
-            }
-        }
-
-        /// <summary>
-        /// for internal use only - used to store the scope in arguments / local variables
-        /// </summary>
-        internal interface IScope
-        {
-            Randomizer.State[] GetStates();
-            Randomizer Current { get; }
-        }
-
-        /// <summary>
-        /// holds the last scope created on the current thread. This scope is used to generate repro file when
-        /// application crashes
-        /// </summary>
-        [ThreadStatic]
-        private static IScope t_lastCreatedScope;
-
-        /// <summary>
-        /// holds the current scope on the thread, it is used to ensure scope creation and disposal calls are balanced
-        /// </summary>
-        [ThreadStatic]
-        private static IScope t_currentScope;
-
-        /// <summary>
-        /// represents a randomizer scope, that makes use of Randomizer or derived types
-        /// </summary>
-        public class Scope<RandomizerType> : IScope, IDisposable
-            where RandomizerType : Randomizer, new()
-        {
-            private readonly RandomizerPool _pool;
-            private RandomizerType _current;
-            internal Randomizer.State[] _scopeStates;
-            private IScope _previousScope;
-
-            public RandomizerType Current
-            {
-                get
-                {
-                    if (_current == null)
-                        throw new ObjectDisposedException(GetType().FullName);
-                    return _current;
-                }
-            }
-
-            /// <summary>
-            /// Clones the random states from parent scope and generates a new one for itself.
-            /// Each time new scope is created, it is set as ts_lastCreatedScope on the current thread.
-            /// </summary>
-            internal Scope(RandomizerPool pool, IScope parent)
-            {
-                t_lastCreatedScope = this;
-                _previousScope = t_currentScope;
-                t_currentScope = this;
-                _pool = pool;
-
-                RandomizerType current;
-                _pool.CreateScopeRandomizer(parent, out _scopeStates, out current);
-
-                // mark the scope as constructed
-                _current = current;
-            }
-
-            Randomizer.State[] IScope.GetStates()
-            {
-                return _scopeStates;
-            }
-
-            Randomizer IScope.Current { get { return Current; } }
-
-            /// <summary>
-            /// Disposes the scope and reverts the current thread scope to previous one.
-            /// Note that the "last created scope" is not changed on Dispose, thus the scope instance
-            /// itself can still be used to collect repro states.
-            /// </summary>
-            public void Dispose()
-            {
-                if (_current != null)
-                {
-                    _current = null;
-
-                    if (t_currentScope != this)
-                    {
-                        // every creation of scope in test must be balanced with Dispose call, use 'using' to enforce that!
-                        // nested scopes are allowed, child scope must be disposed before the parent one
-                        throw new InvalidOperationException("Unbalanced call to scope.Dispose");
-                    }
-
-                    t_currentScope = _previousScope;
-                }
-            }
-
-            /// <summary>
-            /// creates a new scope with Randomizer type or derived
-            /// </summary>
-            /// <returns></returns>
-            public Scope<NestedRandomizerType> NewScope<NestedRandomizerType>()
-                where NestedRandomizerType : Randomizer, new()
-            {
-                IScope newScope;
-
-                if (typeof(NestedRandomizerType) == typeof(Randomizer))
-                    newScope = new Scope(_pool, this); // to ensure later casting works fine
-                else
-                    newScope = new Scope<NestedRandomizerType>(_pool, this);
-
-                return (Scope<NestedRandomizerType>)newScope;
-            }
-
-            /// <summary>
-            /// shortcut to create Scope with Randomizer type
-            /// </summary>
-            /// <returns></returns>
-            public Scope NewScope()
-            {
-                return new Scope(_pool, this);
-            }
-        }
-
-        /// <summary>
-        /// wrapping class for Scope that creates random instances using the Randomizer type itself
-        /// </summary>
-        public class Scope : Scope<Randomizer>
-        {
-            internal Scope(RandomizerPool pool, IScope parent)
-                : base(pool, parent)
-            { }
-        }
-
-        /// <summary>
-        /// helper method to dump scope information to the file
-        /// </summary>
-        private void SaveReproInternal(string reproFile, IScope scope)
-        {
-            Randomizer.State[] states = scope.GetStates();
-            using (StreamWriter reproStream = new StreamWriter(new FileStream(reproFile, FileMode.OpenOrCreate)))
-            {
-                for (int i = 0; i < states.Length; i++)
-                {
-                    // dump the scope as string
-                    reproStream.WriteLine(states[i].ToString());
-                }
-            }
-        }
-
-        /// <summary>
-        /// saves the repro data for specific scope
-        /// </summary>
-        public void SaveRepro<RandomizerType>(string reproFile, Scope<RandomizerType> scope)
-            where RandomizerType : Randomizer, new()
-        {
-            SaveReproInternal(reproFile, scope);
-        }
-
-        /// <summary>
-        /// save the repro data for the last scope created on the current thread.
-        /// </summary>
-        public void SaveLastThreadScopeRepro(string reproFile)
-        {
-            SaveReproInternal(reproFile, t_lastCreatedScope);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomColumnOptions.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomColumnOptions.cs
deleted file mode 100644 (file)
index 3edbc73..0000000
+++ /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.Data.SqlClient.ManualTesting.Tests
-{
-    [Flags]
-    public enum SqlRandomColumnOptions
-    {
-        None = 0,
-        Sparse = 0x1,
-        ColumnSet = 0x2, // should not be used with Sparse
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTable.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTable.cs
deleted file mode 100644 (file)
index 2ea7160..0000000
+++ /dev/null
@@ -1,781 +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.Collections;
-using System.Collections.Generic;
-using System.Text;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// represents table with random column types and values in it
-    /// </summary>
-    public class SqlRandomTable
-    {
-        // "Row-Overflow Data Exceeding 8 KB"
-        private const int MaxBytesPerRow = 8060;
-        // however, with sparse columns the limit drops to 8018
-        private const int MaxBytesPerRowWithSparse = 8018;
-
-        // SQL Server uses 6 bytes per-row to store row info (null-bitmap overhead is calculated based on column size)
-        private const int ConstantOverhead = 6;
-
-        // SQL does not allow table creation with more than 1024 non-sparse columns
-        private const int MaxNonSparseColumns = 1024;
-
-        // cannot send more than 2100 parameters in one command
-        private const int MaxParameterCount = 2100;
-
-        /// <summary>
-        /// column types
-        /// </summary>
-        private readonly SqlRandomTableColumn[] _columns;
-        private readonly string[] _columnNames;
-
-        public readonly IList<SqlRandomTableColumn> Columns;
-        public readonly IList<string> ColumnNames;
-        public readonly int? PrimaryKeyColumnIndex;
-        public readonly bool HasSparseColumns;
-        public readonly double NonSparseValuesTotalSize;
-
-        /// <summary>
-        /// maximum size of the row allowed for this column (depends if it has sparse columns or not)
-        /// </summary>
-        public int MaxRowSize
-        {
-            get
-            {
-                if (HasSparseColumns)
-                    return MaxBytesPerRowWithSparse;
-                else
-                    return MaxBytesPerRow;
-            }
-        }
-
-        /// <summary>
-        /// rows and their values
-        /// </summary>
-        private readonly List<object[]> _rows;
-
-        public IList<object> this[int row]
-        {
-            get
-            {
-                return new List<object>(_rows[row]).AsReadOnly();
-            }
-        }
-
-        public SqlRandomTable(SqlRandomTableColumn[] columns, int? primaryKeyColumnIndex = null, int estimatedRowCount = 0)
-        {
-            if (columns == null || columns.Length == 0)
-                throw new ArgumentException("non-empty type array is required");
-            if (estimatedRowCount < 0)
-                throw new ArgumentOutOfRangeException("non-negative row count is required, use 0 for default");
-            if (primaryKeyColumnIndex.HasValue && (primaryKeyColumnIndex.Value < 0 || primaryKeyColumnIndex.Value >= columns.Length))
-                throw new ArgumentOutOfRangeException("primaryColumnIndex");
-
-            PrimaryKeyColumnIndex = primaryKeyColumnIndex;
-            _columns = (SqlRandomTableColumn[])columns.Clone();
-            _columnNames = new string[columns.Length];
-            if (estimatedRowCount == 0)
-                _rows = new List<object[]>();
-            else
-                _rows = new List<object[]>(estimatedRowCount);
-
-            Columns = new List<SqlRandomTableColumn>(_columns).AsReadOnly();
-            ColumnNames = new List<string>(_columnNames).AsReadOnly();
-            bool hasSparse = false;
-            double totalNonSparse = 0;
-            foreach (var c in _columns)
-            {
-                if (c.IsSparse)
-                {
-                    hasSparse = true;
-                }
-                else
-                {
-                    totalNonSparse += c.GetInRowSize(null); // for non-sparse columns size does not depend on the value
-                }
-            }
-            HasSparseColumns = hasSparse;
-            NonSparseValuesTotalSize = totalNonSparse;
-        }
-
-        public string GetColumnName(int c)
-        {
-            if (_columnNames[c] == null)
-            {
-                AutoGenerateColumnNames();
-            }
-
-            return _columnNames[c];
-        }
-
-        public string GetColumnTSqlType(int c)
-        {
-            return _columns[c].GetTSqlTypeDefinition();
-        }
-
-        /// <summary>
-        /// adds new row with random values, each column has 50% chance to have null value
-        /// </summary>
-        public void AddRow(SqlRandomizer rand)
-        {
-            BitArray nullBitmap = rand.NextBitmap(_columns.Length);
-            AddRow(rand, nullBitmap);
-        }
-
-        private bool IsPrimaryKey(int c)
-        {
-            return PrimaryKeyColumnIndex.HasValue && PrimaryKeyColumnIndex.Value == c;
-        }
-
-        /// <summary>
-        /// adds a new row with random values and specified null bitmap
-        /// </summary>
-        public void AddRow(SqlRandomizer rand, BitArray nullBitmap)
-        {
-            object[] row = new object[_columns.Length];
-
-            // non-sparse columns will always take fixed size, must add them now
-            double rowSize = NonSparseValuesTotalSize;
-            double maxRowSize = MaxRowSize;
-
-            if (PrimaryKeyColumnIndex.HasValue)
-            {
-                // make sure pkey is set first
-                // ignore the null bitmap in this case
-                object pkeyValue = _rows.Count;
-                row[PrimaryKeyColumnIndex.Value] = pkeyValue;
-            }
-
-            for (int c = 0; c < row.Length; c++)
-            {
-                if (IsPrimaryKey(c))
-                {
-                    // handled above
-                    continue;
-                }
-
-                if (SkipOnInsert(c))
-                {
-                    row[c] = null; // this null value should not be used, assert triggered if it is
-                }
-                else if (rowSize >= maxRowSize)
-                {
-                    // reached the limit, cannot add more for this row
-                    row[c] = DBNull.Value;
-                }
-                else if (nullBitmap[c])
-                {
-                    row[c] = DBNull.Value;
-                }
-                else
-                {
-                    object value = _columns[c].CreateRandomValue(rand);
-                    if (value == null || value == DBNull.Value)
-                    {
-                        row[c] = DBNull.Value;
-                    }
-                    else if (IsSparse(c))
-                    {
-                        // check if the value fits
-                        double newRowSize = rowSize + _columns[c].GetInRowSize(value);
-                        if (newRowSize > maxRowSize)
-                        {
-                            // cannot fit it, zero this one and try to fit next column
-                            row[c] = DBNull.Value;
-                        }
-                        else
-                        {
-                            // the value is OK, keep it
-                            row[c] = value;
-                            rowSize = newRowSize;
-                        }
-                    }
-                    else
-                    {
-                        // non-sparse values are already counted in NonSparseValuesTotalSize
-                        row[c] = value;
-                    }
-                }
-            }
-
-            _rows.Add(row);
-        }
-
-        public void AddRows(SqlRandomizer rand, int rowCount)
-        {
-            for (int i = 0; i < rowCount; i++)
-                AddRow(rand);
-        }
-
-        public string GenerateCreateTableTSql(string tableName)
-        {
-            StringBuilder tsql = new StringBuilder();
-
-            tsql.AppendFormat("CREATE TABLE {0} (", tableName);
-
-            for (int c = 0; c < _columns.Length; c++)
-            {
-                if (c != 0)
-                    tsql.Append(", ");
-
-                tsql.AppendFormat("[{0}] {1}", GetColumnName(c), GetColumnTSqlType(c));
-                if (IsPrimaryKey(c))
-                {
-                    tsql.Append(" PRIMARY KEY");
-                }
-                else if (IsSparse(c))
-                {
-                    tsql.Append(" SPARSE NULL");
-                }
-                else if (IsColumnSet(c))
-                {
-                    tsql.Append(" COLUMN_SET FOR ALL_SPARSE_COLUMNS NULL");
-                }
-                else
-                {
-                    tsql.Append(" NULL");
-                }
-            }
-
-            tsql.AppendFormat(") ON [PRIMARY]");
-
-            return tsql.ToString();
-        }
-
-        public void DumpColumnsInfo(TextWriter output)
-        {
-            for (int i = 0; i < _columnNames.Length - 1; i++)
-            {
-                output.Write(_columnNames[i]);
-                if (_columns[i].StorageSize.HasValue)
-                    output.Write(",  [StorageSize={0}]", _columns[i].StorageSize.Value);
-                if (_columns[i].Precision.HasValue)
-                    output.Write(",  [Precision={0}]", _columns[i].Precision.Value);
-                if (_columns[i].Scale.HasValue)
-                    output.Write(",  [Scale={0}]", _columns[i].Scale.Value);
-                output.WriteLine();
-            }
-        }
-
-        public void DumpRow(TextWriter output, object[] row)
-        {
-            if (row == null || row.Length != _columns.Length)
-                throw new ArgumentException("Row length does not match the columns");
-
-            for (int i = 0; i < _columnNames.Length - 1; i++)
-            {
-                object val = row[i];
-                string type;
-                if (val == null)
-                {
-                    val = "<dbnull>";
-                    type = "";
-                }
-                else
-                {
-                    type = val.GetType().Name;
-                    if (val is Array)
-                    {
-                        val = string.Format("[Length={0}]", ((Array)val).Length);
-                    }
-                    else if (val is string)
-                    {
-                        val = string.Format("[Length={0}]", ((string)val).Length);
-                    }
-                    else
-                    {
-                        val = string.Format("[{0}]", val);
-                    }
-                }
-
-                output.WriteLine("[{0}] = {1}", _columnNames[i], val);
-            }
-        }
-
-        private bool SkipOnInsert(int c)
-        {
-            if (_columns[c].Type == SqlDbType.Timestamp)
-            {
-                // cannot insert timestamp
-                return true;
-            }
-
-            if (IsColumnSet(c))
-            {
-                // skip column set, using sparse columns themselves
-                return true;
-            }
-
-            // OK to insert value
-            return false;
-        }
-
-        public void GenerateTableOnServer(SqlConnection con, string tableName)
-        {
-            // create table
-            SqlCommand cmd = con.CreateCommand();
-            cmd.CommandType = CommandType.Text;
-            cmd.CommandText = GenerateCreateTableTSql(tableName);
-
-            cmd.ExecuteNonQuery();
-
-            InsertRows(con, tableName, 0, _rows.Count);
-        }
-
-        public void InsertRows(SqlConnection con, string tableName, int rowFrom, int rowToExclusive)
-        {
-            if (con == null || tableName == null)
-            {
-                throw new ArgumentNullException("connection and table name must be valid");
-            }
-
-            if (rowToExclusive > _rows.Count)
-            {
-                throw new ArgumentOutOfRangeException("rowToExclusive", rowToExclusive, "cannot be greater than the row count");
-            }
-
-            if (rowFrom < 0 || rowFrom > rowToExclusive)
-            {
-                throw new ArgumentOutOfRangeException("rowFrom", rowFrom, "cannot be less than 0 or greater than rowToExclusive");
-            }
-
-            SqlCommand cmd = null;
-            SqlParameter[] parameters = null;
-            for (int r = rowFrom; r < rowToExclusive; r++)
-            {
-                InsertRowInternal(con, ref cmd, ref parameters, tableName, r);
-            }
-        }
-
-        public void InsertRow(SqlConnection con, string tableName, int row)
-        {
-            if (con == null || tableName == null)
-            {
-                throw new ArgumentNullException("connection and table name must be valid");
-            }
-
-            if (row < 0 || row >= _rows.Count)
-            {
-                throw new ArgumentOutOfRangeException("row", row, "cannot be less than 0 or greater than or equal to row count");
-            }
-
-            SqlCommand cmd = null;
-            SqlParameter[] parameters = null;
-            InsertRowInternal(con, ref cmd, ref parameters, tableName, row);
-        }
-
-        private void InsertRowInternal(SqlConnection con, ref SqlCommand cmd, ref SqlParameter[] parameters, string tableName, int row)
-        {
-            // cannot use DataTable: it does not handle well char[] values and variant and also does not support sparse/column set ones
-            StringBuilder columnsText = new StringBuilder();
-            StringBuilder valuesText = new StringBuilder();
-
-            // create the command and parameters on first call, reuse afterwards (to reduces table creation overhead)
-            if (cmd == null)
-            {
-                cmd = con.CreateCommand();
-                cmd.CommandType = CommandType.Text;
-            }
-            else
-            {
-                // need to unbind existing parameters and re-add the next set of values
-                cmd.Parameters.Clear();
-            }
-
-            if (parameters == null)
-            {
-                parameters = new SqlParameter[_columns.Length];
-            }
-
-            object[] rowValues = _rows[row];
-
-            // there is a limit of parameters to be sent (2010)
-            for (int ci = 0; ci < _columns.Length; ci++)
-            {
-                if (cmd.Parameters.Count >= MaxParameterCount)
-                {
-                    // reached the limit of max parameters, cannot continue
-                    // theoretically, we could do INSERT + UPDATE. practically, chances for this to happen are almost none since nulls are skipped
-                    rowValues[ci] = DBNull.Value;
-                    continue;
-                }
-
-                if (SkipOnInsert(ci))
-                {
-                    // cannot insert timestamp
-                    // insert of values into columnset columns are also not supported (use sparse columns themselves)
-                    continue;
-                }
-
-                bool isNull = (rowValues[ci] == DBNull.Value || rowValues[ci] == null);
-
-                if (isNull)
-                {
-                    // columns such as sparse cannot have DEFAULT constraint, thus it is safe to ignore the value of the column when inserting new row
-                    // this also significantly reduces number of columns updated during insert, to prevent "The number of target
-                    // columns that are specified in an INSERT, UPDATE, or MERGE statement exceeds the maximum of 4096."
-                    continue;
-                }
-
-                SqlParameter p = parameters[ci];
-
-                // construct column list
-                if (columnsText.Length > 0)
-                {
-                    columnsText.Append(", ");
-                    valuesText.Append(", ");
-                }
-
-                columnsText.AppendFormat("[{0}]", _columnNames[ci]);
-
-                if (p == null)
-                {
-                    p = cmd.CreateParameter();
-                    p.ParameterName = "@p" + ci;
-                    p.SqlDbType = _columns[ci].Type;
-
-                    parameters[ci] = p;
-                }
-
-                p.Value = rowValues[ci] ?? DBNull.Value;
-
-                cmd.Parameters.Add(p);
-
-                valuesText.Append(p.ParameterName);
-            }
-
-            Debug.Assert(columnsText.Length > 0, "Table that have only TIMESTAMP, ColumnSet or Sparse columns are not allowed - use primary key in this case");
-
-            cmd.CommandText = string.Format("INSERT INTO {0} ( {1} ) VALUES ( {2} )", tableName, columnsText, valuesText);
-
-            cmd.ExecuteNonQuery();
-        }
-
-        /// <summary>
-        /// generates SELECT statement; if columnIndices is null the statement will include all the columns
-        /// </summary>
-        public int GenerateSelectFromTableTSql(string tableName, StringBuilder selectBuilder, int[] columnIndices = null, int indicesOffset = -1, int indicesCount = -1)
-        {
-            if (tableName == null || selectBuilder == null)
-                throw new ArgumentNullException("tableName == null || selectBuilder == null");
-
-            int maxIndicesLength = (columnIndices == null) ? _columns.Length : columnIndices.Length;
-            if (indicesOffset == -1)
-            {
-                indicesOffset = 0;
-            }
-            else if (indicesOffset < 0 || indicesOffset >= maxIndicesLength)
-            {
-                throw new ArgumentOutOfRangeException("indicesOffset");
-            }
-
-            if (indicesCount == -1)
-            {
-                indicesCount = maxIndicesLength;
-            }
-            else if (indicesCount < 1 || (indicesCount + indicesOffset) > maxIndicesLength)
-            {
-                // at least one index required
-                throw new ArgumentOutOfRangeException("indicesCount");
-            }
-
-            double totalRowSize = 0;
-            int countAdded = 0;
-
-            // append the first
-            int columnIndex = (columnIndices == null) ? indicesOffset : columnIndices[indicesOffset];
-            selectBuilder.AppendFormat("SELECT [{0}]", _columnNames[columnIndex]);
-            totalRowSize += _columns[columnIndex].GetInRowSize(null);
-            countAdded++;
-
-            // append the rest, if any
-            int end = indicesOffset + indicesCount;
-            for (int c = indicesOffset + 1; c < end; c++)
-            {
-                columnIndex = (columnIndices == null) ? c : columnIndices[c];
-                totalRowSize += _columns[columnIndex].GetInRowSize(null);
-                if (totalRowSize > MaxRowSize)
-                {
-                    // overflow - stop now
-                    break;
-                }
-
-                selectBuilder.AppendFormat(", [{0}]", _columnNames[columnIndex]);
-                countAdded++;
-            }
-
-            selectBuilder.AppendFormat(" FROM {0}", tableName);
-
-            if (PrimaryKeyColumnIndex.HasValue)
-                selectBuilder.AppendFormat(" ORDER BY [{0}]", _columnNames[PrimaryKeyColumnIndex.Value]);
-
-            return countAdded;
-        }
-
-        #region static helper methods
-
-        private static int GetRowOverhead(int columnSize)
-        {
-            int nullBitmapSize = (columnSize + 7) / 8;
-            return ConstantOverhead + nullBitmapSize;
-        }
-
-        // once we have only this size left on the row, column set column is forced
-        // 40 is an XML and variant size
-        private static readonly int s_columnSetSafetyRange = SqlRandomTypeInfo.XmlRowUsage * 3;
-
-        /// <summary>
-        /// Creates random list of columns from the given source collection. The rules are:
-        /// * table cannot contain more than 1024 non-sparse columns
-        /// * total row size of non-sparse columns should not exceed 8060 or 8018 (with sparse)
-        /// * column set column must be added if number of columns in total exceeds 1024
-        /// </summary>
-        public static SqlRandomTableColumn[] CreateRandTypes(SqlRandomizer rand, SqlRandomTypeInfoCollection sourceCollection, int maxColumnsCount, bool createIdColumn)
-        {
-            var retColumns = new List<SqlRandomTableColumn>(maxColumnsCount);
-            bool hasTimestamp = false;
-            double totalRowSize = 0;
-            int totalRegularColumns = 0;
-
-            bool hasColumnSet = false;
-            bool hasSparseColumns = false;
-            int maxRowSize = MaxBytesPerRow; // set to MaxBytesPerRowWithSparse when sparse column is first added
-
-            int i = 0;
-            if (createIdColumn)
-            {
-                SqlRandomTypeInfo keyType = sourceCollection[SqlDbType.Int];
-                SqlRandomTableColumn keyColumn = keyType.CreateDefaultColumn(SqlRandomColumnOptions.None);
-                retColumns.Add(keyColumn);
-                totalRowSize += keyType.GetInRowSize(keyColumn, null);
-                i++;
-                totalRegularColumns++;
-            }
-
-            for (; i < maxColumnsCount; i++)
-            {
-                // select column options (sparse/column-set)
-                bool isSparse; // must be set in the if/else flow below
-                bool isColumnSet = false;
-
-                if (totalRegularColumns >= MaxNonSparseColumns)
-                {
-                    // reached the limit for regular columns
-
-                    if (!hasColumnSet)
-                    {
-                        // no column-set yet, stop unconditionally
-                        // this can happen if large char/binary value brought the row size total to a limit leaving no space for column-set
-                        break;
-                    }
-
-                    // there is a column set, enforce sparse from this point
-                    isSparse = true;
-                }
-                else if (i == (MaxNonSparseColumns - 1) && hasSparseColumns && !hasColumnSet)
-                {
-                    // we almost reached the limit of regular & sparse columns with, but no column set added
-                    // to increase chances for >1024 columns, enforce column set now
-                    isColumnSet = true;
-                    isSparse = false;
-                }
-                else if (totalRowSize > MaxBytesPerRowWithSparse)
-                {
-                    Debug.Assert(totalRowSize <= MaxBytesPerRow, "size over the max limit");
-                    Debug.Assert(!hasSparseColumns, "should not have sparse columns after MaxBytesPerRowWithSparse (check maxRowSize)");
-                    // cannot insert sparse from this point
-                    isSparse = false;
-                    isColumnSet = false;
-                }
-                else
-                {
-                    // check how close we are to the limit of the row size
-                    int sparseProbability;
-                    if (totalRowSize < 100)
-                    {
-                        sparseProbability = 2;
-                    }
-                    else if (totalRowSize < MaxBytesPerRowWithSparse / 2)
-                    {
-                        sparseProbability = 10;
-                    }
-                    else if (totalRowSize < (MaxBytesPerRowWithSparse - s_columnSetSafetyRange))
-                    {
-                        sparseProbability = 50;
-                    }
-                    else
-                    {
-                        // close to the row size limit, special case
-                        if (!hasColumnSet)
-                        {
-                            // if we have not added column set column yet
-                            // column-set is a regular column and its size counts towards row size, so time to add it
-                            isColumnSet = true;
-                            sparseProbability = -1; // not used
-                        }
-                        else
-                        {
-                            sparseProbability = 90;
-                        }
-                    }
-
-                    if (!isColumnSet)
-                    {
-                        isSparse = (rand.Next(100) < sparseProbability);
-
-                        if (!isSparse && !hasColumnSet)
-                        {
-                            // if decided to add regular column, give it a (low) chance to inject a column set at any position
-                            isColumnSet = rand.Next(100) < 1;
-                        }
-                    }
-                    else
-                    {
-                        isSparse = false;
-                    }
-                }
-
-                // select the type
-                SqlRandomTypeInfo ti;
-                SqlRandomColumnOptions options = SqlRandomColumnOptions.None;
-
-                if (isSparse)
-                {
-                    Debug.Assert(!isColumnSet, "should not have both sparse and column set flags set");
-                    ti = sourceCollection.NextSparse(rand);
-                    Debug.Assert(ti.CanBeSparseColumn, "NextSparse must return only types that can be sparse");
-                    options |= SqlRandomColumnOptions.Sparse;
-                }
-                else if (isColumnSet)
-                {
-                    Debug.Assert(!hasColumnSet, "there is already a column set, we should not set isColumnSet again above");
-                    ti = sourceCollection[SqlDbType.Xml];
-                    options |= SqlRandomColumnOptions.ColumnSet;
-                }
-                else
-                {
-                    // regular column
-                    ti = sourceCollection.Next(rand);
-
-                    if (ti.Type == SqlDbType.Timestamp)
-                    {
-                        // while table can contain single timestamp column only, there is no way to insert values into it.
-                        // thus, do not allow this
-                        if (hasTimestamp || maxColumnsCount == 1)
-                        {
-                            ti = sourceCollection[SqlDbType.Int];
-                        }
-                        else
-                        {
-                            // table cannot have two timestamp columns
-                            hasTimestamp = true;
-                        }
-                    }
-                }
-
-                SqlRandomTableColumn col = ti.CreateRandomColumn(rand, options);
-
-                if (!isSparse)
-                {
-                    double rowSize = ti.GetInRowSize(col, DBNull.Value);
-                    int overhead = GetRowOverhead(retColumns.Count + 1); // +1 for this column
-
-                    if (totalRowSize + rowSize + overhead > maxRowSize)
-                    {
-                        // cannot use this column
-                        // note that if this column is a column set column
-                        continue;
-                    }
-
-                    totalRowSize += rowSize;
-                    totalRegularColumns++;
-                }
-                // else - sparse columns are not counted towards row size when table is created (they are when inserting new row with non-null value in the sparse column)...
-
-                retColumns.Add(col);
-
-                // after adding the column, update the state
-                if (isColumnSet)
-                {
-                    hasColumnSet = true;
-                }
-
-                if (isSparse)
-                {
-                    hasSparseColumns = true;
-                    maxRowSize = MaxBytesPerRowWithSparse; // reduce the max row size
-                }
-            }
-
-            return retColumns.ToArray();
-        }
-
-        public static SqlRandomTable Create(SqlRandomizer rand, SqlRandomTypeInfoCollection sourceCollection, int maxColumnsCount, int rowCount, bool createPrimaryKeyColumn)
-        {
-            SqlRandomTableColumn[] testTypes = CreateRandTypes(rand, sourceCollection, maxColumnsCount, createPrimaryKeyColumn);
-            SqlRandomTable table = new SqlRandomTable(testTypes, primaryKeyColumnIndex: createPrimaryKeyColumn ? (Nullable<int>)0 : null, estimatedRowCount: rowCount);
-            table.AddRows(rand, rowCount);
-            return table;
-        }
-
-        private void AutoGenerateColumnNames()
-        {
-            Dictionary<string, int> nameMap = new Dictionary<string, int>(_columns.Length);
-            for (int c = 0; c < _columns.Length; c++)
-            {
-                if (_columnNames[c] == null)
-                {
-                    // pick name that is not in table yet
-                    string name = GenerateColumnName(nameMap, c);
-                    nameMap[name] = c;
-                    _columnNames[c] = name;
-                }
-                else
-                {
-                    // check for dups
-                    if (nameMap.ContainsKey(_columnNames[c]))
-                    {
-                        // should not happen now since column names are auto-generated only
-                        throw new InvalidOperationException("duplicate column names detected");
-                    }
-                }
-            }
-        }
-
-        private string GenerateColumnName(Dictionary<string, int> nameMap, int c)
-        {
-            string baseName;
-            if (IsPrimaryKey(c))
-                baseName = "PKEY";
-            else
-                baseName = string.Format("C{0}_{1}", _columns[c].Type, c);
-
-            string name = baseName;
-            int extraSuffix = 1;
-            while (nameMap.ContainsKey(name))
-            {
-                name = string.Format("{0}_{1}", baseName, extraSuffix);
-                ++extraSuffix;
-            }
-            return name;
-        }
-
-        private bool IsSparse(int c)
-        {
-            return _columns[c].IsSparse;
-        }
-
-        private bool IsColumnSet(int c)
-        {
-            return _columns[c].IsColumnSet;
-        }
-
-        #endregion static helper methods
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTableColumn.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTableColumn.cs
deleted file mode 100644 (file)
index d4021e8..0000000
+++ /dev/null
@@ -1,70 +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.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// holds an information used to create a column in SQL Server
-    /// </summary>
-    public sealed class SqlRandomTableColumn
-    {
-        public readonly SqlRandomTypeInfo TypeInfo;
-        public readonly int? StorageSize;
-        public readonly int? Precision;
-        public readonly int? Scale;
-        public readonly SqlRandomColumnOptions Options;
-
-        // useful shortcuts
-        public SqlDbType Type { get { return TypeInfo.Type; } }
-        public string GetTSqlTypeDefinition() { return TypeInfo.GetTSqlTypeDefinition(this); }
-        public object CreateRandomValue(SqlRandomizer rand) { return TypeInfo.CreateRandomValue(rand, this); }
-        public object Read(SqlDataReader reader, int ordinal, Type asType) { return TypeInfo.Read(reader, ordinal, this, asType); }
-        public bool CanCompareValues { get { return TypeInfo.CanCompareValues(this); } }
-        public bool CompareValues(object expected, object actual) { return TypeInfo.CompareValues(this, expected, actual); }
-        public string BuildErrorMessage(object expected, object actual) { return TypeInfo.BuildErrorMessage(this, expected, actual); }
-        public double GetInRowSize(object value) { return TypeInfo.GetInRowSize(this, value); }
-        public bool IsSparse { get { return (Options & SqlRandomColumnOptions.Sparse) != 0; } }
-        public bool IsColumnSet { get { return (Options & SqlRandomColumnOptions.ColumnSet) != 0; } }
-
-        public SqlRandomTableColumn(SqlRandomTypeInfo typeInfo, SqlRandomColumnOptions options)
-        {
-            if (typeInfo == null)
-            {
-                throw new ArgumentNullException(nameof(typeInfo));
-            }
-
-            if ((options & SqlRandomColumnOptions.ColumnSet) != 0)
-            {
-                if ((options & SqlRandomColumnOptions.Sparse) != 0)
-                {
-                    throw new ArgumentException("Must not be sparse", nameof(options));
-                }
-
-                if (typeInfo.Type != SqlDbType.Xml)
-                {
-                    throw new ArgumentException("columnset column must be an XML column");
-                }
-            }
-
-            TypeInfo = typeInfo;
-            Options = options;
-        }
-
-        public SqlRandomTableColumn(SqlRandomTypeInfo typeInfo, SqlRandomColumnOptions options, int? storageSize)
-            : this(typeInfo, options)
-        {
-            StorageSize = storageSize;
-            Precision = null;
-            Scale = null;
-        }
-
-        public SqlRandomTableColumn(SqlRandomTypeInfo typeInfo, SqlRandomColumnOptions options, int? precision, int? scale)
-            : this(typeInfo, options)
-        {
-            StorageSize = null;
-            Precision = precision;
-            Scale = scale;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypeInfo.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypeInfo.cs
deleted file mode 100644 (file)
index 0074148..0000000
+++ /dev/null
@@ -1,421 +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.Text;
-using System.Data.Common;
-using System.Globalization;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// represents a base class for SQL type random generation
-    /// </summary>
-    public abstract class SqlRandomTypeInfo
-    {
-        // max size on the row for large blob types to prevent row overflow, when creating the table:
-        // "Warning: The table "TestTable" has been created, but its maximum row size exceeds the allowed maximum of 8060 bytes. INSERT or UPDATE to this table will fail if the resulting row exceeds the size limit."
-        // tests show that the actual size is 36, I added 4 more bytes for extra
-        protected const int LargeVarDataRowUsage = 40; // var types
-        protected const int LargeDataRowUsage = 40; // text/ntext/image
-        protected internal const int XmlRowUsage = 40; //
-        protected const int VariantRowUsage = 40;
-
-        public readonly SqlDbType Type;
-
-        protected SqlRandomTypeInfo(SqlDbType t)
-        {
-            Type = t;
-        }
-
-        /// <summary>
-        /// true if column of this type can be created as sparse column
-        /// </summary>
-        public virtual bool CanBeSparseColumn
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-
-        /// <summary>
-        /// creates a default column instance for given type
-        /// </summary>
-        public SqlRandomTableColumn CreateDefaultColumn()
-        {
-            return CreateDefaultColumn(SqlRandomColumnOptions.None);
-        }
-
-        /// <summary>
-        /// creates a default column instance for given type
-        /// </summary>
-        public virtual SqlRandomTableColumn CreateDefaultColumn(SqlRandomColumnOptions options)
-        {
-            return new SqlRandomTableColumn(this, options);
-        }
-
-        /// <summary>
-        /// creates a column with random size/precision/scale values, where applicable.
-        /// </summary>
-        /// <remarks>this method is overridden for some types to create columns with random size/precision</remarks>
-        public virtual SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            return CreateDefaultColumn(options);
-        }
-
-        /// <summary>
-        /// helper method to check validity of input column
-        /// </summary>
-        protected void ValidateColumnInfo(SqlRandomTableColumn columnInfo)
-        {
-            if (columnInfo == null)
-                throw new ArgumentNullException(nameof(columnInfo));
-
-            if (Type != columnInfo.Type)
-                throw new ArgumentException("Type mismatch");
-        }
-
-        /// <summary>
-        /// Returns the size used by a column value within the row. This method is used when generating random table to ensure
-        /// the row size does not overflow
-        /// </summary>
-        public double GetInRowSize(SqlRandomTableColumn columnInfo, object value)
-        {
-            ValidateColumnInfo(columnInfo);
-
-            if (columnInfo.IsSparse)
-            {
-                if (value == DBNull.Value && value == null)
-                {
-                    // null values of sparse columns do not use in-row size
-                    return 0;
-                }
-                else
-                {
-                    // if sparse column has non-null value, it has an additional penalty of 4 bytes added to its storage size
-                    return 4 + GetInRowSizeInternal(columnInfo);
-                }
-            }
-            else
-            {
-                // not a sparse column
-                return GetInRowSizeInternal(columnInfo);
-            }
-        }
-
-        protected abstract double GetInRowSizeInternal(SqlRandomTableColumn columnInfo);
-
-        /// <summary>
-        /// gets TSQL definition of the column
-        /// </summary>
-        public string GetTSqlTypeDefinition(SqlRandomTableColumn columnInfo)
-        {
-            ValidateColumnInfo(columnInfo);
-            return GetTSqlTypeDefinitionInternal(columnInfo);
-        }
-
-        protected abstract string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo);
-
-        /// <summary>
-        /// creates random, but valued value for the type, based on the given column definition
-        /// </summary>
-        public object CreateRandomValue(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            ValidateColumnInfo(columnInfo);
-            return CreateRandomValueInternal(rand, columnInfo);
-        }
-
-        protected abstract object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo);
-
-        /// <summary>
-        /// helper method to read character data from the reader
-        /// </summary>
-        protected object ReadCharData(DbDataReader reader, int ordinal, Type asType)
-        {
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-
-            if (asType == typeof(string))
-                return reader.GetString(ordinal);
-            else if (asType == typeof(char[]) || asType == typeof(DBNull))
-                return reader.GetString(ordinal).ToCharArray();
-            else
-                throw new NotSupportedException("Wrong type: " + asType.FullName);
-        }
-
-        /// <summary>
-        /// helper method to read byte-array data from the reader
-        /// </summary>
-        protected object ReadByteArray(DbDataReader reader, int ordinal, Type asType)
-        {
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-
-            if (asType == typeof(byte[]) || asType == typeof(DBNull))
-                return (byte[])reader.GetValue(ordinal);
-            else
-                throw new NotSupportedException("Wrong type: " + asType.FullName);
-        }
-
-        protected bool IsNullOrDbNull(object value)
-        {
-            return DBNull.Value.Equals(value) || value == null;
-        }
-
-        /// <summary>
-        /// helper method to check that actual test value has same type as expectedType or it is dbnull.
-        /// </summary>
-        /// <param name="bothDbNull">set to true if both values are DbNull</param>
-        /// <returns>true if expected value is DbNull or has the expected type</returns>
-        protected bool CompareDbNullAndType(Type expectedType, object expected, object actual, out bool bothDbNull)
-        {
-            bool isNullExpected = IsNullOrDbNull(expected);
-            bool isNullActual = IsNullOrDbNull(actual);
-
-            bothDbNull = isNullActual && isNullExpected;
-
-            if (bothDbNull)
-                return true;
-
-            if (isNullActual || isNullExpected)
-                return false; // only one is null, but not both
-
-            if (expectedType == null)
-                return true;
-
-            // both not null
-            if (expectedType != expected.GetType())
-                throw new ArgumentException("Wrong type!");
-
-            return (expectedType == actual.GetType());
-        }
-
-        /// <summary>
-        /// helper method to compare two byte arrays
-        /// </summary>
-        /// <remarks>I considered use of Generics here, but switched to explicit typed version due to performance overhead.
-        /// When using generic version, there is no way to quickly compare two values (expected[i] == actual[i]), and using
-        /// Equals method performs boxing, increasing the time spent on this method.</remarks>
-        private bool CompareByteArray(byte[] expected, byte[] actual, bool allowIncomplete = false, byte paddingValue = 0)
-        {
-            if (expected.Length > actual.Length)
-            {
-                return false;
-            }
-            else if (!allowIncomplete && expected.Length < actual.Length)
-            {
-                return false;
-            }
-
-            // check expected array values
-            int end = expected.Length;
-            for (int i = 0; i < end; i++)
-            {
-                if (expected[i] != actual[i])
-                    return false;
-            }
-
-            // check for padding in actual values
-            end = actual.Length;
-            for (int i = expected.Length; i < end; i++)
-            {
-                // ensure rest of array are zeros
-                if (paddingValue != actual[i])
-                {
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// helper method to compare two char arrays
-        /// </summary>
-        /// <remarks>I considered use of Generics here, but switched to explicit typed version due to performance overhead.
-        /// When using generic version, there is no way to quickly compare two values (expected[i] == actual[i]), and using
-        /// Equals method performs boxing, increasing the time spent on this method.</remarks>
-        private bool CompareCharArray(char[] expected, char[] actual, bool allowIncomplete = false, char paddingValue = ' ')
-        {
-            if (expected.Length > actual.Length)
-            {
-                return false;
-            }
-            else if (!allowIncomplete && expected.Length < actual.Length)
-            {
-                return false;
-            }
-
-            // check expected array values
-            int end = expected.Length;
-            for (int i = 0; i < end; i++)
-            {
-                if (expected[i] != actual[i])
-                    return false;
-            }
-
-            // check for padding in actual values
-            end = actual.Length;
-            for (int i = expected.Length; i < end; i++)
-            {
-                // ensure rest of array are zeros
-                if (paddingValue != actual[i])
-                {
-                    return false;
-                }
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// helper method to compare two non-array values.
-        /// </summary>
-        protected bool CompareValues<T>(object expected, object actual) where T : struct
-        {
-            bool bothDbNull;
-            if (!CompareDbNullAndType(typeof(T), expected, actual, out bothDbNull) || bothDbNull)
-                return bothDbNull;
-
-            return expected.Equals(actual);
-        }
-
-
-        /// <summary>
-        /// validates that the actual value is DbNull or byte array and compares it to expected
-        /// </summary>
-        protected bool CompareByteArray(object expected, object actual, bool allowIncomplete, byte paddingValue = 0)
-        {
-            bool bothDbNull;
-            if (!CompareDbNullAndType(typeof(byte[]), expected, actual, out bothDbNull) || bothDbNull)
-                return bothDbNull;
-            return CompareByteArray((byte[])expected, (byte[])actual, allowIncomplete, paddingValue);
-        }
-
-        /// <summary>
-        /// validates that the actual value is DbNull or char array and compares it to expected
-        /// </summary>
-        protected bool CompareCharArray(object expected, object actual, bool allowIncomplete, char paddingValue = ' ')
-        {
-            bool bothDbNull;
-            if (!CompareDbNullAndType(typeof(char[]), expected, actual, out bothDbNull) || bothDbNull)
-                return bothDbNull;
-            return CompareCharArray((char[])expected, (char[])actual, allowIncomplete, paddingValue);
-        }
-
-        /// <summary>
-        /// helper method to reads datetime from the reader
-        /// </summary>
-        protected object ReadDateTime(DbDataReader reader, int ordinal, Type asType)
-        {
-            ValidateReadType(typeof(DateTime), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetDateTime(ordinal);
-        }
-
-        protected void ValidateReadType(Type expectedType, Type readAsType)
-        {
-            if (readAsType != expectedType && readAsType != typeof(DBNull))
-                throw new ArgumentException("Wrong type: " + readAsType.FullName);
-        }
-
-        /// <summary>
-        /// this method is called to read the value from the data reader
-        /// </summary>
-        public object Read(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            if (reader == null || asType == null)
-                throw new ArgumentNullException("reader == null || asType == null");
-            ValidateColumnInfo(columnInfo);
-            return ReadInternal(reader, ordinal, columnInfo, asType);
-        }
-
-        protected abstract object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType);
-
-        /// <summary>
-        /// used to check if this column can be compared; returns true by default (timestamp and column set columns return false)
-        /// </summary>
-        public virtual bool CanCompareValues(SqlRandomTableColumn columnInfo)
-        {
-            return true;
-        }
-
-        /// <summary>
-        /// This method is called to compare the actual value read to expected. Expected value must be either dbnull or from the given type.
-        /// Actual value can be any.
-        /// </summary>
-        public bool CompareValues(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            ValidateColumnInfo(columnInfo);
-            return CompareValuesInternal(columnInfo, expected, actual);
-        }
-
-        protected abstract bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual);
-
-        public string BuildErrorMessage(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            ValidateColumnInfo(columnInfo);
-
-            string expectedAsString = IsNullOrDbNull(expected) ? "null" : "\"" + ValueAsString(columnInfo, expected) + "\"";
-            string actualAsString = IsNullOrDbNull(actual) ? "null" : "\"" + ValueAsString(columnInfo, actual) + "\"";
-
-            return string.Format(CultureInfo.InvariantCulture,
-                "  Column type: {0}\n" +
-                "  Expected value: {1}\n" +
-                "  Actual value: {2}",
-                GetTSqlTypeDefinition(columnInfo),
-                expectedAsString,
-                actualAsString);
-        }
-
-        /// <summary>
-        /// using ToString by default, supports arrays and many primitives;
-        /// override as needed
-        /// </summary>
-        /// <param name="value">value is not null or dbnull(validated before)</param>
-        protected virtual string ValueAsString(SqlRandomTableColumn columnInfo, object value)
-        {
-            Array a = value as Array;
-            if (a == null)
-            {
-                return string.Format(CultureInfo.InvariantCulture, "{0}: {1}", value.GetType().Name, PrimitiveValueAsString(value));
-            }
-            else
-            {
-                StringBuilder sb = new StringBuilder();
-                sb.AppendFormat("{0}[{1}]", value.GetType().Name, a.Length);
-                if (a.Length > 0)
-                {
-                    sb.Append(":");
-                    for (int i = 0; i < a.Length; i++)
-                    {
-                        sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", PrimitiveValueAsString(a.GetValue(i)));
-                    }
-                }
-
-                return sb.ToString();
-            }
-        }
-
-        public string PrimitiveValueAsString(object value)
-        {
-            if (value is char)
-            {
-                int c = (int)(char)value; // double-cast is needed from object
-                return c.ToString("X4", CultureInfo.InvariantCulture);
-            }
-            else if (value is byte)
-            {
-                byte b = (byte)value;
-                return b.ToString("X2", CultureInfo.InvariantCulture);
-            }
-            else
-            {
-                return string.Format(CultureInfo.InvariantCulture, "{0}", value.ToString());
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypeInfoCollection.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypeInfoCollection.cs
deleted file mode 100644 (file)
index 32369df..0000000
+++ /dev/null
@@ -1,186 +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.Linq;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// Defines a collection of types to be used by the test. Tests can start with CreateSql2005Collection or
-    /// CreateSql2008Collection and add/remove types, as needed.
-    /// </summary>
-    public sealed class SqlRandomTypeInfoCollection : System.Collections.ObjectModel.KeyedCollection<SqlDbType, SqlRandomTypeInfo>
-    {
-        private static readonly SqlRandomTypeInfo[] s_sql2005Types =
-        {
-            // var types
-            new SqlVarBinaryTypeInfo(),
-            new SqlVarCharTypeInfo(),
-            new SqlNVarCharTypeInfo(),
-
-            // integer data types
-            new SqlBigIntTypeInfo(),
-            new SqlIntTypeInfo(),
-            new SqlSmallIntTypeInfo(),
-            new SqlTinyIntTypeInfo(),
-
-            // fixed length blobs
-            new SqlCharTypeInfo(),
-            new SqlNCharTypeInfo(),
-            new SqlBinaryTypeInfo(),
-
-            // large blobs
-            new SqlTextTypeInfo(),
-            new SqlNTextTypeInfo(),
-            new SqlImageTypeInfo(),
-
-            // bit
-            new SqlBitTypeInfo(),
-
-            // decimal
-            new SqlDecimalTypeInfo(),
-
-            // money types
-            new SqlMoneyTypeInfo(),
-            new SqlSmallMoneyTypeInfo(),
-
-            // float types
-            new SqRealTypeInfo(),
-            new SqFloatTypeInfo(),
-
-            // typestamp (== rowversion)
-            new SqlRowVersionTypeInfo(),
-
-            // unique identifier (== guid)
-            new SqlUniqueIdentifierTypeInfo(),
-
-            // date/time types
-            new SqlDateTimeTypeInfo(),
-            new SqlSmallDateTimeTypeInfo(),
-
-            // variant
-            new SqlVariantTypeInfo(),
-
-            // xml
-            new SqlXmlTypeInfo(),
-        };
-
-        // types added in SQL 2008
-        private static readonly SqlRandomTypeInfo[] s_newInSql2008Types =
-        {
-            // date/time types
-            new SqlDateTypeInfo(),
-            new SqlDateTime2TypeInfo(),
-            new SqlDateTimeOffsetTypeInfo(),
-            new SqlTimeTypeInfo(),
-        };
-
-        // reset it each time collection is modified
-        private IList<SqlRandomTypeInfo> _sparseColumns = null;
-
-        public IList<SqlRandomTypeInfo> SparseColumns
-        {
-            get
-            {
-                if (_sparseColumns == null)
-                {
-                    // rebuild it
-                    var sparseColumns = this.Where(t => t.CanBeSparseColumn).ToArray();
-                    _sparseColumns = new ReadOnlyCollection<SqlRandomTypeInfo>(sparseColumns);
-                }
-
-                return _sparseColumns;
-            }
-        }
-
-        public SqlRandomTypeInfoCollection(params SqlRandomTypeInfo[] typeSet1)
-            : this(typeSet1, null)
-        { }
-
-        protected override void ClearItems()
-        {
-            _sparseColumns = null;
-            base.ClearItems();
-        }
-
-        protected override void InsertItem(int index, SqlRandomTypeInfo item)
-        {
-            _sparseColumns = null;
-            base.InsertItem(index, item);
-        }
-
-        protected override void RemoveItem(int index)
-        {
-            _sparseColumns = null;
-            base.RemoveItem(index);
-        }
-
-        protected override void SetItem(int index, SqlRandomTypeInfo item)
-        {
-            _sparseColumns = null;
-            base.SetItem(index, item);
-        }
-
-        /// <summary>
-        /// helper c-tor to fill one or two type sets
-        /// </summary>
-        private SqlRandomTypeInfoCollection(SqlRandomTypeInfo[] typeSet1, SqlRandomTypeInfo[] typeSet2)
-        {
-            if (typeSet1 != null)
-            {
-                AddRange(typeSet1);
-            }
-            if (typeSet2 != null)
-            {
-                AddRange(typeSet2);
-            }
-        }
-
-        protected override SqlDbType GetKeyForItem(SqlRandomTypeInfo item)
-        {
-            return item.Type;
-        }
-
-        public void AddRange(SqlRandomTypeInfo[] types)
-        {
-            for (int i = 0; i < types.Length; i++)
-                Add(types[i]);
-        }
-
-        /// <summary>
-        /// creates a collection of types supported in SQL 2005
-        /// </summary>
-        public static SqlRandomTypeInfoCollection CreateSql2005Collection()
-        {
-            return new SqlRandomTypeInfoCollection(s_sql2005Types);
-        }
-
-        /// <summary>
-        /// creates a collection of types supported in SQL 2005 and 2008
-        /// </summary>
-        public static SqlRandomTypeInfoCollection CreateSql2008Collection()
-        {
-            return new SqlRandomTypeInfoCollection(s_sql2005Types, s_newInSql2008Types);
-        }
-
-        /// <summary>
-        /// returns random type info
-        /// </summary>
-        public SqlRandomTypeInfo Next(SqlRandomizer rand)
-        {
-            return base[rand.NextIntInclusive(0, maxValueInclusive: Count - 1)];
-        }
-
-        /// <summary>
-        /// returns random type info from the columns that can be sparse
-        /// </summary>
-        public SqlRandomTypeInfo NextSparse(SqlRandomizer rand)
-        {
-            var sparseColumns = SparseColumns;
-            return sparseColumns[rand.NextIntInclusive(0, maxValueInclusive: sparseColumns.Count - 1)];
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypesForSqlServer.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomTypesForSqlServer.cs
deleted file mode 100644 (file)
index 1198fd9..0000000
+++ /dev/null
@@ -1,1455 +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.Data.Common;
-using System.Diagnostics;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    internal sealed class SqlVarBinaryTypeInfo : SqlRandomTypeInfo
-    {
-        private const int MaxDefinedSize = 8000;
-        private const string TypePrefix = "varbinary";
-        private const int DefaultSize = 1;
-
-        internal SqlVarBinaryTypeInfo()
-            : base(SqlDbType.VarBinary)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return LargeVarDataRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            string sizeSuffix;
-            if (!columnInfo.StorageSize.HasValue)
-            {
-                sizeSuffix = DefaultSize.ToString();
-            }
-            else
-            {
-                int size = columnInfo.StorageSize.Value;
-                if (size > MaxDefinedSize)
-                {
-                    sizeSuffix = "max";
-                }
-                else
-                {
-                    Debug.Assert(size > 0, "wrong size");
-                    sizeSuffix = size.ToString();
-                }
-            }
-            return string.Format("{0}({1})", TypePrefix, sizeSuffix);
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            int size = rand.NextAllocationSizeBytes(1);
-            return new SqlRandomTableColumn(this, options, size);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultSize;
-            return rand.NextByteArray(0, size);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadByteArray(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareByteArray(expected, actual, allowIncomplete: false);
-        }
-    }
-
-    internal sealed class SqlVarCharTypeInfo : SqlRandomTypeInfo
-    {
-        private const int MaxDefinedCharSize = 8000;
-        private const string TypePrefix = "varchar";
-        private const int DefaultCharSize = 1;
-
-        internal SqlVarCharTypeInfo()
-            : base(SqlDbType.VarChar)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return LargeVarDataRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            string sizeSuffix;
-            if (!columnInfo.StorageSize.HasValue)
-            {
-                sizeSuffix = DefaultCharSize.ToString();
-            }
-            else
-            {
-                int size = columnInfo.StorageSize.Value;
-                if (size > MaxDefinedCharSize)
-                {
-                    sizeSuffix = "max";
-                }
-                else
-                {
-                    Debug.Assert(size > 0, "wrong size");
-                    sizeSuffix = size.ToString();
-                }
-            }
-
-            return string.Format("{0}({1})", TypePrefix, sizeSuffix);
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            int size = rand.NextAllocationSizeBytes(1);
-            return new SqlRandomTableColumn(this, options, size);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize;
-            return rand.NextAnsiArray(0, size);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadCharData(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareCharArray(expected, actual, allowIncomplete: false);
-        }
-    }
-
-    internal sealed class SqlNVarCharTypeInfo : SqlRandomTypeInfo
-    {
-        private const int MaxDefinedCharSize = 4000;
-        private const string TypePrefix = "nvarchar";
-        private const int DefaultCharSize = 1;
-
-        internal SqlNVarCharTypeInfo()
-            : base(SqlDbType.NVarChar)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return LargeVarDataRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            string sizeSuffix;
-            if (!columnInfo.StorageSize.HasValue)
-            {
-                sizeSuffix = DefaultCharSize.ToString();
-            }
-            else
-            {
-                int charSize = columnInfo.StorageSize.Value / 2;
-                if (charSize > MaxDefinedCharSize)
-                {
-                    sizeSuffix = "max";
-                }
-                else
-                {
-                    Debug.Assert(charSize > 0, "wrong size");
-                    sizeSuffix = charSize.ToString();
-                }
-            }
-
-            return string.Format("{0}({1})", TypePrefix, sizeSuffix);
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            int size = rand.NextAllocationSizeBytes(2);
-            size = size & 0xFFFE; // clean last bit to make it even
-            return new SqlRandomTableColumn(this, options, storageSize: size);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            int storageSize = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize * 2;
-            return rand.NextUcs2Array(0, storageSize);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadCharData(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareCharArray(expected, actual, allowIncomplete: false);
-        }
-    }
-
-    internal sealed class SqlBigIntTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "bigint";
-        private const int StorageSize = 8;
-
-        public SqlBigIntTypeInfo()
-            : base(SqlDbType.BigInt)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return StorageSize;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextBigInt();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(long), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetInt64(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<long>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlIntTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "int";
-        private const int StorageSize = 4;
-
-        public SqlIntTypeInfo()
-            : base(SqlDbType.Int)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return StorageSize;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextIntInclusive();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(int), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetInt32(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<int>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlSmallIntTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "smallint";
-        private const int StorageSize = 2;
-
-        public SqlSmallIntTypeInfo()
-            : base(SqlDbType.SmallInt)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return StorageSize;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextSmallInt();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(short), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetInt16(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<short>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlTinyIntTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "tinyint";
-        private const int StorageSize = 1;
-
-        public SqlTinyIntTypeInfo()
-            : base(SqlDbType.TinyInt)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return StorageSize;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextTinyInt();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(byte), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetByte(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<byte>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlTextTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "text";
-
-        public SqlTextTypeInfo()
-            : base(SqlDbType.Text)
-        {
-        }
-
-        public override bool CanBeSparseColumn
-        {
-            get { return false; }
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return LargeDataRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextAnsiArray(0, columnInfo.StorageSize);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadCharData(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareCharArray(expected, actual, allowIncomplete: false);
-        }
-    }
-
-    internal sealed class SqlNTextTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "ntext";
-
-        public SqlNTextTypeInfo()
-            : base(SqlDbType.NText)
-        {
-        }
-
-        public override bool CanBeSparseColumn
-        {
-            get { return false; }
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return LargeDataRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextUcs2Array(0, columnInfo.StorageSize);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadCharData(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareCharArray(expected, actual, allowIncomplete: false);
-        }
-    }
-
-    internal sealed class SqlImageTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "image";
-
-        public SqlImageTypeInfo()
-            : base(SqlDbType.Image)
-        {
-        }
-
-        public override bool CanBeSparseColumn
-        {
-            get { return false; }
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return LargeDataRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextByteArray(0, columnInfo.StorageSize);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadByteArray(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareByteArray(expected, actual, allowIncomplete: false);
-        }
-    }
-
-    internal sealed class SqlBinaryTypeInfo : SqlRandomTypeInfo
-    {
-        private const int MaxStorageSize = 8000;
-        private const string TypePrefix = "binary";
-        private const int DefaultSize = 1;
-
-        public SqlBinaryTypeInfo()
-            : base(SqlDbType.Binary)
-        {
-        }
-
-        private int GetSize(SqlRandomTableColumn columnInfo)
-        {
-            ValidateColumnInfo(columnInfo);
-
-            int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultSize;
-            if (size < 1 || size > MaxStorageSize)
-                throw new NotSupportedException("wrong size");
-
-            return size;
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return GetSize(columnInfo);
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return string.Format("{0}({1})", TypePrefix, GetSize(columnInfo));
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            int size = rand.NextAllocationSizeBytes(1, MaxStorageSize);
-            return new SqlRandomTableColumn(this, options, size);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultSize;
-            return rand.NextByteArray(0, size);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadByteArray(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareByteArray(expected, actual, allowIncomplete: true);
-        }
-    }
-
-    internal sealed class SqlCharTypeInfo : SqlRandomTypeInfo
-    {
-        private const int MaxCharSize = 8000;
-        private const string TypePrefix = "char";
-        private const int DefaultCharSize = 1;
-
-        public SqlCharTypeInfo()
-            : base(SqlDbType.Char)
-        {
-        }
-
-        private int GetCharSize(SqlRandomTableColumn columnInfo)
-        {
-            ValidateColumnInfo(columnInfo);
-
-            int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize;
-            if (size < 1 || size > MaxCharSize)
-                throw new NotSupportedException("wrong size");
-
-            return size;
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return GetCharSize(columnInfo);
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return string.Format("{0}({1})", TypePrefix, GetCharSize(columnInfo));
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            int size = rand.NextAllocationSizeBytes(1, MaxCharSize);
-            return new SqlRandomTableColumn(this, options, size);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            int size = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value : DefaultCharSize;
-            return rand.NextAnsiArray(0, size);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadCharData(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareCharArray(expected, actual, allowIncomplete: true);
-        }
-    }
-
-    internal sealed class SqlNCharTypeInfo : SqlRandomTypeInfo
-    {
-        private const int MaxCharSize = 4000;
-        private const string TypePrefix = "nchar";
-        private const int DefaultCharSize = 1;
-
-        public SqlNCharTypeInfo()
-            : base(SqlDbType.NChar)
-        {
-        }
-
-        private int GetCharSize(SqlRandomTableColumn columnInfo)
-        {
-            ValidateColumnInfo(columnInfo);
-
-            int charSize = columnInfo.StorageSize.HasValue ? columnInfo.StorageSize.Value / 2 : DefaultCharSize;
-            if (charSize < 1 || charSize > MaxCharSize)
-                throw new NotSupportedException("wrong size");
-
-            return charSize;
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return GetCharSize(columnInfo) * 2; // nchar is not stored in row
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return string.Format("{0}({1})", TypePrefix, GetCharSize(columnInfo));
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            int size = rand.NextAllocationSizeBytes(2, MaxCharSize * 2);
-            size = size & 0xFFFE; // clean last bit to make it even
-            return new SqlRandomTableColumn(this, options, size);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            int storageSize = GetCharSize(columnInfo) * 2;
-            return rand.NextUcs2Array(0, storageSize);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadCharData(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareCharArray(expected, actual, allowIncomplete: true);
-        }
-    }
-
-    internal sealed class SqlBitTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlBitTypeInfo()
-            : base(SqlDbType.Bit)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 0.125; // 8 bits => 1 byte
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "bit";
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextBit();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(bool), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetBoolean(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<bool>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlDecimalTypeInfo : SqlRandomTypeInfo
-    {
-        private int _defaultPrecision = 18;
-
-        public SqlDecimalTypeInfo()
-            : base(SqlDbType.Decimal)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            int precision = columnInfo.Precision.HasValue ? columnInfo.Precision.Value : _defaultPrecision;
-            if (precision < 1 || precision > 38)
-            {
-                throw new ArgumentOutOfRangeException("wrong precision");
-            }
-
-            if (precision < 10)
-            {
-                return 5;
-            }
-            else if (precision < 20)
-            {
-                return 9;
-            }
-            else if (precision < 28)
-            {
-                return 13;
-            }
-            else
-            {
-                return 17;
-            }
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "decimal";
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            return CreateDefaultColumn(options);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return (decimal)Math.Round(rand.NextDouble());
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(decimal), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetDecimal(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<decimal>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlMoneyTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "money";
-        private const int StorageSize = 8;
-
-        public SqlMoneyTypeInfo()
-            : base(SqlDbType.Money)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return StorageSize;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextMoney();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(decimal), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetDecimal(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<decimal>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlSmallMoneyTypeInfo : SqlRandomTypeInfo
-    {
-        private const string TypeTSqlName = "smallmoney";
-        private const int StorageSize = 4;
-
-        public SqlSmallMoneyTypeInfo()
-            : base(SqlDbType.SmallMoney)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return StorageSize;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TypeTSqlName;
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextSmallMoney();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(decimal), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetDecimal(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<decimal>(expected, actual);
-        }
-    }
-
-    internal sealed class SqRealTypeInfo : SqlRandomTypeInfo
-    {
-        // simplify to double-precision or real only
-        private const int RealPrecision = 7;
-        private const int RealMantissaBits = 24;
-        private const string TSqlTypeName = "real";
-
-        public SqRealTypeInfo()
-            : base(SqlDbType.Real)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 4;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return TSqlTypeName;
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            return CreateDefaultColumn(options);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextReal();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(float), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetFloat(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<float>(expected, actual);
-        }
-    }
-
-
-    internal sealed class SqFloatTypeInfo : SqlRandomTypeInfo
-    {
-        // simplify to double-precision or real only
-        private const int MaxFloatMantissaBits = 53;
-        private const int MaxFloatPrecision = 15;
-        private const int RealPrecision = 7;
-        private const int RealMantissaBits = 24;
-        private const string TypePrefix = "float";
-
-        public SqFloatTypeInfo()
-            : base(SqlDbType.Float)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            // float
-            if (!columnInfo.Precision.HasValue)
-            {
-                return 8;
-            }
-            else
-            {
-                int precision = columnInfo.Precision.Value;
-                if (precision != RealPrecision && precision != MaxFloatPrecision)
-                    throw new ArgumentException("wrong precision");
-                return (precision <= RealPrecision) ? 4 : 8;
-            }
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            int precision = columnInfo.Precision.HasValue ? columnInfo.Precision.Value : MaxFloatPrecision;
-            if (precision != RealPrecision && precision != MaxFloatPrecision)
-                throw new ArgumentException("wrong precision");
-            int mantissaBits = (precision <= RealPrecision) ? 24 : 53;
-            return string.Format("{0}({1})", TypePrefix, mantissaBits);
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            return CreateDefaultColumn(options);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            int precision = columnInfo.Precision.HasValue ? columnInfo.Precision.Value : MaxFloatPrecision;
-            if (precision <= RealPrecision)
-                return rand.NextDouble(float.MinValue, float.MaxValue, precision);
-            else
-                return rand.NextDouble(double.MinValue, double.MaxValue, precision);
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(double), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetDouble(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<double>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlRowVersionTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlRowVersionTypeInfo()
-            : base(SqlDbType.Timestamp)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 8;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "rowversion";
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextRowVersion();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadByteArray(reader, ordinal, asType);
-        }
-
-        public override bool CanBeSparseColumn
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public override bool CanCompareValues(SqlRandomTableColumn columnInfo)
-        {
-            // completely ignore TIMESTAMP value comparison
-            return false;
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            throw new InvalidOperationException("should not be used for timestamp - use CanCompareValues before calling this method");
-        }
-    }
-
-    internal sealed class SqlUniqueIdentifierTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlUniqueIdentifierTypeInfo()
-            : base(SqlDbType.UniqueIdentifier)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 16;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "uniqueidentifier";
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            // this method does not use Guid.NewGuid since it is not based on the given rand object
-            return rand.NextUniqueIdentifier();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(Guid), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return reader.GetGuid(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<Guid>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlDateTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlDateTypeInfo()
-            : base(SqlDbType.Date)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 3;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "date";
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextDate();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadDateTime(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<DateTime>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlDateTimeTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlDateTimeTypeInfo()
-            : base(SqlDbType.DateTime)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 8;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "datetime";
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextDateTime();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadDateTime(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<DateTime>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlDateTime2TypeInfo : SqlRandomTypeInfo
-    {
-        private const int DefaultPrecision = 7;
-
-        public SqlDateTime2TypeInfo()
-            : base(SqlDbType.DateTime2)
-        {
-        }
-
-        private static int GetPrecision(SqlRandomTableColumn columnInfo)
-        {
-            int precision;
-
-            if (columnInfo.Precision.HasValue)
-            {
-                precision = columnInfo.Precision.Value;
-                if (precision < 0 || precision > 7)
-                    throw new ArgumentOutOfRangeException("columnInfo.Precision");
-            }
-            else
-            {
-                precision = DefaultPrecision;
-            }
-
-            return precision;
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            int precision = GetPrecision(columnInfo);
-            if (precision < 3)
-                return 6;
-            else if (precision < 5)
-                return 7;
-            else
-                return 8;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            int precision = GetPrecision(columnInfo);
-            if (precision == DefaultPrecision)
-                return "datetime2";
-            else
-            {
-                Debug.Assert(precision > 0, "wrong precision");
-                return string.Format("datetime2({0})", precision);
-            }
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            return CreateDefaultColumn(options);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextDateTime2();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadDateTime(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<DateTime>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlDateTimeOffsetTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlDateTimeOffsetTypeInfo()
-            : base(SqlDbType.DateTimeOffset)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 10;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "datetimeoffset";
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            return CreateDefaultColumn(options);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextDateTimeOffset();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(DateTimeOffset), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return ((System.Data.SqlClient.SqlDataReader)reader).GetDateTimeOffset(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<DateTimeOffset>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlSmallDateTimeTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlSmallDateTimeTypeInfo()
-            : base(SqlDbType.SmallDateTime)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 4;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "smalldatetime";
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextSmallDateTime();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadDateTime(reader, ordinal, asType);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<DateTime>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlTimeTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlTimeTypeInfo()
-            : base(SqlDbType.Time)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return 5;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "time ";
-        }
-
-        public override SqlRandomTableColumn CreateRandomColumn(SqlRandomizer rand, SqlRandomColumnOptions options)
-        {
-            return CreateDefaultColumn(options);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            return rand.NextTime();
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            ValidateReadType(typeof(TimeSpan), asType);
-            if (reader.IsDBNull(ordinal))
-                return DBNull.Value;
-            return ((System.Data.SqlClient.SqlDataReader)reader).GetTimeSpan(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            return CompareValues<TimeSpan>(expected, actual);
-        }
-    }
-
-    internal sealed class SqlVariantTypeInfo : SqlRandomTypeInfo
-    {
-        private static readonly SqlRandomTypeInfo[] s_variantSubTypes =
-        {
-            // var types
-            new SqlVarBinaryTypeInfo(),
-            new SqlVarCharTypeInfo(),
-            new SqlNVarCharTypeInfo(),
-
-            // integer data types
-            new SqlBigIntTypeInfo(),
-            new SqlIntTypeInfo(),
-            new SqlSmallIntTypeInfo(),
-            new SqlTinyIntTypeInfo(),
-
-            // fixed length blobs
-            new SqlCharTypeInfo(),
-            new SqlNCharTypeInfo(),
-            new SqlBinaryTypeInfo(),
-
-            // large blobs
-            new SqlTextTypeInfo(),
-            new SqlNTextTypeInfo(),
-            new SqlImageTypeInfo(),
-
-            // bit
-            new SqlBitTypeInfo(),
-
-            // decimal
-            new SqlDecimalTypeInfo(),
-
-            // money types
-            new SqlMoneyTypeInfo(),
-            new SqlSmallMoneyTypeInfo(),
-
-            // float types
-            new SqRealTypeInfo(),
-            new SqFloatTypeInfo(),
-
-            // unique identifier (== guid)
-            new SqlUniqueIdentifierTypeInfo(),
-
-            // date/time types
-            new SqlDateTimeTypeInfo(),
-            new SqlSmallDateTimeTypeInfo(),
-        };
-
-        public SqlVariantTypeInfo()
-            : base(SqlDbType.Variant)
-        {
-        }
-
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return VariantRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "sql_variant";
-        }
-
-        private static bool IsUnicodeType(SqlDbType t)
-        {
-            return (t == SqlDbType.NChar || t == SqlDbType.NText || t == SqlDbType.NVarChar);
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            SqlRandomTypeInfo subType = s_variantSubTypes[rand.NextIntInclusive(0, maxValueInclusive: s_variantSubTypes.Length - 1)];
-            object val = subType.CreateRandomValue(rand, new SqlRandomTableColumn(subType, SqlRandomColumnOptions.None, 8000));
-            char[] cval = val as char[];
-            if (cval != null)
-            {
-                int maxLength = IsUnicodeType(subType.Type) ? 4000 : 8000;
-                Debug.Assert(cval.Length < maxLength, "char array length cannot be greater than " + maxLength);
-                // cannot insert char[] into variant
-                val = new string((char[])val);
-            }
-            else
-            {
-                byte[] bval = val as byte[];
-                if (bval != null)
-                    Debug.Assert(bval.Length < 8000, "byte array length cannot be greater than 8000");
-            }
-
-            return val;
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return reader.GetValue(ordinal);
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            bool bothDbNull;
-            if (!CompareDbNullAndType(null, expected, actual, out bothDbNull) || bothDbNull)
-                return bothDbNull;
-
-            Type expectedType = expected.GetType();
-
-            if (expectedType == typeof(byte[]))
-            {
-                return CompareByteArray(expected, actual, allowIncomplete: false);
-            }
-            else if (expectedType == typeof(char[]))
-            {
-                return CompareCharArray(expected, actual, allowIncomplete: false);
-            }
-            else if (expectedType == typeof(string))
-            {
-                // special handling for strings, only in variant
-                if (actual.GetType() == typeof(string))
-                    return string.Equals((string)expected, (string)actual, StringComparison.Ordinal);
-                else
-                    return false;
-            }
-            else
-            {
-                return expected.Equals(actual);
-            }
-        }
-    }
-
-    internal sealed class SqlXmlTypeInfo : SqlRandomTypeInfo
-    {
-        public SqlXmlTypeInfo()
-            : base(SqlDbType.Xml)
-        {
-        }
-
-        protected override double GetInRowSizeInternal(SqlRandomTableColumn columnInfo)
-        {
-            return XmlRowUsage;
-        }
-
-        protected override string GetTSqlTypeDefinitionInternal(SqlRandomTableColumn columnInfo)
-        {
-            return "xml";
-        }
-
-        protected override object CreateRandomValueInternal(SqlRandomizer rand, SqlRandomTableColumn columnInfo)
-        {
-            if ((columnInfo.Options & SqlRandomColumnOptions.ColumnSet) != 0)
-            {
-                // use the sparse columns themselves to insert values
-                // testing column set column correctness is not a goal for the stress test
-                throw new NotImplementedException("should not use this method for column set columns");
-            }
-
-            int charSize = rand.NextAllocationSizeBytes(0, columnInfo.StorageSize);
-            const string prefix = "<x>";
-            const string suffix = "</x>";
-            if (charSize > (prefix.Length + suffix.Length))
-            {
-                string randValue = new string('a', charSize - (prefix.Length + suffix.Length));
-                return string.Format("<x>{0}</x>", randValue).ToCharArray();
-            }
-            else
-            {
-                // for accurate comparison, use the short form
-                return "<x />".ToCharArray();
-            }
-        }
-
-        protected override object ReadInternal(DbDataReader reader, int ordinal, SqlRandomTableColumn columnInfo, Type asType)
-        {
-            return ReadCharData(reader, ordinal, asType);
-        }
-
-        public override bool CanCompareValues(SqlRandomTableColumn columnInfo)
-        {
-            return (columnInfo.Options & SqlRandomColumnOptions.ColumnSet) == 0;
-        }
-
-        protected override bool CompareValuesInternal(SqlRandomTableColumn columnInfo, object expected, object actual)
-        {
-            if ((columnInfo.Options & SqlRandomColumnOptions.ColumnSet) != 0)
-            {
-                throw new InvalidOperationException("should not be used for ColumnSet columns - use CanCompareValues before calling this method");
-            }
-            return CompareCharArray(expected, actual, allowIncomplete: false);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomizer.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/RandomStressTest/SqlRandomizer.cs
deleted file mode 100644 (file)
index 39c272a..0000000
+++ /dev/null
@@ -1,685 +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.Data.SqlTypes;
-using System.Diagnostics;
-using System.Globalization;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// Generates random values for SQL Server testing, such as DateTime and Money. Instances of this class are not thread safe!
-    /// </summary>
-    public sealed class SqlRandomizer : Randomizer
-    {
-        /// <summary>
-        /// default limit for allocation size
-        /// </summary>
-        public const int DefaultMaxDataSize = 0x10000; // 1Mb
-
-        /// <summary>
-        /// must be set exactly once during construction only since it is part of random state
-        /// </summary>
-        private int _maxDataSize;
-
-        /// <summary>
-        /// when creating random buffers, this value is used to decide how much of random buffer
-        /// will be true random data. The true random data is filled in the beginning and rest of the
-        /// buffer repeats the same information
-        /// </summary>
-        private const int RepeatThreshold = 32;
-
-        public SqlRandomizer()
-            : this(CreateSeed(), DefaultMaxDataSize)
-        { } // do not add code here
-
-        public SqlRandomizer(int seed)
-            : this(seed, DefaultMaxDataSize)
-        { } // do not add code here
-
-        public SqlRandomizer(int seed, int maxDataSize)
-            : base(seed)
-        {
-            _maxDataSize = maxDataSize;
-        }
-
-        public SqlRandomizer(State state)
-            : base(state)
-        {
-            // Deserialize will read _maxDataSize too
-        }
-
-        protected override int BinaryStateSize
-        {
-            get
-            {
-                return base.BinaryStateSize + 4; // 4 bytes for _maxDataSize
-            }
-        }
-
-        protected override void Serialize(byte[] binState, out int nextOffset)
-        {
-            base.Serialize(binState, out nextOffset);
-
-            SerializeInt(_maxDataSize, binState, ref nextOffset);
-        }
-
-        protected internal override void Deserialize(byte[] binState, out int nextOffset)
-        {
-            base.Deserialize(binState, out nextOffset);
-
-            _maxDataSize = DeserializeInt(binState, ref nextOffset);
-        }
-
-        /// <summary>
-        /// generates random bitmap array (optimized)
-        /// </summary>
-        public BitArray NextBitmap(int bitCount)
-        {
-            if (bitCount <= 0)
-                throw new ArgumentOutOfRangeException("bitCount");
-
-            // optimize for any number of bits
-            byte[] randValues = new byte[(bitCount + 7) / 8];
-            base.NextBytes(randValues);
-            BitArray bitMap = new BitArray(randValues);
-            // the bitmap was created with length rounded up to 8, truncate to ensure correct size
-            bitMap.Length = bitCount;
-            return bitMap;
-        }
-
-        /// <summary>
-        /// generates random bitmap array, using probability for null (nullOdds is from 0 to 100)
-        /// </summary>
-        public BitArray NextBitmap(int bitCount, int nullOdds)
-        {
-            if (bitCount <= 0)
-                throw new ArgumentOutOfRangeException("bitCount");
-
-            if (nullOdds < 0 || nullOdds > 100)
-                throw new ArgumentOutOfRangeException("nullOdds");
-
-            // optimize for any number of bits
-            BitArray bitMap = new BitArray(bitCount, false);
-
-            for (int i = 0; i < bitCount; i++)
-            {
-                bitMap[i] = Next(100) < nullOdds;
-            }
-
-            return bitMap;
-        }
-
-        /// <summary>
-        /// generates random list of columns in random order, no repeated columns
-        /// </summary>
-        public int[] NextIndices(int count)
-        {
-            if (count <= 0)
-                throw new ArgumentOutOfRangeException("count");
-
-            int[] indices = new int[count];
-            for (int c = 0; c < count; c++)
-            {
-                indices[c] = c;
-            }
-
-            // shuffle
-            Shuffle(indices);
-
-            return indices;
-        }
-
-        /// <summary>
-        /// Shuffles the values in given array, numbers are taken from the whole array, even if valuesToSet is provided.
-        /// </summary>
-        /// <param name="valuesToSet">if provided, only the beginning of the array up to this index will be shuffled</param>
-        public void Shuffle<T>(T[] values, int? valuesToSet = null)
-        {
-            if (values == null)
-                throw new ArgumentNullException(nameof(values));
-
-            int count = values.Length;
-            int selectValues = count;
-            if (valuesToSet.HasValue)
-            {
-                selectValues = valuesToSet.Value;
-                if (selectValues < 0 || selectValues > count)
-                    throw new ArgumentOutOfRangeException("valuesToShuffle");
-            }
-
-            for (int i = 0; i < selectValues; i++)
-            {
-                int nextIndex = NextIntInclusive(i, maxValueInclusive: count - 1);
-                // swap
-                T temp = values[i]; values[i] = values[nextIndex]; values[nextIndex] = temp;
-            }
-        }
-
-        private enum LowValueEnforcementLevel
-        {
-            Uniform = 32,
-            Weak = 16,
-            Medium = 10,
-            Strong = 4,
-            VeryStrong = 2
-        }
-
-        /// <summary>
-        /// generates size value with low probability of large size values within the given range
-        /// </summary>
-        /// <param name="lowValuesEnforcementLevel">
-        /// lowValuesEnforcementLevel is value between 0 and 31;
-        /// 0 means uniform distribution in the min/max range;
-        /// 31 means very low chances for high values
-        /// </param>
-        private int NextAllocationUnit(int minSize, int maxSize, LowValueEnforcementLevel lowValuesLevel)
-        {
-            if (minSize < 0 || maxSize < 0 || minSize > maxSize)
-                throw new ArgumentOutOfRangeException("minSize or maxSize are out of range");
-
-            if (lowValuesLevel < LowValueEnforcementLevel.VeryStrong || lowValuesLevel > LowValueEnforcementLevel.Uniform)
-                throw new ArgumentOutOfRangeException("lowValuesLevel");
-
-            if (minSize == maxSize)
-                return minSize; // shortcut for fixed size
-
-            long longRange = (long)maxSize - (long)minSize + 1;
-
-            // create a sample in range [0, 1) (it is never 1)
-            double sample = base.NextDouble();
-
-            // decrease chances of large size values based on the how many bits digits are set in the maxValue
-            int bitsPerLevel = (int)lowValuesLevel;
-            long maxBitsLeft = longRange >> bitsPerLevel;
-            while (maxBitsLeft > 0)
-            {
-                sample *= base.NextDouble();
-                maxBitsLeft >>= bitsPerLevel;
-            }
-
-            int res = minSize + (int)(sample * longRange);
-            Debug.Assert(res >= minSize && res <= maxSize);
-            return res;
-        }
-
-        /// <summary>
-        /// Generates a random number to be used as a size for memory allocations.
-        /// This method will return with low numbers most of the time, but it has very low probability to generate large ones.
-        /// The limit is currently set to MaxData (even if maxSize is larger)
-        /// </summary>
-        public int NextAllocationSizeBytes(int minSize = 0, int? maxSize = null)
-        {
-            if (minSize > _maxDataSize)
-                throw new ArgumentOutOfRangeException("minSize cannot be greater than a maximum defined data size");
-            if (!maxSize.HasValue || maxSize.Value > _maxDataSize)
-                maxSize = _maxDataSize;
-            return NextAllocationUnit(minSize, maxSize.Value, LowValueEnforcementLevel.Strong);
-        }
-
-        /// <summary>
-        /// used by random table generators to select random number of columns and rows. This method will return very low numbers with high probability,
-        /// </summary>
-        public void NextTableDimentions(int maxRows, int maxColumns, int maxTotalSize, out int randRows, out int randColumns)
-        {
-            // prefer really low values to ensure table size will not go up way too much too frequently
-            const LowValueEnforcementLevel level = LowValueEnforcementLevel.Medium;
-            if (NextBit())
-            {
-                // select rows first, then columns
-                randColumns = NextAllocationUnit(1, maxColumns, level);
-                randRows = NextAllocationUnit(1, Math.Min(maxRows, maxTotalSize / randColumns), level);
-            }
-            else
-            {
-                randRows = NextAllocationUnit(1, maxRows, level);
-                randColumns = NextAllocationUnit(1, Math.Min(maxColumns, maxTotalSize / randRows), level);
-            }
-        }
-
-        #region byte and char array generators
-
-        /// <summary>
-        /// used internally to repeat randomly generated portions of the array
-        /// </summary>
-        private void Repeat<T>(T[] result, int trueRandomCount)
-        {
-            // repeat the first chunk into rest of the array
-            int remainder = result.Length - trueRandomCount;
-            int offset = trueRandomCount;
-
-            // repeat whole chunks
-            while (remainder >= trueRandomCount)
-            {
-                Array.Copy(result, 0, result, offset, trueRandomCount);
-                remainder -= trueRandomCount;
-                offset += trueRandomCount;
-            }
-
-            // complete the last (partial) chunk in the end, if any
-            if (remainder > 0)
-                Array.Copy(result, 0, result, offset, remainder);
-        }
-
-        /// <summary>
-        /// fill byte array with pseudo random data. Only the beginning of the array is filled with true random numbers, rest of it
-        /// is repeated data.
-        /// </summary>
-        public void FillByteArray(byte[] result)
-        {
-            if (result == null)
-                throw new ArgumentNullException(nameof(result));
-
-            if (result.Length == 0)
-                return;
-
-            // generate the first chunk of the array with true random values
-            int trueRandomCount = base.Next(1, Math.Min(result.Length, RepeatThreshold));
-            for (int i = 0; i < trueRandomCount; i++)
-                result[i] = unchecked((byte)base.Next());
-
-            Repeat(result, trueRandomCount);
-        }
-
-        /// <summary>
-        /// Fill the  array with pseudo random ANSI characters (ascii code less than 128). This method can be used to generate
-        /// char, varchar and text values.
-        /// </summary>
-        public void FillAnsiCharArray(char[] result)
-        {
-            if (result == null)
-                throw new ArgumentNullException(nameof(result));
-
-            if (result.Length == 0)
-                return;
-
-            // generate the first chunk of the array with true random values
-            int trueRandomCount = base.Next(1, Math.Min(result.Length, RepeatThreshold));
-            for (int i = 0; i < trueRandomCount; i++)
-                result[i] = (char)NextIntInclusive(0, maxValueInclusive: 127);
-
-            Repeat(result, trueRandomCount);
-        }
-
-        /// <summary>
-        /// Fill the array with pseudo random unicode characters, not including the surrogate ranges.  This method can be used to generate
-        /// nchar, nvarchar and ntext values.
-        /// </summary>
-        public void FillUcs2CharArray(char[] result)
-        {
-            if (result == null)
-                throw new ArgumentNullException(nameof(result));
-
-            if (result.Length == 0)
-                return;
-
-            // generate the first chunk of the array with true random values
-            int trueRandomCount = base.Next(1, Math.Min(result.Length, RepeatThreshold));
-            for (int i = 0; i < trueRandomCount; i++)
-                result[i] = (char)NextIntInclusive(0, maxValueInclusive: 0xD800 - 1); // do not include surrogates
-
-            Repeat(result, trueRandomCount);
-        }
-
-        /// <summary>
-        /// generates random byte array with high probability of small-size arrays
-        /// </summary>
-        public byte[] NextByteArray(int minSize = 0, int? maxSize = null)
-        {
-            int size = NextAllocationSizeBytes(minSize, maxSize);
-            byte[] resArray = new byte[size];
-            FillByteArray(resArray);
-            return resArray;
-        }
-
-        /// <summary>
-        /// generates random Ucs2 array with high probability of small-size arrays. The result does not include surrogate pairs or characters.
-        /// </summary>
-        public char[] NextUcs2Array(int minSize = 0, int? maxByteSize = null)
-        {
-            // enforce max data in characters
-            if (!maxByteSize.HasValue || maxByteSize.Value > _maxDataSize)
-                maxByteSize = _maxDataSize;
-
-            int charSize = NextAllocationSizeBytes(minSize, maxByteSize) / 2;
-            char[] resArray = new char[charSize];
-            FillUcs2CharArray(resArray);
-            return resArray;
-        }
-
-        /// <summary>
-        /// generates random array with high probability of small-size arrays. The result includes only characters with code less than 128.
-        /// </summary>
-        public char[] NextAnsiArray(int minSize = 0, int? maxSize = null)
-        {
-            // enforce max allocation size for char array
-            if (!maxSize.HasValue || maxSize.Value > _maxDataSize / 2)
-                maxSize = _maxDataSize / 2;
-
-            int size = NextAllocationSizeBytes(minSize, maxSize);
-            char[] resArray = new char[size];
-            FillAnsiCharArray(resArray);
-            return resArray;
-        }
-
-        /// <summary>
-        /// generates random binary value for SQL Server, with high probability of small-size arrays.
-        /// </summary>
-        public byte[] NextBinary(int minSize = 0, int maxSize = 8000)
-        {
-            return NextByteArray(minSize, maxSize);
-        }
-
-        /// <summary>
-        /// returns a random 8-byte array as a timestamp (rowversion) value
-        /// </summary>
-        public byte[] NextRowVersion()
-        {
-            return NextByteArray(8, 8);
-        }
-
-        /// <summary>
-        /// returns a random GUID to be used as unique identifier in SQL. Note that this method is deterministic for fixed seed random instances
-        /// (it does NOT use Guid.NewGuid).
-        /// </summary>
-        public Guid NextUniqueIdentifier()
-        {
-            return new Guid(NextByteArray(16, 16));
-        }
-
-        #endregion
-
-        #region Date and Time values
-
-        /// <summary>
-        /// generates random, but valid datetime-type value, for SQL Server, with 3msec resolution (0, 3, 7msec)
-        /// </summary>
-        public DateTime NextDateTime()
-        {
-            DateTime dt = NextDateTime(SqlDateTime.MinValue.Value, SqlDateTime.MaxValue.Value);
-            // round to datetime type resolution (increments of .000, .003, or .007 seconds)
-            long totalMilliseconds = dt.Ticks / TimeSpan.TicksPerMillisecond;
-            int lastDigit = (int)(totalMilliseconds % 10);
-            if (lastDigit < 3)
-                lastDigit = 0;
-            else if (lastDigit < 7)
-                lastDigit = 3;
-            else
-                lastDigit = 7;
-
-            totalMilliseconds = (totalMilliseconds / 10) * 10 + lastDigit;
-            return new DateTime(totalMilliseconds * TimeSpan.TicksPerMillisecond);
-        }
-
-        /// <summary>
-        /// generates random, but valid datetime2 value for SQL Server
-        /// </summary>
-        public DateTime NextDateTime2()
-        {
-            return NextDateTime(DateTime.MinValue, DateTime.MaxValue);
-        }
-
-        /// <summary>
-        /// generates random, but valid datetimeoffset value for SQL Server
-        /// </summary>
-        public DateTimeOffset NextDateTimeOffset()
-        {
-            return new DateTimeOffset(NextDateTime2());
-        }
-
-        /// <summary>
-        /// generates random, but valid date value for SQL Server
-        /// </summary>
-        public DateTime NextDate()
-        {
-            return NextDateTime2().Date;
-        }
-
-        /// <summary>
-        /// generates random DateTime value in the given range.
-        /// </summary>
-        public DateTime NextDateTime(DateTime minValue, DateTime maxValueInclusive)
-        {
-            double ticksRange = unchecked((double)maxValueInclusive.Ticks - minValue.Ticks + 1);
-            long ticks = minValue.Ticks + (long)(ticksRange * base.NextDouble());
-            return new DateTime(ticks);
-        }
-
-        /// <summary>
-        /// generates random smalldatetime value for SQL server, in the range of January 1, 1900 to June 6, 2079, to an accuracy of one minute
-        /// </summary>
-        public DateTime NextSmallDateTime()
-        {
-            DateTime dt = NextDateTime(
-                        minValue: new DateTime(1900, 1, 1, 0, 0, 0),
-                        maxValueInclusive: new DateTime(2079, 6, 6));
-            // truncate minutes
-            dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0);
-            return dt;
-        }
-
-        /// <summary>
-        /// generates random TIME value for SQL Server (one day clock, 100 nano second precision)
-        /// </summary>
-        public TimeSpan NextTime()
-        {
-            return TimeSpan.FromTicks(Math.Abs(NextBigInt()) % TimeSpan.TicksPerDay);
-        }
-
-        #endregion
-
-        #region Double values
-
-        /// <summary>
-        /// generates random Double value in the given range
-        /// </summary>
-        public double NextDouble(double minValue, double maxValueExclusive)
-        {
-            double res;
-            if (minValue >= maxValueExclusive)
-                throw new ArgumentException("minValue >= maxValueExclusive");
-
-            double rand01 = base.NextDouble();
-
-            if (((minValue >= 0) && (maxValueExclusive >= 0)) ||
-                ((minValue <= 0) && (maxValueExclusive <= 0)))
-            {
-                // safe to diff
-                double diff = maxValueExclusive - minValue;
-                res = minValue + diff * rand01;
-            }
-            else
-            {
-                // not safe to diff, (max-min) may cause overflow
-                res = minValue - minValue * rand01 + maxValueExclusive * rand01;
-            }
-
-            Debug.Assert(res >= minValue && res < maxValueExclusive);
-            return res;
-        }
-
-        /// <summary>
-        /// generates random Double value in the given range and up to precision specified
-        /// </summary>
-        public double NextDouble(double minValue, double maxValueExclusive, int precision)
-        {
-            // ensure input values are rounded
-            if (maxValueExclusive != Math.Round(maxValueExclusive, precision))
-            {
-                throw new ArgumentException("maxValueExclusive must be rounded to the given precision");
-            }
-            if (minValue != Math.Round(minValue, precision))
-            {
-                throw new ArgumentException("minValue must be rounded to the given precision");
-            }
-
-            // this call will also ensure that minValue < maxValueExclusive
-            double res = NextDouble(minValue, maxValueExclusive);
-            res = Math.Round(res, precision);
-
-            if (res >= maxValueExclusive)
-            {
-                // this can happen after rounding up value which was too close to the max edge
-                // just use minValue instead
-                res = minValue;
-            }
-
-            Debug.Assert(res >= minValue && res < maxValueExclusive);
-            return res;
-        }
-
-        /// <summary>
-        /// generates random real value for SQL server. Note that real is a single precision floating number, mapped to 'float' in .Net.
-        /// </summary>
-        public float NextReal()
-        {
-            return (float)NextDouble(float.MinValue, float.MaxValue);
-        }
-
-        #endregion
-
-        #region Integral values
-
-        /// <summary>
-        /// generates random number in the given range, both min and max values can be in the range of returned values.
-        /// </summary>
-        public int NextIntInclusive(int minValue = int.MinValue, int maxValueInclusive = int.MaxValue)
-        {
-            if (minValue == maxValueInclusive)
-                return minValue;
-
-            int res;
-            if (maxValueInclusive == int.MaxValue)
-            {
-                if (minValue == int.MinValue)
-                {
-                    byte[] temp = new byte[4];
-                    base.NextBytes(temp);
-                    res = BitConverter.ToInt32(temp, 0);
-                }
-                else
-                {
-                    res = base.Next(minValue - 1, maxValueInclusive) + 1;
-                }
-            }
-            else // maxValue < int.MaxValue
-            {
-                res = base.Next(minValue, maxValueInclusive + 1);
-            }
-
-            Debug.Assert(res >= minValue && res <= maxValueInclusive);
-            return res;
-        }
-
-        /// <summary>
-        /// random bigint 64-bit value
-        /// </summary>
-        public long NextBigInt()
-        {
-            byte[] temp = new byte[8];
-            base.NextBytes(temp);
-            return BitConverter.ToInt64(temp, 0);
-        }
-
-        /// <summary>
-        /// random smallint (16-bit) value
-        /// </summary>
-        public short NextSmallInt()
-        {
-            return (short)NextIntInclusive(short.MinValue, maxValueInclusive: short.MaxValue);
-        }
-
-        /// <summary>
-        /// generates a tinyint value (8 bit, unsigned)
-        /// </summary>
-        public byte NextTinyInt()
-        {
-            return (byte)NextIntInclusive(0, maxValueInclusive: byte.MaxValue);
-        }
-
-        /// <summary>
-        /// random bit
-        /// </summary>
-        public bool NextBit()
-        {
-            return base.Next() % 2 == 0;
-        }
-
-        #endregion
-
-        #region Monetary types
-
-        /// <summary>
-        /// generates random SMALLMONEY value
-        /// </summary>
-        public decimal NextSmallMoney()
-        {
-            return (decimal)NextDouble(
-                minValue: -214748.3648,
-                maxValueExclusive: 214748.3647,
-                precision: 4);
-        }
-
-        /// <summary>
-        /// generates random MONEY value
-        /// </summary>
-        /// <returns></returns>
-        public decimal NextMoney()
-        {
-            return (decimal)NextDouble((double)SqlMoney.MinValue.Value, (double)SqlMoney.MaxValue.Value);
-        }
-
-        #endregion
-
-        #region helper methods to create random SQL object names
-
-        /// <summary>
-        /// Generates a random name to be used for database object. The length will be no more then (16 + prefix.Length + escapeLeft.Length + escapeRight.Length)
-        /// Note this method is not deterministic, it uses Guid.NewGuild to generate unique name to avoid name conflicts between test runs.
-        /// </summary>
-        private static string GenerateUniqueObjectName(string prefix, string escapeLeft, string escapeRight)
-        {
-            string uniqueName = string.Format("{0}{1}_{2}_{3}{4}",
-                escapeLeft,
-                prefix,
-                DateTime.Now.Ticks.ToString("X", CultureInfo.InvariantCulture), // up to 8 characters
-                Guid.NewGuid().ToString().Substring(0, 6), // take the first 6 characters only
-                escapeRight);
-            return uniqueName;
-        }
-
-        /// <summary>
-        /// Generates a random name to be used for SQL Server database object. SQL Server supports long names (up to 128 characters), add extra info for troubleshooting.
-        /// Note this method is not deterministic, it uses Guid.NewGuild to generate unique name to avoid name conflicts between test runs.
-        /// </summary>
-        public static string GenerateUniqueObjectNameForSqlServer(string prefix)
-        {
-            Process currentProcess = Process.GetCurrentProcess();
-            string extendedPrefix = string.Format(
-                "{0}_{1}@{2}",
-                prefix,
-                currentProcess.ProcessName,
-                currentProcess.MachineName,
-                DateTime.Now.ToString("yyyy_MM_dd", CultureInfo.InvariantCulture));
-            string name = GenerateUniqueObjectName(extendedPrefix, "[", "]");
-            if (name.Length > 128)
-            {
-                throw new ArgumentOutOfRangeException("the name is too long - SQL Server names are limited to 128");
-            }
-            return name;
-        }
-
-        /// <summary>
-        /// Generates a random temp table name for SQL Server.
-        /// Note this method is not deterministic, it uses Guid.NewGuild to generate unique name to avoid name conflicts between test runs.
-        /// </summary>
-        public static string GenerateUniqueTempTableNameForSqlServer()
-        {
-            return GenerateUniqueObjectNameForSqlServer("#T");
-        }
-
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SplitPacketTest/SplitPacketTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SplitPacketTest/SplitPacketTest.cs
deleted file mode 100644 (file)
index 653e8cb..0000000
+++ /dev/null
@@ -1,175 +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.Sockets;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class SplitPacketTest
-    {
-        private int Port = -1;
-        private int SplitPacketSize = 1;
-        private string BaseConnString;
-
-        public SplitPacketTest()
-        {
-            string actualHost;
-            int actualPort;
-
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            GetTcpInfoFromDataSource(builder.DataSource, out actualHost, out actualPort);
-
-            Task.Factory.StartNew(() => { SetupProxy(actualHost, actualPort); });
-
-            for (int i = 0; i < 10 && Port == -1; i++)
-            {
-                Thread.Sleep(500);
-            }
-            if (Port == -1) throw new InvalidOperationException("Proxy local port not defined!");
-
-            builder.DataSource = "tcp:127.0.0.1," + Port;
-            BaseConnString = builder.ConnectionString;
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void OneByteSplitTest()
-        {
-            SplitPacketSize = 1;
-            OpenConnection();
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void AlmostFullHeaderTest()
-        {
-            SplitPacketSize = 7;
-            OpenConnection();
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void FullHeaderTest()
-        {
-            SplitPacketSize = 8;
-            OpenConnection();
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void HeaderPlusOneTest()
-        {
-            SplitPacketSize = 9;
-            OpenConnection();
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void MARSSplitTest()
-        {
-            SplitPacketSize = 1;
-            OpenMarsConnection("select * from Orders");
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void MARSReplicateTest()
-        {
-            SplitPacketSize = 1;
-            OpenMarsConnection("select REPLICATE('A', 10000)");
-        }
-
-        private void OpenMarsConnection(string cmdText)
-        {
-            using (SqlConnection conn = new SqlConnection((new SqlConnectionStringBuilder(BaseConnString) { MultipleActiveResultSets = true }).ConnectionString))
-            {
-                conn.Open();
-                using (SqlCommand cmd1 = new SqlCommand(cmdText, conn))
-                using (SqlCommand cmd2 = new SqlCommand(cmdText, conn))
-                using (SqlCommand cmd3 = new SqlCommand(cmdText, conn))
-                using (SqlCommand cmd4 = new SqlCommand(cmdText, conn))
-                {
-                    cmd1.ExecuteReader();
-                    cmd2.ExecuteReader();
-                    cmd3.ExecuteReader();
-                    cmd4.ExecuteReader();
-                }
-                conn.Close();
-            }
-        }
-
-        private void OpenConnection()
-        {
-            using (SqlConnection conn = new SqlConnection(BaseConnString))
-            {
-                conn.Open();
-                using (SqlCommand cmd = new SqlCommand("select * from Orders", conn))
-                {
-                    SqlDataReader reader = cmd.ExecuteReader();
-                    Assert.True(reader.HasRows, "Split packet query did not return any rows!");
-                }
-                conn.Close();
-            }
-        }
-
-        private void SetupProxy(string actualHost, int actualPort)
-        {
-            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
-            listener.Start();
-            Port = ((IPEndPoint)listener.LocalEndpoint).Port;
-            var client = listener.AcceptTcpClientAsync().GetAwaiter().GetResult();
-
-            var sqlClient = new TcpClient();
-            sqlClient.ConnectAsync(actualHost, actualPort).Wait();
-
-            Task.Factory.StartNew(() => { ForwardToSql(client, sqlClient); });
-            Task.Factory.StartNew(() => { ForwardToClient(client, sqlClient); });
-        }
-
-        private void ForwardToSql(TcpClient ourClient, TcpClient sqlClient)
-        {
-            while (true)
-            {
-                byte[] buffer = new byte[1024];
-                int bytesRead = ourClient.GetStream().Read(buffer, 0, buffer.Length);
-
-                sqlClient.GetStream().Write(buffer, 0, bytesRead);
-            }
-        }
-
-        private void ForwardToClient(TcpClient ourClient, TcpClient sqlClient)
-        {
-            while (true)
-            {
-                byte[] buffer = new byte[SplitPacketSize];
-                int bytesRead = sqlClient.GetStream().Read(buffer, 0, buffer.Length);
-
-                ourClient.GetStream().Write(buffer, 0, bytesRead);
-
-                buffer = new byte[1024];
-                bytesRead = sqlClient.GetStream().Read(buffer, 0, buffer.Length);
-
-                ourClient.GetStream().Write(buffer, 0, bytesRead);
-            }
-        }
-
-        private static void GetTcpInfoFromDataSource(string dataSource, out string hostName, out int port)
-        {
-            string[] dataSourceParts = dataSource.Split(',');
-            if (dataSourceParts.Length == 1)
-            {
-                hostName = dataSourceParts[0].Replace("tcp:", "");
-                port = 1433;
-            }
-            else if (dataSourceParts.Length == 2)
-            {
-                hostName = dataSourceParts[0].Replace("tcp:", "");
-                port = int.Parse(dataSourceParts[1]);
-            }
-            else
-            {
-                throw new InvalidOperationException("TCP Connection String not in correct format!");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/AdjustPrecScaleForBulkCopy.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/AdjustPrecScaleForBulkCopy.cs
deleted file mode 100644 (file)
index 110a718..0000000
+++ /dev/null
@@ -1,70 +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.Data.SqlTypes;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class AdjustPrecScaleForBulkCopy
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void RunTest()
-        {
-            SqlDecimal value = BulkCopySqlDecimalToTable(new SqlDecimal(0), 1, 0, 2, 2);
-            Assert.Equal("0.00", value.ToString());
-
-            value = BulkCopySqlDecimalToTable(new SqlDecimal(10.0), 10, 1, 4, 2);
-            Assert.Equal("10.00", value.ToString());
-
-            value = BulkCopySqlDecimalToTable(new SqlDecimal(10.00), 7, 2, 2, 0);
-            Assert.Equal("10", value.ToString());
-
-            value = BulkCopySqlDecimalToTable(new SqlDecimal(12.345), 5, 3, 3, 1);
-            Assert.Equal("12.3", value.ToString());
-
-            value = BulkCopySqlDecimalToTable(new SqlDecimal(123.45), 10, 2, 4, 1);
-            Assert.Equal("123.4", value.ToString());
-
-            Assert.Throws<InvalidOperationException>(() => BulkCopySqlDecimalToTable(new SqlDecimal(111.00), 7, 2, 2, 0));
-        }
-
-        private static SqlDecimal BulkCopySqlDecimalToTable(SqlDecimal decimalValue, int sourcePrecision, int sourceScale, int targetPrecision, int targetScale)
-        {
-            string tableName = DataTestUtility.GenerateTableName();
-            string connectionString = DataTestUtility.TcpConnStr;
-
-            SqlDecimal resultValue;
-            try
-            {
-                DataTestUtility.RunNonQuery(connectionString, $"create table {tableName} (target_column decimal({targetPrecision}, {targetScale}))");
-
-                SqlDecimal inputValue = SqlDecimal.ConvertToPrecScale(decimalValue, sourcePrecision, sourceScale);
-
-                DataTable dt = new DataTable();
-                dt.Clear();
-                dt.Columns.Add("source_column", typeof(SqlDecimal));
-                DataRow row = dt.NewRow();
-                row["source_column"] = inputValue;
-                dt.Rows.Add(row);
-
-                using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
-                {
-                    sbc.DestinationTableName = tableName;
-                    sbc.ColumnMappings.Add("source_column", "target_column");
-                    sbc.WriteToServer(dt);
-                }
-
-                DataTable resultTable = DataTestUtility.RunQuery(connectionString, $"select * from {tableName}");
-                resultValue = new SqlDecimal((decimal)resultTable.Rows[0][0]);
-            }
-            finally
-            {
-                DataTestUtility.RunNonQuery(connectionString, $"drop table {tableName}");
-            }
-
-            return resultValue;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/AzureDistributedTransaction.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/AzureDistributedTransaction.cs
deleted file mode 100644 (file)
index 025584b..0000000
+++ /dev/null
@@ -1,70 +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.Transactions;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class AzureDistributedTransaction
-    {
-        private static readonly string s_connectionString = DataTestUtility.TcpConnStr;
-        private static readonly string s_tableName        = "Azure_" + Guid.NewGuid().ToString().Replace('-', '_');
-        private static readonly string s_createTableCmd   = $"CREATE TABLE {s_tableName} (NAME NVARCHAR(40), AGE INT)";
-        private static readonly string s_sqlBulkCopyCmd   = "SELECT * FROM(VALUES ('Fuller', 33), ('Davon', 49)) AS q (FirstName, Age)";
-        private static readonly int    s_commandTimeout   = 30;
-
-        public static void Test()
-        {
-            try
-            {
-#if DEBUG
-               Console.WriteLine($"Creating Table {s_tableName}");
-#endif
-                // Setup Azure Table
-                Helpers.ExecuteNonQueryAzure(s_connectionString, s_createTableCmd, s_commandTimeout);
-                using (var txScope = new TransactionScope())
-                {
-                    BulkCopy(s_connectionString);
-                    txScope.Complete();
-                }
-            }
-            catch (Exception ex)
-            {
-                Console.WriteLine($"Error: {ex.Message}");
-                Assert.Null(ex);
-            }
-            finally
-            {
-#if DEBUG
-                Console.WriteLine($"Dropping Table {s_tableName}");
-#endif
-                // Drop Azure Table
-                Helpers.ExecuteNonQueryAzure(s_connectionString, "DROP TABLE " + s_tableName, s_commandTimeout);
-            }
-        }
-
-        static void BulkCopy(string connectionString)
-        {
-            using (SqlConnection connectionSrc = new SqlConnection(connectionString))
-            using (SqlConnection connectionDst = new SqlConnection(connectionString))
-            using (SqlCommand commandSrc = new SqlCommand(s_sqlBulkCopyCmd, connectionSrc))
-            using (SqlCommand commandDst = connectionDst.CreateCommand())
-            {
-                connectionSrc.Open();
-                connectionDst.Open();
-
-                commandSrc.CommandTimeout = s_commandTimeout;
-                using (SqlDataReader reader = commandSrc.ExecuteReader())
-                {
-                    using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connectionDst))
-                    {
-                        sqlBulkCopy.DestinationTableName = s_tableName;
-                        sqlBulkCopy.WriteToServer(reader);
-                    }
-                    reader.Close();
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug84548.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug84548.cs
deleted file mode 100644 (file)
index c93b5cb..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Bug84548
-    {
-        public static void Test(string srcConstr, string dstConstr, string targettable)
-        {
-            string targetCustomerTable = targettable + "_customer";
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "CREATE TABLE [" + targetCustomerTable + "] ([CustomerID] [nchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, CONSTRAINT [PK_" + targetCustomerTable + "] PRIMARY KEY CLUSTERED (CustomerID) ON [PRIMARY]) ON [PRIMARY]");
-
-                    Helpers.TryExecute(dstCmd,
-                        "CREATE TABLE [" + targettable + "] ([OrderID] [int] NOT NULL , " +
-                        " [CustomerID] [nchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , " +
-                        " CONSTRAINT [PK_" + targettable + "] PRIMARY KEY  CLUSTERED " +
-                        " (" +
-                        "  [OrderID]" +
-                        " )  ON [PRIMARY] ," +
-                        " CONSTRAINT [FK_" + targettable + "_Customers] FOREIGN KEY " +
-                        " (" +
-                        "  [CustomerID]" +
-                        " ) REFERENCES [" + targetCustomerTable + "] (" +
-                        " [CustomerID]" +
-                        " )" +
-                        ") ON [PRIMARY]");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    {
-                        srcConn.Open();
-
-                        // First copy the customer ID list across
-                        SqlCommand customerCommand = new SqlCommand("SELECT CustomerID from Northwind..Customers", srcConn);
-                        using (DbDataReader reader = customerCommand.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = targetCustomerTable;
-                                bulkcopy.WriteToServer(reader);
-                            }
-                        }
-
-                        SqlCommand srcCmd = new SqlCommand("select OrderID, CustomerID from Northwind..Orders where OrderId = 10643", srcConn);
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = targettable;
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                                ColumnMappings.Add("OrderID", "OrderID");
-                                ColumnMappings.Add("CustomerID", "CustomerID");
-
-                                bulkcopy.WriteToServer(reader);
-                                bulkcopy.Close();
-                            }
-                        }
-                    }
-                    Helpers.VerifyResults(dstConn, targettable, 2, 1);
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + targettable);
-                    Helpers.TryExecute(dstCmd, "drop table " + targetCustomerTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug85007.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug85007.cs
deleted file mode 100644 (file)
index 3e06bc5..0000000
+++ /dev/null
@@ -1,108 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Bug85007
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            string targetCustomerTable = dstTable + "_customer";
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "CREATE TABLE [" + targetCustomerTable + "] ([CustomerID] [nchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, CONSTRAINT [PK_" + targetCustomerTable + "] PRIMARY KEY CLUSTERED (CustomerID) ON [PRIMARY]) ON [PRIMARY]");
-
-                    Helpers.TryExecute(dstCmd,
-                        "CREATE TABLE [" + dstTable + "] (" +
-                        "    [OrderID] [int] IDENTITY (1, 1) NOT NULL ," +
-                        "    [CustomerID] [nchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ," +
-                        "    [EmployeeID] [int] NULL ," +
-                        "    [OrderDate] [datetime] NULL ," +
-                        "    [RequiredDate] [datetime] NULL ," +
-                        "    [ShippedDate] [datetime] NULL ," +
-                        "    [ShipVia] [int] NULL ," +
-                        "    [Freight] [money] NULL CONSTRAINT [DF_" + dstTable + "_Freight] DEFAULT (0)," +
-                        "    [ShipName] [nvarchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ," +
-                        "    [ShipAddress] [nvarchar] (60) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ," +
-                        "    [ShipCity] [nvarchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ," +
-                        "    [ShipRegion] [nvarchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ," +
-                        "    [ShipPostalCode] [nvarchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ," +
-                        "    [ShipCountry] [nvarchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ," +
-                        "    CONSTRAINT [PK_" + dstTable + "] PRIMARY KEY  CLUSTERED " +
-                        "    (" +
-                        "        [OrderID]" +
-                        "    )  ON [PRIMARY] ," +
-                        "    CONSTRAINT [FK_" + dstTable + "_Customers] FOREIGN KEY " +
-                        "    (" +
-                        "        [CustomerID]" +
-                        "    ) REFERENCES [" + targetCustomerTable + "] (" +
-                        "        [CustomerID]" +
-                        "    )" +
-                        ") ON [PRIMARY]");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand customerCmd = new SqlCommand("SELECT CustomerID from Northwind..Customers", srcConn))
-                    {
-                        srcConn.Open();
-
-                        // First copy the customer ID list across
-                        using (DbDataReader reader = customerCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = targetCustomerTable;
-                                bulkcopy.WriteToServer(reader);
-                            }
-                        }
-
-                        SqlCommand srcCmd = new SqlCommand("select * from orders", srcConn);
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-                                bulkcopy.BatchSize = 6;
-
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                                ColumnMappings.Add("OrderID", "OrderID");
-                                ColumnMappings.Add("CustomerID", "CustomerID");
-                                ColumnMappings.Add("EmployeeID", "EmployeeID");
-                                ColumnMappings.Add("RequiredDate", "RequiredDate");
-                                ColumnMappings.Add("ShippedDate", "ShippedDate");
-                                ColumnMappings.Add("ShipVia", "ShipVia");
-                                ColumnMappings.Add("Freight", "Freight");
-                                ColumnMappings.Add("ShipName", "ShipName");
-                                ColumnMappings.Add("ShipAddress", "ShipAddress");
-                                ColumnMappings.Add("ShipCity", "ShipCity");
-                                ColumnMappings.Add("ShipRegion", "ShipRegion");
-                                ColumnMappings.Add("ShipPostalCode", "ShipPostalCode");
-                                ColumnMappings.Add("ShipCountry", "ShipCountry");
-
-                                bulkcopy.WriteToServer(reader);
-                            }
-                            Helpers.VerifyResults(dstConn, dstTable, 14, 830);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                    Helpers.TryExecute(dstCmd, "drop table " + targetCustomerTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug903514.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug903514.cs
deleted file mode 100644 (file)
index 1043f88..0000000
+++ /dev/null
@@ -1,95 +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.Data;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Bug903514
-    {
-        public static void Test(string constr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(constr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 varchar(7000))");
-            }
-
-            DoBulkCopy(constr, dstTable, 2);
-            DoBulkCopy(constr, dstTable, 0);
-
-            using (SqlConnection dstConn = new SqlConnection(constr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-            }
-        }
-
-        private static void DoBulkCopy(string dstConstr, string dstTable, int timeout)
-        {
-            DataTable table = new DataTable();
-            DataColumn column;
-            DataRow row;
-
-            column = new DataColumn();
-            column.DataType = System.Type.GetType("System.Int32");
-            column.ColumnName = "col1";
-            table.Columns.Add(column);
-            column = new DataColumn();
-            column.DataType = Type.GetType("System.String");
-            column.ColumnName = "col2";
-            table.Columns.Add(column);
-
-            if (0 == timeout)
-            {
-                for (int i = 0; i < 100; i++)
-                {
-                    row = table.NewRow();
-                    row["col1"] = i;
-                    row["col2"] = "item " + i;
-                    table.Rows.Add(row);
-                }
-            }
-            else
-            {
-                string s = new string('a', 4000);
-
-                for (int i = 0; i < 750000; i++)
-                {
-                    row = table.NewRow();
-                    row["col1"] = i;
-                    row["col2"] = s;
-                    table.Rows.Add(row);
-                }
-            }
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            {
-                dstConn.Open();
-
-                using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                {
-                    bulkcopy.DestinationTableName = dstTable;
-
-                    bulkcopy.BulkCopyTimeout = timeout;
-
-                    try
-                    {
-                        bulkcopy.WriteToServer(table);
-                    }
-                    catch (Exception e)
-                    {
-                        Assert.True(e.Message.Contains("Timeout expired") && 0 != timeout, "Unexpected exception: " + e);
-                    }
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug98182.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug98182.cs
deleted file mode 100644 (file)
index 4e22f6a..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Bug98182
-    {
-        public static void Test(string constr, string dstTable)
-        {
-            string srctable = "[" + dstTable + " src]";
-            dstTable = "[" + dstTable + "]";
-
-            string[] epilogue = {
-                "create table " + srctable + "([col 1] int primary key, [col 2] text)",
-                "insert into " + srctable + " values (33, 'Michael')",
-                "create table " + dstTable + "([col 1] int primary key, [col 2] text)",
-            };
-            string[] prologue = {
-                "drop table  " + srctable,
-                "drop table  " + dstTable,
-            };
-
-            using (SqlConnection dstConn = new SqlConnection(constr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.ProcessCommandBatch(typeof(SqlConnection), constr, epilogue);
-
-                    using (SqlConnection srcConn = new SqlConnection(constr))
-                    using (SqlCommand srcCmd = new SqlCommand(string.Format("select * from {0} ", srctable), srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-                                ColumnMappings.Add("[col 1]", "col 1");
-                                ColumnMappings.Add("col 2", "[col 2]");
-
-                                bulkcopy.WriteToServer(reader);
-                            }
-
-                            Helpers.VerifyResults(dstConn, dstTable, 2, 1);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.ProcessCommandBatch(typeof(SqlConnection), constr, prologue);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CheckConstraints.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CheckConstraints.cs
deleted file mode 100644 (file)
index ca4ac9d..0000000
+++ /dev/null
@@ -1,64 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CheckConstraints
-    {
-        public static void Test(string constr, string srctable, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(constr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    // create the source table
-                    Helpers.TryExecute(dstCmd, "create table " + srctable + " (col1 int , col2 int, col3 text)");
-                    Helpers.TryExecute(dstCmd, "insert into " + srctable + " values (33, 498, 'Michael')");
-                    Helpers.TryExecute(dstCmd, "insert into " + srctable + " values (34, 499, 'Astrid')");
-                    Helpers.TryExecute(dstCmd, "insert into " + srctable + " values (65, 500, 'alles K\u00E4se')");
-
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int primary key, col2 int CONSTRAINT CK_" + dstTable + " CHECK (col2 < 500), col3 text)");
-
-                    using (SqlConnection srcConn = new SqlConnection(constr))
-                    using (SqlCommand srcCmd = new SqlCommand("select * from " + srctable, srcConn))
-                    {
-                        srcConn.Open();
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            try
-                            {
-                                using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.CheckConstraints, null))
-                                {
-                                    bulkcopy.DestinationTableName = dstTable;
-                                    SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                                    ColumnMappings.Add("col1", "col1");
-                                    ColumnMappings.Add("col2", "col2");
-                                    ColumnMappings.Add("col3", "col3");
-                                    bulkcopy.WriteToServer(reader);
-                                }
-                            }
-                            catch (SqlException sqlEx)
-                            {
-                                // Error 547 == The %ls statement conflicted with the %ls constraint "%.*ls".
-                                DataTestUtility.AssertEqualsWithDescription(547, sqlEx.Number, "Unexpected error number.");
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                    Helpers.TryExecute(dstCmd, "drop table " + srctable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/ColumnCollation.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/ColumnCollation.cs
deleted file mode 100644 (file)
index 1c768b7..0000000
+++ /dev/null
@@ -1,64 +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.Data;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class ColumnCollation
-    {
-        public static void Test(string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                Helpers.TryExecute(dstCmd, "create table " + dstTable + " (name_jp varchar(20) collate Japanese_CI_AS, " +
-                    "name_ru varchar(20) collate Cyrillic_General_CI_AS)");
-
-                string s_jp = "\u6C5F\u6238\u7CF8\u3042\u3084\u3064\u308A\u4EBA\u5F62";
-                string s_ru = "\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430";
-
-                DataTable table = new DataTable();
-                table.Columns.Add("name_jp", typeof(string));
-                table.Columns.Add("name_ru", typeof(string));
-                DataRow row = table.NewRow();
-                row["name_jp"] = s_jp;
-                row["name_ru"] = s_ru;
-                table.Rows.Add(row);
-
-                using (SqlBulkCopy bcp = new SqlBulkCopy(dstConn))
-                {
-                    bcp.DestinationTableName = dstTable;
-                    bcp.WriteToServer(table);
-                }
-
-                using (SqlDataReader reader = (new SqlCommand("select * from  " + dstTable, dstConn)).ExecuteReader())
-                {
-                    while (reader.Read())
-                    {
-                        DataTestUtility.AssertEqualsWithDescription(
-                            0, string.CompareOrdinal(s_jp, reader["name_jp"] as string),
-                            "Unexpected value: " + reader["name_jp"]);
-
-                        DataTestUtility.AssertEqualsWithDescription(
-                            0, string.CompareOrdinal(s_ru, reader["name_ru"] as string),
-                            "Unexpected value: " + reader["name_ru"]);
-                    }
-                }
-
-            }
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-            }
-        }
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReader.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReader.cs
deleted file mode 100644 (file)
index e445743..0000000
+++ /dev/null
@@ -1,83 +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;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyAllFromReader
-    {
-        private static readonly string destinationTable = null;
-        private static readonly string sourceTable = "employees";
-        private static readonly string initialQueryTemplate = "create table {0} (col1 int, col2 nvarchar(20), col3 nvarchar(10))";
-        private static readonly string sourceQueryTemplate = "select top 5 EmployeeID, LastName, FirstName from {0}";
-
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            Debug.Assert((int)SqlBulkCopyOptions.UseInternalTransaction == 1 << 5, "Compiler screwed up the options");
-
-            dstTable = destinationTable != null ? destinationTable : dstTable;
-
-            string sourceQuery = string.Format(sourceQueryTemplate, sourceTable);
-            string initialQuery = string.Format(initialQueryTemplate, dstTable);
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, initialQuery);
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            IDictionary stats;
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-                                dstConn.StatisticsEnabled = true;
-                                bulkcopy.WriteToServer(reader);
-                                dstConn.StatisticsEnabled = false;
-                                stats = dstConn.RetrieveStatistics();
-                            }
-                            Helpers.VerifyResults(dstConn, dstTable, 3, 5);
-
-                            Assert.True(0 < (long)stats["BytesReceived"], "BytesReceived is non-positive.");
-                            Assert.True(0 < (long)stats["BytesSent"], "BytesSent is non-positive.");
-                            Assert.True((long)stats["ConnectionTime"] >= (long)stats["ExecutionTime"], "Connection Time is less than Execution Time.");
-                            Assert.True((long)stats["ExecutionTime"] >= (long)stats["NetworkServerTime"], "Execution Time is less than Network Server Time.");
-                            DataTestUtility.AssertEqualsWithDescription((long)0, (long)stats["UnpreparedExecs"], "Non-zero UnpreparedExecs value: " + (long)stats["UnpreparedExecs"]);
-                            DataTestUtility.AssertEqualsWithDescription((long)0, (long)stats["PreparedExecs"], "Non-zero PreparedExecs value: " + (long)stats["PreparedExecs"]);
-                            DataTestUtility.AssertEqualsWithDescription((long)0, (long)stats["Prepares"], "Non-zero Prepares value: " + (long)stats["Prepares"]);
-                            DataTestUtility.AssertEqualsWithDescription((long)0, (long)stats["CursorOpens"], "Non-zero CursorOpens value: " + (long)stats["CursorOpens"]);
-                            DataTestUtility.AssertEqualsWithDescription((long)0, (long)stats["IduRows"], "Non-zero IduRows value: " + (long)stats["IduRows"]);
-
-                            DataTestUtility.AssertEqualsWithDescription((long)4, stats["BuffersReceived"], "Unexpected BuffersReceived value.");
-                            DataTestUtility.AssertEqualsWithDescription((long)3, stats["BuffersSent"], "Unexpected BuffersSent value.");
-                            DataTestUtility.AssertEqualsWithDescription((long)0, stats["IduCount"], "Unexpected IduCount value.");
-                            DataTestUtility.AssertEqualsWithDescription((long)3, stats["SelectCount"], "Unexpected SelectCount value.");
-                            DataTestUtility.AssertEqualsWithDescription((long)3, stats["ServerRoundtrips"], "Unexpected ServerRoundtrips value.");
-                            DataTestUtility.AssertEqualsWithDescription((long)4, stats["SelectRows"], "Unexpected SelectRows value.");
-                            DataTestUtility.AssertEqualsWithDescription((long)2, stats["SumResultSets"], "Unexpected SumResultSets value.");
-                            DataTestUtility.AssertEqualsWithDescription((long)0, stats["Transactions"], "Unexpected Transactions value.");
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReader1.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReader1.cs
deleted file mode 100644 (file)
index e52a43b..0000000
+++ /dev/null
@@ -1,51 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyAllFromReader1
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 * from employees", srcConn))
-                    {
-                        srcConn.Open();
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                                ColumnMappings.Add("EmployeeID", "col1");
-                                ColumnMappings.Add("LastName", "col2");
-                                ColumnMappings.Add("FirstName", "col3");
-
-                                bulkcopy.WriteToServer(reader);
-                            }
-                            Helpers.VerifyResults(dstConn, dstTable, 3, 5);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderAsync.cs
deleted file mode 100644 (file)
index fb686be..0000000
+++ /dev/null
@@ -1,69 +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;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyAllFromReaderAsync
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            // Use this semaphore to ensure that results are written to the log in the correct order
-            SemaphoreSlim outputSemaphore = new SemaphoreSlim(0, 1);
-
-            Task t = TestAsync(srcConstr, dstConstr, dstTable, outputSemaphore);
-            outputSemaphore.Release();
-            t.Wait();
-            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
-        }
-
-        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable, SemaphoreSlim outputSemaphore)
-        {
-            string initialQueryTemplate = "create table {0} (col1 int, col2 nvarchar(20), col3 nvarchar(10))";
-            string sourceQueryTemplate = "select top 5 EmployeeID, LastName, FirstName from {0}";
-            string srcTable = "employees";
-
-            string sourceQuery = string.Format(sourceQueryTemplate, srcTable);
-            string initialQuery = string.Format(initialQueryTemplate, dstTable);
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, initialQuery);
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
-                    {
-                        srcConn.Open();
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-
-                                await bulkcopy.WriteToServerAsync(reader);
-                            }
-                            await outputSemaphore.WaitAsync();
-                            Helpers.VerifyResults(dstConn, dstTable, 3, 5);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderCancelAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderCancelAsync.cs
deleted file mode 100644 (file)
index 15f772c..0000000
+++ /dev/null
@@ -1,66 +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;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyAllFromReaderCancelAsync
-    {
-        static CancellationTokenSource cts = null;
-
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            cts = new CancellationTokenSource();
-            cts.Cancel();
-            Task t = TestAsync(srcConstr, dstConstr, dstTable, cts.Token);
-            DataTestUtility.AssertThrowsWrapper<AggregateException, TaskCanceledException>(() => t.Wait());
-            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
-        }
-
-        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable, CancellationToken ctoken)
-        {
-            string initialQueryTemplate = "create table {0} (col1 int, col2 nvarchar(20), col3 nvarchar(10))";
-            string sourceQueryTemplate = "select top 5 EmployeeID, LastName, FirstName from {0}";
-            string srcTable = "employees";
-
-            string sourceQuery = string.Format(sourceQueryTemplate, srcTable);
-            string initialQuery = string.Format(initialQueryTemplate, dstTable);
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, initialQuery);
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            await bulkcopy.WriteToServerAsync(reader, ctoken);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseAsync.cs
deleted file mode 100644 (file)
index 8e0c3ec..0000000
+++ /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.Collections;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyAllFromReaderConnectionClosedAsync
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            Task t = TestAsync(srcConstr, dstConstr, dstTable);
-            DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => t.Wait());
-            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
-        }
-
-        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable)
-        {
-            string initialQueryTemplate = "create table {0} (col1 int, col2 nvarchar(20), col3 nvarchar(10))";
-            string sourceQueryTemplate = "select top 5 EmployeeID, LastName, FirstName from {0}";
-            string sourceTable = "employees";
-
-            string sourceQuery = string.Format(sourceQueryTemplate, sourceTable);
-            string initialQuery = string.Format(initialQueryTemplate, dstTable);
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, initialQuery);
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            dstConn.Close();
-                            await bulkcopy.WriteToServerAsync(reader);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryDropTable(dstConstr, dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseOnEventAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyAllFromReaderConnectionCloseOnEventAsync.cs
deleted file mode 100644 (file)
index 23bf51c..0000000
+++ /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.Collections;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Diagnostics;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyAllFromReaderConnectionClosedOnEventAsync
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-#if DEBUG
-            string initialQueryTemplate = "create table {0} (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 varchar(8000))";
-            string sourceQuery = "select EmployeeID, LastName, FirstName, REPLICATE('a', 8000) from employees";
-            string initialQuery = string.Format(initialQueryTemplate, dstTable);
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, initialQuery);
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-
-                                // Close the bulk copy's connection when it notifies us
-                                bulkcopy.NotifyAfter = 1;
-                                bulkcopy.SqlRowsCopied += (sender, e) =>
-                                {
-                                    dstConn.Close();
-                                };
-
-                                using (AsyncDebugScope debugScope = new AsyncDebugScope())
-                                {
-                                    // Force all writes to pend, this will guarantee that we will go through the correct code path
-                                    debugScope.ForceAsyncWriteDelay = 1;
-
-                                    // Check that the copying fails
-                                    string message = string.Format(SystemDataResourceManager.Instance.ADP_OpenConnectionRequired, "WriteToServer", SystemDataResourceManager.Instance.ADP_ConnectionStateMsg_Closed);
-                                    DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => bulkcopy.WriteToServerAsync(reader).Wait(5000), innerExceptionMessage: message);
-                                }
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryDropTable(dstConstr, dstTable);
-                }
-            }
-#endif
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyMultipleReaders.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyMultipleReaders.cs
deleted file mode 100644 (file)
index 241ca85..0000000
+++ /dev/null
@@ -1,64 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyMultipleReaders
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = srcConn.CreateCommand())
-                    {
-                        srcConn.Open();
-
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            srcCmd.CommandText = "select EmployeeID, LastName from employees where LastName < 'E%'";
-                            using (DbDataReader reader = srcCmd.ExecuteReader())
-                            {
-                                bulkcopy.WriteToServer(reader);
-                            }
-                            DataTestUtility.AssertEqualsWithDescription(0, bulkcopy.ColumnMappings.Count, "Unexpected ColumnMappings count.");
-
-                            srcCmd.CommandText = "select EmployeeID, LastName, FirstName from employees where LastName > 'D%'";
-                            using (DbDataReader reader = srcCmd.ExecuteReader())
-                            {
-                                bulkcopy.WriteToServer(reader);
-                            }
-                            DataTestUtility.AssertEqualsWithDescription(0, bulkcopy.ColumnMappings.Count, "Unexpected ColumnMappings count.");
-
-                            srcCmd.CommandText = "select EmployeeID, FirstName from employees where LastName < 'E%'";
-                            using (DbDataReader reader = srcCmd.ExecuteReader())
-                            {
-                                bulkcopy.WriteToServer(reader);
-                            }
-                            DataTestUtility.AssertEqualsWithDescription(0, bulkcopy.ColumnMappings.Count, "Unexpected ColumnMappings count.");
-
-                            Helpers.VerifyResults(dstConn, dstTable, 3, 15);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromDatatable.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromDatatable.cs
deleted file mode 100644 (file)
index 0e85a83..0000000
+++ /dev/null
@@ -1,75 +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.Data;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopySomeFromDataTable
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            DataSet dataset;
-            SqlDataAdapter adapter;
-            DataTable datatable;
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 datetime)");
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select * from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        dataset = new DataSet("MyDataSet");
-                        adapter = new SqlDataAdapter(srcCmd);
-                        adapter.Fill(dataset);
-                        datatable = dataset.Tables[0];
-
-                        string columnname;
-
-                        foreach (DataColumn column in datatable.Columns)
-                        {
-                            columnname = column.ColumnName;
-                        }
-
-                        datatable.Rows[0].BeginEdit();
-                        datatable.Rows[0][0] = 333;
-                        datatable.Rows[0].EndEdit();
-
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            bulkcopy.BatchSize = 7;
-
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            ColumnMappings.Add(0, "col1");
-                            ColumnMappings.Add(1, "col2");
-                            ColumnMappings.Add(2, "col3");
-                            bulkcopy.WriteToServer(datatable, DataRowState.Unchanged);
-                            datatable.Rows.GetEnumerator().Reset();
-                            bulkcopy.WriteToServer(datatable, DataRowState.Modified);
-                            datatable.Rows.GetEnumerator().Reset();
-                            bulkcopy.WriteToServer(datatable, DataRowState.Deleted);
-                            bulkcopy.Close();
-                        }
-
-                        Helpers.VerifyResults(dstConn, dstTable, 4, 18);
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromDatatableAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromDatatableAsync.cs
deleted file mode 100644 (file)
index 524fc19..0000000
+++ /dev/null
@@ -1,83 +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.Data;
-using System.Data.SqlClient;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopySomeFromDataTableAsync
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            // Use this semaphore to ensure that results are written to the log in the correct order
-            SemaphoreSlim outputSemaphore = new SemaphoreSlim(0, 1);
-
-            Task t = TestAsync(srcConstr, dstConstr, dstTable, outputSemaphore);
-            outputSemaphore.Release();
-            t.Wait();
-            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
-        }
-
-        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable, SemaphoreSlim outputSemaphore)
-        {
-            DataSet dataset;
-            SqlDataAdapter adapter;
-            DataTable datatable;
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 datetime)");
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select * from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        dataset = new DataSet("MyDataSet");
-                        adapter = new SqlDataAdapter(srcCmd);
-                        adapter.Fill(dataset);
-                        datatable = dataset.Tables[0];
-
-                        datatable.Rows[0].BeginEdit();
-                        datatable.Rows[0][0] = 333;
-                        datatable.Rows[0].EndEdit();
-
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            bulkcopy.BatchSize = 7;
-
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            ColumnMappings.Add(0, "col1");
-                            ColumnMappings.Add(1, "col2");
-                            ColumnMappings.Add(2, "col3");
-                            bulkcopy.WriteToServer(datatable, DataRowState.Unchanged);
-                            datatable.Rows.GetEnumerator().Reset();
-                            await bulkcopy.WriteToServerAsync(datatable, DataRowState.Modified);
-                            datatable.Rows.GetEnumerator().Reset();
-                            await bulkcopy.WriteToServerAsync(datatable, DataRowState.Deleted);
-                            bulkcopy.Close();
-                        }
-
-                        await outputSemaphore.WaitAsync();
-                        Helpers.VerifyResults(dstConn, dstTable, 4, 18);
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromReader.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromReader.cs
deleted file mode 100644 (file)
index 8acdb7e..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopySomeFromReader
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 datetime)");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select * from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-                                bulkcopy.BatchSize = 6;
-
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                                ColumnMappings.Add("EmployeeID", "col1");
-                                ColumnMappings.Add("BirthDate", "col4");
-                                ColumnMappings.Add("FirstName", "col2");
-                                ColumnMappings.Add("LastName", "col3");
-
-                                bulkcopy.WriteToServer(reader);
-                            }
-                            Helpers.VerifyResults(dstConn, dstTable, 4, 9);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromRowArray.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromRowArray.cs
deleted file mode 100644 (file)
index 22feaf9..0000000
+++ /dev/null
@@ -1,66 +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.Data;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopySomeFromRowArray
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            DataSet dataset;
-            SqlDataAdapter adapter;
-            DataTable datatable;
-            DataRow[] rows;
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 datetime)");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select * from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        dataset = new DataSet("MyDataSet");
-                        adapter = new SqlDataAdapter(srcCmd);
-                        adapter.Fill(dataset);
-                        datatable = dataset.Tables[0];
-                        rows = new DataRow[datatable.Rows.Count];
-                        for (int i = 0; i < rows.Length; i++)
-                        {
-                            rows[i] = datatable.Rows[i];
-                        }
-
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            bulkcopy.BatchSize = 4;
-
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            ColumnMappings.Add(0, "col1");
-                            ColumnMappings.Add(2, "col3");
-
-                            bulkcopy.WriteToServer(rows);
-                            bulkcopy.Close();
-                        }
-                        Helpers.VerifyResults(dstConn, dstTable, 4, 9);
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromRowArrayAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopySomeFromRowArrayAsync.cs
deleted file mode 100644 (file)
index 6a95295..0000000
+++ /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.Data;
-using System.Data.SqlClient;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopySomeFromRowArrayAsync
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            // Use this semaphore to ensure that results are written to the log in the correct order
-            SemaphoreSlim outputSemaphore = new SemaphoreSlim(0, 1);
-
-            Task t = TestAsync(srcConstr, dstConstr, dstTable, outputSemaphore);
-            outputSemaphore.Release();
-            t.Wait();
-            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
-        }
-
-        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable, SemaphoreSlim outputSemaphore)
-        {
-            DataSet dataset;
-            SqlDataAdapter adapter;
-            DataTable datatable;
-            DataRow[] rows;
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 datetime)");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select * from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        dataset = new DataSet("MyDataSet");
-                        adapter = new SqlDataAdapter(srcCmd);
-                        adapter.Fill(dataset);
-                        datatable = dataset.Tables[0];
-                        rows = new DataRow[datatable.Rows.Count];
-                        for (int i = 0; i < rows.Length; i++)
-                        {
-                            rows[i] = datatable.Rows[i];
-                        }
-
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            bulkcopy.BatchSize = 4;
-
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            ColumnMappings.Add(0, "col1");
-                            ColumnMappings.Add(2, "col3");
-
-                            await bulkcopy.WriteToServerAsync(rows);
-                            bulkcopy.Close();
-                        }
-                        await outputSemaphore.WaitAsync();
-                        Helpers.VerifyResults(dstConn, dstTable, 4, 9);
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyVariants.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyVariants.cs
deleted file mode 100644 (file)
index 614b745..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyVariants
-    {
-        public static void Test(string constr, string dstTable)
-        {
-            string[] prologue =
-            {
-                "create table " + dstTable + "_src (col_1 int primary key, col_2 sql_variant)",
-
-                "insert into " + dstTable + "_src values (0, null)",
-                "insert into " + dstTable + "_src values (1, convert(int, 0))",
-                "insert into " + dstTable + "_src values (2, convert(smallint, -32768))",
-                "insert into " + dstTable + "_src values (3, convert(real, 2.2))",
-                "insert into " + dstTable + "_src values (4, convert(float, -3303.33303))",
-                "insert into " + dstTable + "_src values (5, convert(decimal(28,4), 44404.4404))",
-                "insert into " + dstTable + "_src values (6, convert(money, $555505.5505) )",
-                "insert into " + dstTable + "_src values (7, convert(smallmoney, $-6.6606) )",
-                "insert into " + dstTable + "_src values (8, convert(bit, 1) )",
-                "insert into " + dstTable + "_src values (9, convert(tinyint, 8) )",
-                "insert into " + dstTable + "_src values (10, convert(uniqueidentifier, '00000000-0000-0000-0000-000000000009') )",
-                "insert into " + dstTable + "_src values (11, convert(varbinary(756), 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0A) )",
-                "insert into " + dstTable + "_src values (12, convert(varchar(756), '111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111101') )",
-                "insert into " + dstTable + "_src values (13, convert(nvarchar(756), N'???a???????????????????????????????\u00FCb\u00F6ua\u00E4Z\u00DFABC\u00C4bo\u00DCOU\u00D6vrh\u00C3\u00E3??z?????????????????z?????????A?????a???????????????????????????????\u00FCb\u00F6ua\u00E4Z\u00DFABC\u00C4bo\u00DCOU\u00D6vrh\u00C3\u00E3??z?????????????????z?????????A?????a???????????????????????????????\u00FCb\u00F6ua\u00E4Z\u00DFABC\u00C4bo\u00DCOU\u00D6vrh\u00C3\u00E3??z?????????????????z?????????A?????a???????????????????????????????\u00FCb\u00F6ua\u00E4Z\u00DFABC\u00C4bo\u00DCOU\u00D6vrh\u00C3\u00E3??z?????????????????z?????????A?????a?????') )",
-                "insert into " + dstTable + "_src values (14, convert(datetime, {ts '2003-01-11 12:54:01.133'}) )",
-                "insert into " + dstTable + "_src values (15, convert(bigint, 444444444444404) )",
-                "insert into " + dstTable + "_src values (16, convert(int, -555505) )",
-                "insert into " + dstTable + "_src values (17, convert(smallint, 16) )",
-                "insert into " + dstTable + "_src values (18, convert(real, 777707.7) )",
-                "insert into " + dstTable + "_src values (19, convert(float, -888888808.88018) )",
-                "insert into " + dstTable + "_src values (20, convert(decimal(28,4), 99999999999999999909.9019) )",
-
-                "create table " + dstTable + "_dst (col_1 int primary key, col_2 sql_variant)",
-            };
-
-            using (SqlConnection dstConn = new SqlConnection(constr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    foreach (string cmdtext in prologue)
-                    {
-                        Helpers.TryExecute(dstCmd, cmdtext);
-                    }
-                    using (SqlConnection srcConn = new SqlConnection(constr))
-                    using (SqlCommand srcCmd = new SqlCommand("select * from " + dstTable + "_src", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable + "_dst";
-                                bulkcopy.WriteToServer(reader);
-                            }
-                            Helpers.VerifyResults(dstConn, dstTable + "_dst", 2, 21);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable + "_src");
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable + "_dst");
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWidenNullInexactNumerics.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWidenNullInexactNumerics.cs
deleted file mode 100644 (file)
index 27c59b0..0000000
+++ /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.Collections.Generic;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyWidenNullInexactNumerics
-    {
-        public static void Test(string sourceDatabaseConnectionString, string destinationDatabaseConnectionString)
-        {
-            // this test copies float and real inexact numeric types into decimal targets using bulk copy to check that the widening of the type succeeds.
-
-            using (var sourceConnection = new SqlConnection(sourceDatabaseConnectionString))
-            using (var destinationConnection = new SqlConnection(destinationDatabaseConnectionString))
-            {
-                sourceConnection.Open();
-                destinationConnection.Open();
-
-                RunCommands(sourceConnection,
-                    new[]
-                    {
-                        "drop table if exists dbo.__SqlBulkCopyBug_Source",
-                        "create table dbo.__SqlBulkCopyBug_Source (floatVal float null, realVal real null)",
-                        "insert dbo.__SqlBulkCopyBug_Source(floatVal,realVal) values(1,1),(2,2),(null,null),(0.00000000000001,0.00000000000001)"
-                    }
-                );
-
-                RunCommands(destinationConnection,
-                    new[]
-                    {
-                        "drop table if exists dbo.__SqlBulkCopyBug_Destination",
-                        "create table dbo.__SqlBulkCopyBug_Destination (floatVal decimal(18,10) null,realVal decimal(18,10) null)"
-                    }
-                );
-
-                Exception error = null;
-                try
-                {
-                    var bulkCopy = new SqlBulkCopy(destinationConnection, SqlBulkCopyOptions.Default, null);
-                    bulkCopy.DestinationTableName = "dbo.__SqlBulkCopyBug_Destination";
-                    using (var sourceCommand = new SqlCommand("select * from dbo.__SqlBulkCopyBug_Source", sourceConnection, null))
-                    using (var sourceReader = sourceCommand.ExecuteReader())
-                    {
-                        bulkCopy.WriteToServer(sourceReader);
-                    }
-                }
-                catch (Exception ex)
-                {
-                    error = ex;
-                }
-                finally
-                {
-                    try
-                    {
-                        RunCommands(sourceConnection,
-                            new[]
-                            {
-                                "drop table if exists dbo.__SqlBulkCopyBug_Source",
-                                "drop table if exists dbo.__SqlBulkCopyBug_Destination",
-                            }
-                        );
-                    }
-                    catch
-                    {
-                    }
-                }
-
-                Assert.Null(error);
-            }
-        }
-
-        public static void RunCommands(SqlConnection connection, IEnumerable<string> commands)
-        {
-            using (var sqlCommand = connection.CreateCommand())
-            {
-                foreach (var command in commands)
-                {
-                    Helpers.TryExecute(sqlCommand, command);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent.cs
deleted file mode 100644 (file)
index 8d5f5ba..0000000
+++ /dev/null
@@ -1,82 +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.Data;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyWithEvent
-    {
-        private static readonly long[] ExpectedRowCopiedResults = { 50, 100 };
-        private static int currentRowCopyResult = 0;
-
-        protected static void OnRowCopied(object sender, SqlRowsCopiedEventArgs e)
-        {
-            Assert.True(currentRowCopyResult < ExpectedRowCopiedResults.Length, "More row copies than expected!");
-            DataTestUtility.AssertEqualsWithDescription(ExpectedRowCopiedResults[currentRowCopyResult++], e.RowsCopied, "Unexpected Rows Copied count.");
-        }
-
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            DataSet dataset;
-            SqlDataAdapter adapter;
-            DataTable datatable;
-            DataRow[] rows;
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (orderid int, customerid nchar(5), rdate datetime, freight money, shipname nvarchar(40))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 100 * from orders", srcConn))
-                    {
-                        srcConn.Open();
-
-                        dataset = new DataSet("MyDataSet");
-                        adapter = new SqlDataAdapter(srcCmd);
-                        adapter.Fill(dataset);
-                        datatable = dataset.Tables[0];
-                        rows = new DataRow[datatable.Rows.Count];
-                        for (int i = 0; i < rows.Length; i++)
-                        {
-                            rows[i] = datatable.Rows[i];
-                        }
-                    }
-
-                    using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                    {
-
-                        bulkcopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnRowCopied);
-
-                        bulkcopy.DestinationTableName = dstTable;
-                        bulkcopy.NotifyAfter = 50;
-
-                        SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                        ColumnMappings.Add(0, "orderid");
-                        ColumnMappings.Add(1, "customerid");
-                        ColumnMappings.Add(4, "rdate");
-                        ColumnMappings.Add(7, "freight");
-                        ColumnMappings.Add(8, "shipname");
-
-                        bulkcopy.WriteToServer(rows);
-                        bulkcopy.SqlRowsCopied -= new SqlRowsCopiedEventHandler(OnRowCopied);
-                    }
-                    Helpers.VerifyResults(dstConn, dstTable, 5, 100);
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent1.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEvent1.cs
deleted file mode 100644 (file)
index 863f997..0000000
+++ /dev/null
@@ -1,84 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyWithEvent1
-    {
-        private static SqlBulkCopy bulkcopy;
-
-        private static readonly long[] ExpectedRowCopiedResults = { 50, 100 };
-        private static int currentRowCopyResult = 0;
-
-        private static void OnRowCopied(object sender, SqlRowsCopiedEventArgs e)
-        {
-            Assert.True(currentRowCopyResult < ExpectedRowCopiedResults.Length, "More row copies than expected!");
-            DataTestUtility.AssertEqualsWithDescription(ExpectedRowCopiedResults[currentRowCopyResult++], e.RowsCopied, "Unexpected Rows Copied count.");
-
-            if (e.RowsCopied > 50)
-            {
-                e.Abort = true; // Abort batch
-            }
-            else if (e.RowsCopied > 60)
-            {
-                bulkcopy.NotifyAfter = 0; // switch off notification
-            }
-            else if (e.RowsCopied > 3)
-            {
-                bulkcopy.NotifyAfter = 10; // decrease notification frequency
-            }
-        }
-
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (orderid int, customerid nchar(5), rdate datetime, freight money, shipname nvarchar(40))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 100 * from orders", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, null))
-                        {
-                            bulkcopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnRowCopied);
-
-                            bulkcopy.DestinationTableName = dstTable;
-                            bulkcopy.NotifyAfter = 50;
-
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            ColumnMappings.Add("OrderID", "orderid");
-                            ColumnMappings.Add("CustomerID", "customerid");
-                            ColumnMappings.Add("RequiredDate", "rdate");
-                            ColumnMappings.Add("Freight", "freight");
-                            ColumnMappings.Add("ShipName", "shipname");
-
-                            bulkcopy.NotifyAfter = 3;
-                            DataTestUtility.AssertThrowsWrapper<OperationAbortedException>(() => bulkcopy.WriteToServer(reader));
-                            bulkcopy.SqlRowsCopied -= new SqlRowsCopiedEventHandler(OnRowCopied);
-                            bulkcopy.Close();
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEventAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/CopyWithEventAsync.cs
deleted file mode 100644 (file)
index 05ad44a..0000000
+++ /dev/null
@@ -1,96 +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.Data;
-using System.Data.SqlClient;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class CopyWithEventAsync
-    {
-        private static readonly long[] ExpectedRowCopiedResults = { 50, 100 };
-        private static int currentRowCopyResult = 0;
-
-        private static void OnRowCopied(object sender, SqlRowsCopiedEventArgs e)
-        {
-            Assert.True(currentRowCopyResult < ExpectedRowCopiedResults.Length, "More row copies than expected!");
-            DataTestUtility.AssertEqualsWithDescription(ExpectedRowCopiedResults[currentRowCopyResult++], e.RowsCopied, "Unexpected Rows Copied count.");
-        }
-
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            // Use this semaphore to ensure that results are written to the log in the correct order
-            SemaphoreSlim outputSemaphore = new SemaphoreSlim(0, 1);
-
-            Task t = TestAsync(srcConstr, dstConstr, dstTable, outputSemaphore);
-            outputSemaphore.Release();
-            t.Wait();
-            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
-        }
-
-        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable, SemaphoreSlim outputSemaphore)
-        {
-            DataSet dataset;
-            SqlDataAdapter adapter;
-            DataTable datatable;
-            DataRow[] rows;
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (orderid int, customerid nchar(5), rdate datetime, freight money, shipname nvarchar(40))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 100 * from orders", srcConn))
-                    {
-                        srcConn.Open();
-
-                        dataset = new DataSet("MyDataSet");
-                        adapter = new SqlDataAdapter(srcCmd);
-                        adapter.Fill(dataset);
-                        datatable = dataset.Tables[0];
-                        rows = new DataRow[datatable.Rows.Count];
-                        for (int i = 0; i < rows.Length; i++)
-                        {
-                            rows[i] = datatable.Rows[i];
-                        }
-                    }
-
-                    using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                    {
-
-                        bulkcopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnRowCopied);
-
-                        bulkcopy.DestinationTableName = dstTable;
-                        bulkcopy.NotifyAfter = 50;
-
-                        SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                        ColumnMappings.Add(0, "orderid");
-                        ColumnMappings.Add(1, "customerid");
-                        ColumnMappings.Add(4, "rdate");
-                        ColumnMappings.Add(7, "freight");
-                        ColumnMappings.Add(8, "shipname");
-
-                        await bulkcopy.WriteToServerAsync(rows);
-                        bulkcopy.SqlRowsCopied -= new SqlRowsCopiedEventHandler(OnRowCopied);
-                    }
-                    await outputSemaphore.WaitAsync();
-                    Helpers.VerifyResults(dstConn, dstTable, 5, 100);
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/ErrorOnRowsMarkedAsDeleted.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/ErrorOnRowsMarkedAsDeleted.cs
deleted file mode 100644 (file)
index e481fb6..0000000
+++ /dev/null
@@ -1,151 +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.Data;
-using System.Data.SqlClient;
-using System.Text;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    /// <summary>
-    /// Test case for SqlBulkEdit raising exception on rows marked as deleted
-    /// </summary>
-    public class ErrorOnRowsMarkedAsDeleted
-    {
-        // This char is used to mark the row as 'to be deleted'.
-        // See RunCase lines below
-        const char DeletedRowMark = 'D';
-
-        /// <summary>
-        /// specifies which overload of WriteToServer we want to test
-        /// </summary>
-        enum SqlBulkCopyInputType
-        {
-            DataTable,
-            RowsList
-        }
-
-        public static void Test(string dstConstr, string targettable)
-        {
-            using (SqlConnection destConn = new SqlConnection(dstConstr))
-            {
-                destConn.Open();
-
-                string tablePrefix = targettable.Replace(' ', '_') + "_Case";
-                int tableIdx = 1;
-
-                // run several cases, using DataTable or RowsList as an input method
-                // no need to duplicate tests since from dev point they are sharing the same code
-                RunCase(destConn, "empty table", SqlBulkCopyInputType.DataTable, tablePrefix + (tableIdx++), "D");
-                RunCase(destConn, "single deleted row", SqlBulkCopyInputType.RowsList, tablePrefix + (tableIdx++), "D");
-                RunCase(destConn, "deleted row is first", SqlBulkCopyInputType.DataTable, tablePrefix + (tableIdx++), "DRR");
-                RunCase(destConn, "deleted row is last", SqlBulkCopyInputType.RowsList, tablePrefix + (tableIdx++), "RRD");
-                RunCase(destConn, "continues deleted rows", SqlBulkCopyInputType.DataTable, tablePrefix + (tableIdx++), "RDDDDR");
-                RunCase(destConn, "deleted row is in the middle", SqlBulkCopyInputType.RowsList, tablePrefix + (tableIdx++), "RDR");
-                RunCase(destConn, "empty table", SqlBulkCopyInputType.DataTable, tablePrefix + (tableIdx++), "");
-                RunCase(destConn, "no deleted rows", SqlBulkCopyInputType.RowsList, tablePrefix + (tableIdx++), "RR");
-                RunCase(destConn, "big bang", SqlBulkCopyInputType.DataTable, tablePrefix + (tableIdx++), "DRRDRRRDDDDDDDDRRDRDDRDRDDDRRD");
-            }
-        }
-
-        /// <summary>
-        /// runs single case: creates DataTable with some of the rows deleted, calls SqlBulkCopy on it and
-        /// validates the results
-        /// </summary>
-        /// <param name="conn"></param>
-        /// <param name="caseName"></param>
-        /// <param name="tableName"></param>
-        /// <param name="rows">rows map: 'N' means value = row index; 'D' means value is Deleted</param>
-        /// <returns>true on failure; false - otherwise</returns>
-        private static void RunCase(SqlConnection conn, string caseName, SqlBulkCopyInputType inputType, string tableName, string rowsMap)
-        {
-            // create simple table
-            DataTable table = new DataTable();
-            table.Columns.Add("IntVal", typeof(int));
-
-            // create the rows, each one contains one field:
-            // * the index of the row, if row stays
-            // * -1 if row is marked to be deleted
-
-            // row values has no meaning for the SqlBulkCopy, they are used for test output verification only
-            // at the same loop, create list of rows that expected to appear in the target table after bulk copy
-
-            StringBuilder expectedRows = new StringBuilder();
-            for (int i = 0; i < rowsMap.Length; i++)
-            {
-                if (rowsMap[i] == DeletedRowMark)
-                {
-                    // this row is to be deleted, mark with -1
-                    table.Rows.Add(-1);
-                }
-                else
-                {
-                    // this row should stay, use row index as value and add it to expected list
-                    table.Rows.Add(i);
-                    expectedRows.AppendFormat("{0} ", i);
-                }
-            }
-
-            table.AcceptChanges();
-
-            // mark the rows relevant for this case as deleted
-            DataRow[] rowsToDelete = table.Select("IntVal=-1");
-            for (int i = 0; i < rowsToDelete.Length; i++)
-            {
-                rowsToDelete[i].Delete();
-            }
-
-            // create SQL table with one int field, similar to the above DataTable
-            SqlCommand cmd = conn.CreateCommand();
-            cmd.CommandText = "CREATE TABLE [" + tableName + "] (IntVal int)";
-            cmd.ExecuteNonQuery();
-
-            try
-            {
-                using (SqlBulkCopy bcp = new SqlBulkCopy(conn))
-                {
-                    bcp.DestinationTableName = tableName;
-
-                    // run the test
-                    switch (inputType)
-                    {
-                        case SqlBulkCopyInputType.DataTable:
-                            bcp.WriteToServer(table);
-                            break;
-                        case SqlBulkCopyInputType.RowsList:
-                            DataRow[] rowsList = new DataRow[table.Rows.Count];
-                            table.Rows.CopyTo(rowsList, 0);
-                            bcp.WriteToServer(rowsList);
-                            break;
-                        default:
-                            throw new InvalidOperationException("How did we reach here?");
-                    }
-                }
-
-                // now, read the Actual Rows from SQL
-                StringBuilder actualRows = new StringBuilder();
-                cmd.CommandText = "SELECT * FROM [" + tableName + "]";
-                using (SqlDataReader r = cmd.ExecuteReader())
-                {
-                    while (r.Read())
-                    {
-                        int val = Convert.ToInt32(r[0]);
-                        actualRows.AppendFormat("{0} ", val);
-                    }
-                }
-
-                // compare the Expected and the Actual values
-                DataTestUtility.AssertEqualsWithDescription(expectedRows.ToString(), actualRows.ToString(), "Unexpected rows data for test case " + caseName);
-            }
-            finally
-            {
-                // delete the table
-                cmd = conn.CreateCommand();
-                cmd.CommandText = "DROP TABLE [" + tableName + "]";
-                cmd.ExecuteNonQuery();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/FireTrigger.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/FireTrigger.cs
deleted file mode 100644 (file)
index 90541f6..0000000
+++ /dev/null
@@ -1,77 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class FireTrigger
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            string dstTable1 = dstTable + "_1"; // this table will receive a value if the trigger fires!
-            string trigger = dstTable + "_2";
-            string[] prologue =
-            {
-                "create table " + dstTable + "(col1 int, col2 nvarchar(20), col3 nvarchar(10))",
-                "create table " + dstTable1 + "  (col1 int);",
-                "create trigger " + trigger + "  on " + dstTable + " for INSERT as insert into " + dstTable1 + "  values (333)"
-            };
-            string[] epilogue =
-            {
-                "drop table " + dstTable1 + " ",
-                "drop trigger " + trigger + " ",
-                "drop table " + dstTable
-            };
-
-            string sourceTable = "employees";
-            string sourceQueryTemplate = "select top 5 EmployeeID, LastName, FirstName from {0}";
-            string sourceQuery = string.Format(sourceQueryTemplate, sourceTable);
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                Helpers.ProcessCommandBatch(dstCmd, prologue);
-
-                try
-                {
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            SqlBulkCopyOptions option = SqlBulkCopyOptions.FireTriggers;
-
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, option, null))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-                                bulkcopy.WriteToServer(reader);
-                            }
-                        }
-
-                        dstCmd.CommandText = "select top 2 * from " + dstTable1 + " ";
-                        using (DbDataReader reader2 = dstCmd.ExecuteReader())
-                        {
-                            Assert.True(reader2.Read(), "Failed to read!");
-
-                            Assert.True(reader2[0] is int, "Unexpected Field(0) type: " + reader2[0].GetType());
-
-                            Assert.True((int)(reader2[0]) == 333, "Unexpected Field(0) value: " + reader2[0]);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.ProcessCommandBatch(dstCmd, epilogue);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Helpers.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Helpers.cs
deleted file mode 100644 (file)
index 659efc5..0000000
+++ /dev/null
@@ -1,99 +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.Data;
-using System.Data.Common;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Helpers
-    {
-        internal static void ProcessCommandBatch(Type connType, string constr, string[] batch)
-        {
-            if (batch.Length > 0)
-            {
-                object[] activatorArgs = new object[1];
-                activatorArgs[0] = constr;
-                using (DbConnection conn = (DbConnection)Activator.CreateInstance(connType, activatorArgs))
-                {
-                    conn.Open();
-                    DbCommand cmd = conn.CreateCommand();
-
-                    ProcessCommandBatch(cmd, batch);
-                }
-            }
-        }
-
-        internal static void ProcessCommandBatch(DbCommand cmd, string[] batch)
-        {
-            foreach (string cmdtext in batch)
-            {
-                Helpers.TryExecute(cmd, cmdtext);
-            }
-        }
-
-        public static int TryDropTable(string dstConstr, string tableName)
-        {
-            using (SqlConnection dropConn = new SqlConnection(dstConstr))
-            using (SqlCommand dropCmd = dropConn.CreateCommand())
-            {
-                dropConn.Open();
-                return Helpers.TryExecute(dropCmd, "drop table " + tableName);
-            }
-        }
-
-        public static int TryExecute(DbCommand cmd, string strText)
-        {
-            cmd.CommandText = strText;
-            return cmd.ExecuteNonQuery();
-        }
-
-        public static int ExecuteNonQueryAzure(string strConnectionString, string strCommand, int commandTimeout = 60)
-        {
-            using (SqlConnection connection = new SqlConnection(strConnectionString))
-            using (SqlCommand command = connection.CreateCommand())
-            {
-                connection.Open();
-                // We need to increase CommandTimeout else you might see the following error:
-                // "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
-                command.CommandTimeout = commandTimeout;
-                return Helpers.TryExecute(command, strCommand);
-            }
-        }
-
-        public static bool VerifyResults(DbConnection conn, string dstTable, int expectedColumns, int expectedRows)
-        {
-            using (DbCommand cmd = conn.CreateCommand())
-            {
-                cmd.CommandText = "select * from " + dstTable + "; select count(*) from " + dstTable;
-                using (DbDataReader reader = cmd.ExecuteReader())
-                {
-                    int numColumns = reader.FieldCount;
-                    reader.NextResult();
-                    reader.Read();
-                    int numRows = (int)reader[0];
-                    reader.Close();
-
-                    DataTestUtility.AssertEqualsWithDescription(expectedColumns, numColumns, "Unexpected number of columns.");
-                    DataTestUtility.AssertEqualsWithDescription(expectedRows, numRows, "Unexpected number of columns.");
-                }
-            }
-            return false;
-        }
-
-        public static bool CheckTableRows(DbConnection conn, string table, bool shouldHaveRows)
-        {
-            string query = "select * from " + table;
-            using (DbCommand cmd = conn.CreateCommand())
-            {
-                cmd.CommandText = query;
-                using (DbDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTestUtility.AssertEqualsWithDescription(shouldHaveRows, reader.HasRows, "Unexpected value for HasRows.");
-                }
-            }
-            return false;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs
deleted file mode 100644 (file)
index 71f17f8..0000000
+++ /dev/null
@@ -1,151 +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.Data;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class InvalidAccessFromEvent
-    {
-        private static string _dstConstr;
-        private static string _dstTable;
-        private static SqlConnection _dstConn;
-        private static SqlTransaction _tx;
-        private static SqlCommand _dstcmd;
-        private static DataTable _dataTable;
-        private static string expectedErrorMsg;
-
-        protected static void OnRowCopiedClose(object sender, SqlRowsCopiedEventArgs e)
-        {
-            _dstConn.Close();
-        }
-
-        protected static void OnRowCopiedExecute(object sender, SqlRowsCopiedEventArgs e)
-        {
-            _dstcmd.ExecuteNonQuery();
-        }
-
-        protected static void OnRowCopiedRollback(object sender, SqlRowsCopiedEventArgs e)
-        {
-            _tx.Rollback();
-        }
-
-        protected static void OnRowCopiedCommit(object sender, SqlRowsCopiedEventArgs e)
-        {
-            _tx.Commit();
-        }
-
-        protected static void OnRowCopiedChangeDatabase(object sender, SqlRowsCopiedEventArgs e)
-        {
-            _dstConn.ChangeDatabase("msdb");
-        }
-
-        protected static void OnRowCopiedBulkCopy(object sender, SqlRowsCopiedEventArgs e)
-        {
-            InnerTest(null);
-        }
-
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            _dstConstr = dstConstr;
-            _dstTable = dstTable;
-
-            DataSet dataset;
-            SqlDataAdapter adapter;
-
-            using (SqlConnection srcConn = new SqlConnection(srcConstr))
-            using (SqlCommand srcCmd = new SqlCommand("select top 20 * from orders", srcConn))
-            {
-                srcConn.Open();
-
-                dataset = new DataSet("MyDataSet");
-                adapter = new SqlDataAdapter(srcCmd);
-                adapter.Fill(dataset);
-                _dataTable = dataset.Tables[0];
-            }
-
-            using (_dstConn = new SqlConnection(dstConstr))
-            {
-                _dstConn.Open();
-                _dstcmd = _dstConn.CreateCommand();
-
-                try
-                {
-                    Helpers.TryExecute(_dstcmd, "create table " + dstTable + " (orderid int, customerid nchar(5), rdate datetime, freight money, shipname nvarchar(40))");
-                    _dstcmd.CommandText = "truncate table " + dstTable;
-
-                    expectedErrorMsg = SystemDataResourceManager.Instance.SQL_ConnectionLockedForBcpEvent;
-                    InnerTest(new SqlRowsCopiedEventHandler(OnRowCopiedRollback));
-                    InnerTest(new SqlRowsCopiedEventHandler(OnRowCopiedCommit));
-                    InnerTest(new SqlRowsCopiedEventHandler(OnRowCopiedChangeDatabase));
-                    InnerTest(new SqlRowsCopiedEventHandler(OnRowCopiedExecute));
-                    InnerTest(new SqlRowsCopiedEventHandler(OnRowCopiedBulkCopy));
-
-                    // this will close the connect which is valid so it must be the last test!
-                    expectedErrorMsg = string.Format(
-                        SystemDataResourceManager.Instance.ADP_OpenConnectionRequired,
-                        "WriteToServer",
-                        SystemDataResourceManager.Instance.ADP_ConnectionStateMsg_Closed);
-                    InnerTest(new SqlRowsCopiedEventHandler(OnRowCopiedClose));
-                }
-                finally
-                {
-                    // the original connection is probably trashed
-                    Helpers.TryDropTable(dstConstr, dstTable);
-                }
-            }
-        }
-
-        internal static void InnerTest(SqlRowsCopiedEventHandler eventHandler)
-        {
-            bool hitException = false;
-            try
-            {
-                if (null == _tx || null == _tx.Connection)
-                {
-                    _tx = _dstConn.BeginTransaction();
-                    _dstcmd.Transaction = _tx;
-                    _dstcmd.ExecuteNonQuery();
-                }
-                SqlBulkCopy bulkcopy;
-                using (bulkcopy = new SqlBulkCopy(_dstConn, SqlBulkCopyOptions.Default, _tx))
-                {
-                    bulkcopy.SqlRowsCopied += eventHandler;
-
-                    bulkcopy.DestinationTableName = _dstTable;
-                    bulkcopy.NotifyAfter = 10;
-
-                    SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                    ColumnMappings.Add(0, "orderid");
-                    ColumnMappings.Add(1, "customerid");
-                    ColumnMappings.Add(4, "rdate");
-                    ColumnMappings.Add(7, "freight");
-                    ColumnMappings.Add(8, "shipname");
-
-                    bulkcopy.WriteToServer(_dataTable);
-                    bulkcopy.SqlRowsCopied -= eventHandler;
-
-                    _tx.Commit();
-                }
-            }
-            catch (Exception e)
-            {
-                while (null != e.InnerException)
-                {
-                    e = e.InnerException;
-                }
-
-                Assert.True(e is InvalidOperationException, "Unexpected exception type: " + e.GetType());
-                Assert.True(e.Message.Contains(expectedErrorMsg), string.Format("Incorrect error message. Expected: {0}. Actual: {1}.", expectedErrorMsg, e.Message));
-                _tx.Dispose();
-
-                hitException = true;
-            }
-            Assert.True(hitException, "Did not encounter expected exception.");
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumn.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetColumn.cs
deleted file mode 100644 (file)
index d29f41e..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class MissingTargetColumn
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            ColumnMappings.Add("EmployeeID", "col1");
-                            ColumnMappings.Add("LastName", "col2"); // this column does not exist
-                            ColumnMappings.Add("FirstName", "col3");
-
-                            string errorMsg = SystemDataResourceManager.Instance.SQL_BulkLoadNonMatchingColumnMapping;
-                            DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => bulkcopy.WriteToServer(reader), exceptionMessage: errorMsg);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetTable.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/MissingTargetTable.cs
deleted file mode 100644 (file)
index a5a6159..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class MissingTargetTable
-    {
-        public static void Test(string srcConstr, string dstConstr, string targetTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                {
-                    srcConn.Open();
-
-                    using (DbDataReader reader = srcCmd.ExecuteReader())
-                    {
-                        bool hitException = false;
-                        try
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = targetTable;
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                                ColumnMappings.Add("EmployeeID", "col1");
-                                ColumnMappings.Add("LastName", "col2");
-                                ColumnMappings.Add("FirstName", "col3");
-
-                                bulkcopy.WriteToServer(reader);
-                                bulkcopy.Close();
-                            }
-                        }
-                        catch (InvalidOperationException ioe)
-                        {
-                            string expectedErrorMsg = string.Format(SystemDataResourceManager.Instance.SQL_BulkLoadInvalidDestinationTable, targetTable);
-                            Assert.True(ioe.Message.Contains(expectedErrorMsg), "Unexpected error message: " + ioe.Message);
-                            hitException = true;
-                        }
-                        Assert.True(hitException, "Did not get any exceptions!");
-                    }
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SpecialCharacterNames.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SpecialCharacterNames.cs
deleted file mode 100644 (file)
index 67ad7bc..0000000
+++ /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.Collections.Generic;
-using System.Text;
-using System.Data;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class SpecialCharacterNames
-    {
-        private static string EscapeIdentifier(string name)
-        {
-            return "[" + name.Replace("]", "]]") + "]";
-        }
-
-        public static void Test(string srcConstr, string dstConstr, string dstPrefix)
-        {
-            // create schema and table names with special characters, with ] character escaped.
-            string dstschema = dstPrefix + "_Schema'-]['']";
-            dstschema = EscapeIdentifier(dstschema);
-
-            string dstTable = dstPrefix + "_Table'-]['']";
-            dstTable = EscapeIdentifier(dstTable);
-
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create schema " + dstschema);
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (orderid int, customerid nchar(5))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 2 orderid, customerid from orders", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (SqlDataReader srcreader = srcCmd.ExecuteReader())
-                        {
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-
-                                bulkcopy.WriteToServer(srcreader);
-                            }
-                        }
-                        Helpers.VerifyResults(dstConn, dstTable, 2, 2);
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                    Helpers.TryExecute(dstCmd, "drop schema " + dstschema);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs
deleted file mode 100644 (file)
index 2c6331c..0000000
+++ /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;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class SqlBulkCopyTest
-    {
-        private string srcConstr = null;
-        private string dstConstr = null;
-        private static bool IsAzureServer() => DataTestUtility.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TcpConnStr)).DataSource);
-        private static bool AreConnectionStringsSetup() => DataTestUtility.AreConnStringsSetup();
-
-        public SqlBulkCopyTest()
-        {
-            srcConstr = DataTestUtility.TcpConnStr;
-            dstConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "tempdb" }).ConnectionString;
-        }
-
-        public string AddGuid(string stringin)
-        {
-            stringin += "_" + Guid.NewGuid().ToString().Replace('-', '_');
-            return stringin;
-        }
-
-        [ConditionalFact(nameof(AreConnectionStringsSetup), nameof(IsAzureServer))]
-        public void AzureDistributedTransactionTest()
-        {
-            AzureDistributedTransaction.Test();
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyAllFromReaderTest()
-        {
-            CopyAllFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyAllFromReader1Test()
-        {
-            CopyAllFromReader1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader1"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyMultipleReadersTest()
-        {
-            CopyMultipleReaders.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyMultipleReaders"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopySomeFromReaderTest()
-        {
-            CopySomeFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromReader"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopySomeFromDataTableTest()
-        {
-            CopySomeFromDataTable.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromDataTable"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopySomeFromRowArrayTest()
-        {
-            CopySomeFromRowArray.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromRowArray"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyWithEventTest()
-        {
-            CopyWithEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyWithEvent1Test()
-        {
-            CopyWithEvent1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent1"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void InvalidAccessFromEventTest()
-        {
-            InvalidAccessFromEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_InvalidAccessFromEvent"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Bug84548Test()
-        {
-            Bug84548.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug84548"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void MissingTargetTableTest()
-        {
-            MissingTargetTable.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_MissingTargetTable"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void MissingTargetColumnTest()
-        {
-            MissingTargetColumn.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_MissingTargetColumn"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Bug85007Test()
-        {
-            Bug85007.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug85007"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CheckConstraintsTest()
-        {
-            CheckConstraints.Test(dstConstr, AddGuid("SqlBulkCopyTest_Extensionsrc"), AddGuid("SqlBulkCopyTest_Extensiondst"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TransactionTest()
-        {
-            Transaction.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction0"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Transaction1Test()
-        {
-            Transaction1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction1"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Transaction2Test()
-        {
-            Transaction2.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction2"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Transaction3Test()
-        {
-            Transaction3.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction3"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Transaction4Test()
-        {
-            Transaction4.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction4"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyVariantsTest()
-        {
-            CopyVariants.Test(dstConstr, AddGuid("SqlBulkCopyTest_Variants"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Bug98182Test()
-        {
-            Bug98182.Test(dstConstr, AddGuid("SqlBulkCopyTest_Bug98182 "));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void FireTriggerTest()
-        {
-            FireTrigger.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_FireTrigger"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void ErrorOnRowsMarkedAsDeletedTest()
-        {
-            ErrorOnRowsMarkedAsDeleted.Test(dstConstr, AddGuid("SqlBulkCopyTest_ErrorOnRowsMarkedAsDeleted"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void SpecialCharacterNamesTest()
-        {
-            SpecialCharacterNames.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_SpecialCharacterNames"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Bug903514Test()
-        {
-            Bug903514.Test(dstConstr, AddGuid("SqlBulkCopyTest_Bug903514"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void ColumnCollationTest()
-        {
-            ColumnCollation.Test(dstConstr, AddGuid("SqlBulkCopyTest_ColumnCollation"));
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyWidenNullInexactNumericsTest()
-        {
-            CopyWidenNullInexactNumerics.Test(srcConstr, dstConstr);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyAllFromReaderAsyncTest()
-        {
-            CopyAllFromReaderAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest1")); //Async + Reader
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopySomeFromRowArrayAsyncTest()
-        {
-            CopySomeFromRowArrayAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest2")); //Async + Some Rows
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopySomeFromDataTableAsyncTest()
-        {
-            CopySomeFromDataTableAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest3")); //Async + Some Table
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyWithEventAsyncTest()
-        {
-            CopyWithEventAsync.Test(srcConstr, dstConstr, 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
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void CopyAllFromReaderConnectionClosedAsyncTest()
-        {
-            CopyAllFromReaderConnectionClosedAsync.Test(srcConstr, dstConstr, 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
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TransactionTestAsyncTest()
-        {
-            TransactionTestAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_TransactionTestAsync")); //Async + Transaction rollback
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction.cs
deleted file mode 100644 (file)
index 6956d4d..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Transaction
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, null))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            SqlTransaction myTrans = dstConn.BeginTransaction();
-                            try
-                            {
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => bulkcopy.WriteToServer(reader));
-                            }
-                            finally
-                            {
-                                myTrans.Rollback();
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction1.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction1.cs
deleted file mode 100644 (file)
index e70edb8..0000000
+++ /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;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Transaction1
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, null))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            SqlCommand myCmd = dstConn.CreateCommand();
-                            myCmd.CommandText = "begin transaction";
-                            myCmd.ExecuteNonQuery();
-
-                            try
-                            {
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => bulkcopy.WriteToServer(reader));
-                            }
-                            finally
-                            {
-                                myCmd.CommandText = "rollback transaction";
-                                myCmd.ExecuteNonQuery();
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction2.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction2.cs
deleted file mode 100644 (file)
index 0625120..0000000
+++ /dev/null
@@ -1,66 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Transaction2
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        {
-                            SqlTransaction myTrans = dstConn.BeginTransaction();
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.Default, myTrans))
-                            {
-                                bulkcopy.DestinationTableName = dstTable;
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                                try
-                                {
-                                    bulkcopy.WriteToServer(reader);
-                                    SqlCommand myCmd = dstConn.CreateCommand();
-                                    myCmd.CommandText = "select * from " + dstTable;
-                                    myCmd.Transaction = myTrans;
-                                    using (DbDataReader reader1 = myCmd.ExecuteReader())
-                                    {
-                                        Assert.True(reader1.HasRows, "Expected reader to have rows.");
-                                    }
-                                }
-                                finally
-                                {
-                                    myTrans.Rollback();
-                                }
-                            }
-
-                            Helpers.CheckTableRows(dstConn, dstTable, false);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction3.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction3.cs
deleted file mode 100644 (file)
index a900336..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Transaction3
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlConnection conn3 = new SqlConnection(srcConstr))
-                        {
-                            conn3.Open();
-                            // Start a local transaction on the wrong connection.
-                            SqlTransaction myTrans = conn3.BeginTransaction();
-                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.Default, myTrans))
-                            {
-                                SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-                                bulkcopy.DestinationTableName = dstTable;
-
-                                string exceptionMsg = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => bulkcopy.WriteToServer(reader), exceptionMessage: exceptionMsg);
-
-                                SqlCommand myCmd = dstConn.CreateCommand();
-                                myCmd.CommandText = "select * from " + dstTable;
-                                myCmd.Transaction = myTrans;
-
-                                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => myCmd.ExecuteReader(), exceptionMessage: exceptionMsg);
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction4.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Transaction4.cs
deleted file mode 100644 (file)
index a53fe69..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class Transaction4
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlConnection conn3 = new SqlConnection(srcConstr))
-                        {
-                            conn3.Open();
-                            // Start a local transaction on the wrong connection.
-                            SqlTransaction myTrans = conn3.BeginTransaction();
-                            string errorMsg = SystemDataResourceManager.Instance.SQL_BulkLoadConflictingTransactionOption;
-                            DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, myTrans), exceptionMessage: errorMsg);
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/TransactionTestAsync.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/TransactionTestAsync.cs
deleted file mode 100644 (file)
index 52b1ede..0000000
+++ /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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class TransactionTestAsync
-    {
-        public static void Test(string srcConstr, string dstConstr, string dstTable)
-        {
-            Task t = TestAsync(srcConstr, dstConstr, dstTable);
-            DataTestUtility.AssertThrowsWrapper<AggregateException, InvalidOperationException>(() => t.Wait());
-            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
-        }
-
-        private static async Task TestAsync(string srcConstr, string dstConstr, string dstTable)
-        {
-            using (SqlConnection dstConn = new SqlConnection(dstConstr))
-            using (SqlCommand dstCmd = dstConn.CreateCommand())
-            {
-                dstConn.Open();
-                try
-                {
-                    Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");
-
-                    using (SqlConnection srcConn = new SqlConnection(srcConstr))
-                    using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
-                    {
-                        srcConn.Open();
-
-                        using (DbDataReader reader = srcCmd.ExecuteReader())
-                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, null))
-                        {
-                            bulkcopy.DestinationTableName = dstTable;
-                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
-
-                            SqlTransaction myTrans = dstConn.BeginTransaction();
-                            try
-                            {
-                                await bulkcopy.WriteToServerAsync(reader);
-                            }
-                            finally
-                            {
-                                myTrans.Rollback();
-                            }
-                        }
-                    }
-                }
-                finally
-                {
-                    Helpers.TryExecute(dstCmd, "drop table " + dstTable);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlCredentialTest/SqlCredentialTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlCredentialTest/SqlCredentialTest.cs
deleted file mode 100644 (file)
index 00127b7..0000000
+++ /dev/null
@@ -1,203 +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.Data.SqlClient;
-using System.Data.SqlClient.ManualTesting.Tests;
-using System.Linq;
-using System.Security;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class SqlCredentialTest
-    {
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void CreateSqlConnectionWithCredential()
-        {
-            var user = "u" + Guid.NewGuid().ToString().Replace("-", "");
-            var passStr = "Pax561O$T5K#jD";
-
-            try
-            {
-                createTestUser(user, passStr);
-
-                var csb = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-                csb.Remove("User ID");
-                csb.Remove("Password");
-                csb.IntegratedSecurity = false;
-
-                var password = new SecureString();
-                passStr.ToCharArray().ToList().ForEach(x => password.AppendChar(x));
-                password.MakeReadOnly();
-
-                using (var conn = new SqlConnection(csb.ConnectionString, new SqlCredential(user, password)))
-                using (var cmd = new SqlCommand("SELECT 1;", conn))
-                {
-                    conn.Open();
-                    Assert.Equal(1, cmd.ExecuteScalar());
-                }
-            }
-            finally
-            {
-                dropTestUser(user);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void SqlConnectionChangePasswordPlaintext()
-        {
-            var user = "u" + Guid.NewGuid().ToString().Replace("-", "");
-            var pass = "!21Ja3Ims7LI&n";
-            var newPass = "fmVCNf@24Dg*8j";
-
-            try
-            {
-                createTestUser(user, pass);
-
-                var csb = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-                csb.UserID = user;
-                csb.Password = pass;
-                csb.IntegratedSecurity = false;
-
-                // Change password and try opening connection.
-                SqlConnection.ChangePassword(csb.ConnectionString, newPass);
-                csb.Password = newPass;
-
-                using (var conn = new SqlConnection(csb.ConnectionString))
-                using (var cmd = new SqlCommand("SELECT 1;", conn))
-                {
-                    conn.Open();
-                    Assert.Equal(1, cmd.ExecuteScalar());
-                }
-            }
-            finally
-            {
-                dropTestUser(user);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void SqlConnectionChangePasswordSecureString()
-        {
-            var user = "u" + Guid.NewGuid().ToString().Replace("-", "");
-            var passStr = "tcM0qB^izt%3u7";
-            var newPassStr = "JSG2e(Vp0WCXE&";
-
-            try
-            {
-                createTestUser(user, passStr);
-
-                var csb = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-                csb.Remove("User ID");
-                csb.Remove("Password");
-                csb.IntegratedSecurity = false;
-
-                var password = new SecureString();
-                passStr.ToCharArray().ToList().ForEach(x => password.AppendChar(x));
-                password.MakeReadOnly();
-
-                var newPassword = new SecureString();
-                newPassStr.ToCharArray().ToList().ForEach(x => newPassword.AppendChar(x));
-                newPassword.MakeReadOnly();
-
-                // Change password and try opening connection.
-                SqlConnection.ChangePassword(csb.ConnectionString, new SqlCredential(user, password), newPassword);
-
-                using (var conn = new SqlConnection(csb.ConnectionString, new SqlCredential(user, newPassword)))
-                using (var cmd = new SqlCommand("SELECT 1;", conn))
-                {
-                    conn.Open();
-                    Assert.Equal(1, cmd.ExecuteScalar());
-                }
-            }
-            finally
-            {
-                dropTestUser(user);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void OldCredentialsShouldFail()
-        {
-            String user = "u" + Guid.NewGuid().ToString().Replace("-", "");
-            String passStr = "Pax561O$T5K#jD";
-
-            try
-            {
-                createTestUser(user, passStr);
-
-                SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-                sqlConnectionStringBuilder.Remove("User ID");
-                sqlConnectionStringBuilder.Remove("Password");
-                sqlConnectionStringBuilder.IntegratedSecurity = false;
-
-                SecureString password = new SecureString();
-                passStr.ToCharArray().ToList().ForEach(x => password.AppendChar(x));
-                password.MakeReadOnly();
-                SqlCredential credential = new SqlCredential(user, password);
-
-                using (SqlConnection conn1 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString, credential))
-                using (SqlConnection conn2 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString, credential))
-                using (SqlConnection conn3 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString, credential))
-                using (SqlConnection conn4 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString, credential))
-                {
-                    conn1.Open();
-                    conn2.Open();
-                    conn3.Open();
-                    conn4.Open();
-
-                    SecureString newPassword = new SecureString();
-                    "newPassword".ToCharArray().ToList().ForEach(x => newPassword.AppendChar(x));
-                    newPassword.MakeReadOnly();
-                    SqlConnection.ChangePassword(sqlConnectionStringBuilder.ConnectionString, credential, newPassword);
-                    using (SqlConnection conn5 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString, new SqlCredential(user, password)))
-                    {
-                        Assert.Throws<SqlException>(() => conn5.Open());
-                    }
-                }
-            }
-            finally
-            {
-                dropTestUser(user);
-            }
-        }
-
-        private static void createTestUser(string username, string password)
-        {
-            // Creates a test user with read permissions.
-            string createUserCmd = $"CREATE LOGIN {username} WITH PASSWORD = '{password}', CHECK_POLICY=OFF;"
-                                    + $"EXEC sp_adduser '{username}', '{username}', 'db_datareader';";
-
-            using (var conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (var cmd = new SqlCommand(createUserCmd, conn))
-            {
-                conn.Open();
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private static void dropTestUser(string username)
-        {
-            // Removes a created test user.
-            string dropUserCmd = $"IF EXISTS (SELECT * FROM sys.schemas WHERE name = '{username}') BEGIN DROP SCHEMA {username} END;"
-                                + $"IF EXISTS (SELECT * FROM sys.database_principals WHERE type = 'S' AND name = '{username}') BEGIN DROP USER {username} END;"
-                                + $"DROP LOGIN {username}";
-
-            // Pool must be cleared to prevent DROP LOGIN failure.
-            SqlConnection.ClearAllPools();
-
-            using (var conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (var cmd = new SqlCommand(dropUserCmd, conn))
-            {
-                conn.Open();
-                cmd.ExecuteNonQuery();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlFileStreamTest/SqlFileStreamTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlFileStreamTest/SqlFileStreamTest.cs
deleted file mode 100644 (file)
index 260b04b..0000000
+++ /dev/null
@@ -1,213 +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.Data.SqlTypes;
-using System.IO;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class SqlFileStreamTest
-    {
-        private static bool IsFileStreamEnvironmentSet() => DataTestUtility.IsFileStreamSetup();
-        private static bool AreConnectionStringsSetup() => DataTestUtility.AreConnStringsSetup();
-        private static bool IsIntegratedSecurityEnvironmentSet() => DataTestUtility.IsIntegratedSecuritySetup();
-
-        private static int[] s_insertedValues = { 11 , 22 };
-
-        [PlatformSpecific(TestPlatforms.Windows)]
-        [ConditionalFact(nameof(IsFileStreamEnvironmentSet), nameof(IsIntegratedSecurityEnvironmentSet), nameof(AreConnectionStringsSetup))]
-        public static void ReadFilestream()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                string tempTable = SetupTable(connection);
-                int nRow = 0;
-                byte[] retrievedValue;
-                SqlCommand command = new SqlCommand($"SELECT Photo.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT(),EmployeeId FROM {tempTable} ORDER BY EmployeeId", connection);
-
-                SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
-                command.Transaction = transaction;
-
-                using (SqlDataReader reader = command.ExecuteReader())
-                {
-                    while (reader.Read())
-                    {
-                        // Get the pointer for the file.
-                        string path = reader.GetString(0);
-                        byte[] transactionContext = reader.GetSqlBytes(1).Buffer;
-
-                        // Create the SqlFileStream
-                        using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.Read, FileOptions.SequentialScan, allocationSize: 0))
-                        {
-                            // Read the contents as bytes.
-                            retrievedValue = new byte[fileStream.Length];
-                            fileStream.Read(retrievedValue,0,(int)(fileStream.Length));
-
-                            // Reverse the byte array, if the system architecture is little-endian.
-                            if (BitConverter.IsLittleEndian)
-                                Array.Reverse(retrievedValue);
-
-                            // Compare inserted and retrieved values.
-                            Assert.Equal(s_insertedValues[nRow], BitConverter.ToInt32(retrievedValue,0));
-                        }
-                        nRow++;
-                    }
-
-                }
-                transaction.Commit();
-
-                // Drop Table
-                ExecuteNonQueryCommand($"DROP TABLE {tempTable}", connection);
-            }
-        }
-
-        [PlatformSpecific(TestPlatforms.Windows)]
-        [ConditionalFact(nameof(IsFileStreamEnvironmentSet), nameof(IsIntegratedSecurityEnvironmentSet), nameof(AreConnectionStringsSetup))]
-        public static void OverwriteFilestream()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                string tempTable = SetupTable(connection);
-                byte[] insertedValue = BitConverter.GetBytes(3);
-
-                // Reverse the byte array, if the system architecture is little-endian.
-                if (BitConverter.IsLittleEndian)
-                    Array.Reverse(insertedValue);
-
-                SqlCommand command = new SqlCommand($"SELECT TOP(1) Photo.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT(),EmployeeId FROM {tempTable} ORDER BY EmployeeId", connection);
-
-                SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
-                command.Transaction = transaction;
-
-                using (SqlDataReader reader = command.ExecuteReader())
-                {
-                    while (reader.Read())
-                    {
-                        // Get the pointer for file
-                        string path = reader.GetString(0);
-                        byte[] transactionContext = reader.GetSqlBytes(1).Buffer;
-
-                        // Create the SqlFileStream
-                        using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write, FileOptions.SequentialScan, allocationSize: 0))
-                        {
-                            // Overwrite the first row in the table
-                            fileStream.Write((insertedValue), 0, 4);
-                        }
-                    }
-                }
-                transaction.Commit();
-
-                // Compare inserted and retrieved value
-                byte[] retrievedValue = RetrieveData(tempTable, connection, insertedValue.Length);
-                Assert.Equal(insertedValue, retrievedValue);
-
-                // Drop Table
-                ExecuteNonQueryCommand($"DROP TABLE {tempTable}", connection);
-            }
-        }
-
-        [PlatformSpecific(TestPlatforms.Windows)]
-        [ConditionalFact(nameof(IsFileStreamEnvironmentSet), nameof(IsIntegratedSecurityEnvironmentSet), nameof(AreConnectionStringsSetup))]
-        public static void AppendFilestream()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                string tempTable = SetupTable(connection);
-
-                byte[] insertedValue = BitConverter.GetBytes(s_insertedValues[0]);
-                byte appendedByte = 0x04;
-                insertedValue = AddByteToArray(insertedValue, appendedByte);
-
-                // Reverse the byte array, if the system architecture is little-endian.
-                if (BitConverter.IsLittleEndian)
-                    Array.Reverse(insertedValue);
-
-                SqlCommand command = new SqlCommand($"SELECT TOP(1) Photo.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT(),EmployeeId FROM {tempTable} ORDER BY EmployeeId", connection);
-
-                SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
-                command.Transaction = transaction;
-
-                using (SqlDataReader reader = command.ExecuteReader())
-                {
-                    while (reader.Read())
-                    {
-                        // Get the pointer for file
-                        string path = reader.GetString(0);
-                        byte[] transactionContext = reader.GetSqlBytes(1).Buffer;
-
-                        using (Stream fileStream = new SqlFileStream(path, transactionContext, FileAccess.ReadWrite, FileOptions.SequentialScan, allocationSize: 0))
-                        {
-                            // Seek to the end of the file
-                            fileStream.Seek(0, SeekOrigin.End);
-
-                            // Append a single byte
-                            fileStream.WriteByte(appendedByte);
-                        }
-                    }
-                }
-                transaction.Commit();
-
-                // Compare inserted and retrieved value
-                byte[] retrievedValue = RetrieveData(tempTable, connection, insertedValue.Length);
-                Assert.Equal(insertedValue, retrievedValue);
-
-                // Drop Table
-                ExecuteNonQueryCommand($"DROP TABLE {tempTable}", connection);
-            }
-        }
-        #region Private helper methods
-        private static string SetupTable(SqlConnection conn)
-        {
-            // Generate random table name
-            string tempTable = "fs_" + Guid.NewGuid().ToString().Replace('-', '_');
-
-            // Create table
-            string createTable = $"CREATE TABLE {tempTable} (EmployeeId INT  NOT NULL  PRIMARY KEY, Photo VARBINARY(MAX) FILESTREAM  NULL, RowGuid UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL UNIQUE DEFAULT NEWID() ) ";
-            ExecuteNonQueryCommand(createTable, conn);
-
-            // Insert data into created table
-            for (int i = 0; i < s_insertedValues.Length; i++)
-            {
-                string prepTable = $"INSERT INTO {tempTable} VALUES ({i + 1}, {s_insertedValues[i]} , default)";
-                ExecuteNonQueryCommand(prepTable, conn);
-            }
-
-            return tempTable;
-        }
-
-        private static void ExecuteNonQueryCommand(string cmdText, SqlConnection conn)
-        {
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                cmd.CommandText = cmdText;
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private static byte[] RetrieveData(string tempTable, SqlConnection conn, int len)
-        {
-            SqlCommand command = new SqlCommand($"SELECT TOP(1) Photo FROM {tempTable}", conn);
-            byte[] bArray = new byte[len];
-            using (SqlDataReader reader = command.ExecuteReader())
-            {
-                reader.Read();
-                reader.GetBytes(0, 0, bArray, 0, len);
-            }
-            return bArray;
-        }
-
-        public static byte[] AddByteToArray(byte[] oldArray, byte newByte)
-        {
-            byte[] newArray = new byte[oldArray.Length + 1];
-            oldArray.CopyTo(newArray, 1);
-            newArray[0] = newByte;
-            return newArray;
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlNamedPipesTest/SqlNamedPipesTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlNamedPipesTest/SqlNamedPipesTest.cs
deleted file mode 100644 (file)
index 751eca9..0000000
+++ /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.Runtime.InteropServices;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class SqlNamedPipesTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        [PlatformSpecific(TestPlatforms.Windows)] // Named pipes with the given input strings are not supported on Unix
-        public static void ValidConnStringTest()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.NpConnStr);
-            builder.ConnectTimeout = 5;
-
-            OpenGoodConnection(builder.ConnectionString);
-        }
-
-        private static void OpenGoodConnection(string connectionString)
-        {
-            using (SqlConnection conn = new SqlConnection(connectionString))
-            {
-                conn.Open();
-                DataTestUtility.AssertEqualsWithDescription(ConnectionState.Open, conn.State, "FAILED: Connection should be in open state");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlNotificationTest/SqlNotificationTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlNotificationTest/SqlNotificationTest.cs
deleted file mode 100644 (file)
index 2c2ab64..0000000
+++ /dev/null
@@ -1,343 +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.Threading;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class SqlNotificationTest : IDisposable
-    {
-        // Misc constants
-        private const int CALLBACK_TIMEOUT = 5000; // milliseconds
-
-        // Database schema
-        private readonly string _tableName   = $"dbo.[SQLDEP_{Guid.NewGuid().ToString()}]";
-        private readonly string _queueName   = $"SQLDEP_{Guid.NewGuid().ToString()}";
-        private readonly string _serviceName = $"SQLDEP_{Guid.NewGuid().ToString()}";
-        private readonly string _schemaQueue;
-
-        // Connection information used by all tests
-        private readonly string _startConnectionString;
-        private readonly string _execConnectionString;
-
-        public SqlNotificationTest()
-        {
-            _startConnectionString = DataTestUtility.TcpConnStr;
-            _execConnectionString = DataTestUtility.TcpConnStr;
-
-            _schemaQueue = $"[{_queueName}]";
-
-            Setup();
-        }
-
-        public void Dispose()
-        {
-            Cleanup();
-        }
-
-        #region StartStop_Tests
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_DoubleStart_SameConnStr()
-        {
-            Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener.");
-
-            Assert.False(SqlDependency.Start(_startConnectionString), "Expected failure when trying to start listener.");
-
-            Assert.False(SqlDependency.Stop(_startConnectionString), "Expected failure when trying to completely stop listener.");
-
-            Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener.");
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_DoubleStart_DifferentConnStr()
-        {
-            SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(_startConnectionString);
-
-            // just change something that doesn't impact the dependency dispatcher
-            if (cb.ShouldSerialize("connect timeout"))
-                cb.ConnectTimeout = cb.ConnectTimeout + 1;
-            else
-                cb.ConnectTimeout = 50;
-
-            Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener.");
-
-            try
-            {
-                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => SqlDependency.Start(cb.ToString()));
-            }
-            finally
-            {
-                Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener.");
-
-                Assert.False(SqlDependency.Stop(cb.ToString()), "Expected failure when trying to completely stop listener.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_Start_DifferentDB()
-        {
-            SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(_startConnectionString)
-            {
-                InitialCatalog = "tempdb"
-            };
-            string altDatabaseConnectionString = cb.ToString();
-
-            Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener.");
-
-            Assert.True(SqlDependency.Start(altDatabaseConnectionString), "Failed to start listener.");
-
-            Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener.");
-
-            Assert.True(SqlDependency.Stop(altDatabaseConnectionString), "Failed to stop listener.");
-        }
-        #endregion
-
-        #region SqlDependency_Tests
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_SingleDependency_NoStart()
-        {
-            using (SqlConnection conn = new SqlConnection(_execConnectionString))
-            using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn))
-            {
-                conn.Open();
-
-                SqlDependency dep = new SqlDependency(cmd);
-                dep.OnChange += delegate (object o, SqlNotificationEventArgs args)
-                {
-                    Console.WriteLine("4 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source);
-                };
-
-                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => cmd.ExecuteReader());
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_SingleDependency_Stopped()
-        {
-            SqlDependency.Start(_startConnectionString);
-            SqlDependency.Stop(_startConnectionString);
-
-            using (SqlConnection conn = new SqlConnection(_execConnectionString))
-            using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn))
-            {
-                conn.Open();
-
-                SqlDependency dep = new SqlDependency(cmd);
-                dep.OnChange += delegate (object o, SqlNotificationEventArgs args)
-                {
-                    // Delegate won't be called, since notifications were stoppped
-                    Console.WriteLine("5 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source);
-                };
-
-                DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => cmd.ExecuteReader());
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_SingleDependency_AllDefaults_SqlAuth()
-        {
-            Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener.");
-
-            try
-            {
-                // create a new event every time to avoid mixing notification callbacks
-                ManualResetEvent notificationReceived = new ManualResetEvent(false);
-                ManualResetEvent updateCompleted = new ManualResetEvent(false);
-
-                using (SqlConnection conn = new SqlConnection(_execConnectionString))
-                using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn))
-                {
-                    conn.Open();
-
-                    SqlDependency dep = new SqlDependency(cmd);
-                    dep.OnChange += delegate (object o, SqlNotificationEventArgs arg)
-                    {
-                        Assert.True(updateCompleted.WaitOne(CALLBACK_TIMEOUT, false), "Received notification, but update did not complete.");
-
-                        DataTestUtility.AssertEqualsWithDescription(SqlNotificationType.Change, arg.Type, "Unexpected Type value.");
-                        DataTestUtility.AssertEqualsWithDescription(SqlNotificationInfo.Update, arg.Info, "Unexpected Info value.");
-                        DataTestUtility.AssertEqualsWithDescription(SqlNotificationSource.Data, arg.Source, "Unexpected Source value.");
-
-                        notificationReceived.Set();
-                    };
-
-                    cmd.ExecuteReader();
-                }
-
-                int count = RunSQL("UPDATE " + _tableName + " SET c=" + Environment.TickCount);
-                DataTestUtility.AssertEqualsWithDescription(1, count, "Unexpected count value.");
-
-                updateCompleted.Set();
-
-                Assert.True(notificationReceived.WaitOne(CALLBACK_TIMEOUT, false), "Notification not received within the timeout period");
-            }
-            finally
-            {
-                Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_SingleDependency_CustomQueue_SqlAuth()
-        {
-            Assert.True(SqlDependency.Start(_startConnectionString, _queueName), "Failed to start listener.");
-
-            try
-            {
-                // create a new event every time to avoid mixing notification callbacks
-                ManualResetEvent notificationReceived = new ManualResetEvent(false);
-                ManualResetEvent updateCompleted = new ManualResetEvent(false);
-
-                using (SqlConnection conn = new SqlConnection(_execConnectionString))
-                using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn))
-                {
-                    conn.Open();
-
-                    SqlDependency dep = new SqlDependency(cmd, "service=" + _serviceName + ";local database=msdb", 0);
-                    dep.OnChange += delegate (object o, SqlNotificationEventArgs args)
-                    {
-                        Assert.True(updateCompleted.WaitOne(CALLBACK_TIMEOUT, false), "Received notification, but update did not complete.");
-
-                        Console.WriteLine("7 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source);
-                        notificationReceived.Set();
-                    };
-
-                    cmd.ExecuteReader();
-                }
-
-                int count = RunSQL("UPDATE " + _tableName + " SET c=" + Environment.TickCount);
-                DataTestUtility.AssertEqualsWithDescription(1, count, "Unexpected count value.");
-
-                updateCompleted.Set();
-
-                Assert.False(notificationReceived.WaitOne(CALLBACK_TIMEOUT, false), "Notification should not be received.");
-            }
-            finally
-            {
-                Assert.True(SqlDependency.Stop(_startConnectionString, _queueName), "Failed to stop listener.");
-            }
-        }
-
-        /// <summary>
-        /// SqlDependecy premature timeout
-        /// </summary>
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Test_SingleDependency_Timeout()
-        {
-            Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener.");
-
-            try
-            {
-                // with resolution of 15 seconds, SqlDependency should fire timeout notification only after 45 seconds, leave 5 seconds gap from both sides.
-                const int SqlDependencyTimerResolution = 15; // seconds
-                const int testTimeSeconds = SqlDependencyTimerResolution * 3 - 5;
-                const int minTimeoutEventInterval = testTimeSeconds - 1;
-                const int maxTimeoutEventInterval = testTimeSeconds + SqlDependencyTimerResolution + 1;
-
-                // create a new event every time to avoid mixing notification callbacks
-                ManualResetEvent notificationReceived = new ManualResetEvent(false);
-                DateTime startUtcTime;
-
-                using (SqlConnection conn = new SqlConnection(_execConnectionString))
-                using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn))
-                {
-                    conn.Open();
-
-                    // create SqlDependency with timeout
-                    SqlDependency dep = new SqlDependency(cmd, null, testTimeSeconds);
-                    dep.OnChange += delegate (object o, SqlNotificationEventArgs arg)
-                    {
-                        // notification of Timeout can arrive either from server or from client timer. Handle both situations here:
-                        SqlNotificationInfo info = arg.Info;
-                        if (info == SqlNotificationInfo.Unknown)
-                        {
-                            // server timed out before the client, replace it with Error to produce consistent output for trun
-                            info = SqlNotificationInfo.Error;
-                        }
-
-                        DataTestUtility.AssertEqualsWithDescription(SqlNotificationType.Change, arg.Type, "Unexpected Type value.");
-                        DataTestUtility.AssertEqualsWithDescription(SqlNotificationInfo.Error, arg.Info, "Unexpected Info value.");
-                        DataTestUtility.AssertEqualsWithDescription(SqlNotificationSource.Timeout, arg.Source, "Unexpected Source value.");
-                        notificationReceived.Set();
-                    };
-
-                    cmd.ExecuteReader();
-                    startUtcTime = DateTime.UtcNow;
-                }
-
-                Assert.True(
-                    notificationReceived.WaitOne(TimeSpan.FromSeconds(maxTimeoutEventInterval), false),
-                    string.Format("Notification not received within the maximum timeout period of {0} seconds", maxTimeoutEventInterval));
-
-                // notification received in time, check that it is not too early
-                TimeSpan notificationTime = DateTime.UtcNow - startUtcTime;
-                Assert.True(
-                    notificationTime >= TimeSpan.FromSeconds(minTimeoutEventInterval),
-                    string.Format(
-                        "Notification was not expected before {0} seconds: received after {1} seconds",
-                        minTimeoutEventInterval, notificationTime.TotalSeconds));
-            }
-            finally
-            {
-                Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener.");
-            }
-        }
-
-        #endregion
-
-        #region Utility_Methods
-        private static string[] CreateSqlSetupStatements(string tableName, string queueName, string serviceName)
-        {
-            return new string[] {
-                string.Format("CREATE TABLE {0}(a INT NOT NULL, b NVARCHAR(10), c INT NOT NULL)", tableName),
-                string.Format("INSERT INTO {0} (a, b, c) VALUES (1, 'foo', 0)", tableName),
-                string.Format("CREATE QUEUE {0}", queueName),
-                string.Format("CREATE SERVICE [{0}] ON QUEUE {1} ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification])", serviceName, queueName)
-            };
-        }
-
-        private static string[] CreateSqlCleanupStatements(string tableName, string queueName, string serviceName)
-        {
-            return new string[] {
-                string.Format("DROP TABLE {0}", tableName),
-                string.Format("DROP SERVICE [{0}]", serviceName),
-                string.Format("DROP QUEUE {0}", queueName)
-            };
-        }
-
-        private void Setup()
-        {
-            RunSQL(CreateSqlSetupStatements(_tableName, _schemaQueue, _serviceName));
-        }
-
-        private void Cleanup()
-        {
-            RunSQL(CreateSqlCleanupStatements(_tableName, _schemaQueue, _serviceName));
-        }
-
-        private int RunSQL(params string[] stmts)
-        {
-            int count = -1;
-            using (SqlConnection conn = new SqlConnection(_execConnectionString))
-            {
-                conn.Open();
-
-                SqlCommand cmd = conn.CreateCommand();
-
-                foreach (string stmt in stmts)
-                {
-                    cmd.CommandText = stmt;
-                    int tmp = cmd.ExecuteNonQuery();
-                    count = ((0 <= tmp) ? ((0 <= count) ? count + tmp : tmp) : count);
-                }
-            }
-            return count;
-        }
-
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlSchemaInfoTest/SqlSchemaInfoTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/SqlSchemaInfoTest/SqlSchemaInfoTest.cs
deleted file mode 100644 (file)
index 79b3aec..0000000
+++ /dev/null
@@ -1,201 +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.Data.Common;
-using System.ComponentModel;
-using System.Collections.Generic;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class SqlSchemaInfoTest
-    {
-        #region TestMethods
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestGetSchema()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                conn.Open();
-                DataTable dataBases = conn.GetSchema("DATABASES");
-
-                Assert.True(dataBases.Rows.Count > 0, "At least one database is expected");
-
-                DataTable metaDataCollections = conn.GetSchema(DbMetaDataCollectionNames.MetaDataCollections);
-                Assert.True(metaDataCollections != null && metaDataCollections.Rows.Count > 0);
-
-                DataTable metaDataSourceInfo = conn.GetSchema(DbMetaDataCollectionNames.DataSourceInformation);
-                Assert.True(metaDataSourceInfo != null && metaDataSourceInfo.Rows.Count > 0);
-
-                DataTable metaDataTypes = conn.GetSchema(DbMetaDataCollectionNames.DataTypes);
-                Assert.True(metaDataTypes != null && metaDataTypes.Rows.Count > 0);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestCommandBuilder()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommandBuilder commandBuilder = new SqlCommandBuilder())
-            using (SqlCommand command = connection.CreateCommand())
-            {
-                string identifier = "TestIdentifier";
-                string quotedIdentifier = commandBuilder.QuoteIdentifier(identifier);
-                DataTestUtility.AssertEqualsWithDescription(
-                    "[TestIdentifier]", quotedIdentifier,
-                    "Unexpected QuotedIdentifier string.");
-
-                string unquotedIdentifier = commandBuilder.UnquoteIdentifier(quotedIdentifier);
-                DataTestUtility.AssertEqualsWithDescription(
-                    "TestIdentifier", unquotedIdentifier,
-                    "Unexpected UnquotedIdentifier string.");
-
-                identifier = "identifier]withclosesquarebracket";
-                quotedIdentifier = commandBuilder.QuoteIdentifier(identifier);
-                DataTestUtility.AssertEqualsWithDescription(
-                    "[identifier]]withclosesquarebracket]", quotedIdentifier,
-                    "Unexpected QuotedIdentifier string.");
-
-                unquotedIdentifier = null;
-                unquotedIdentifier = commandBuilder.UnquoteIdentifier(quotedIdentifier);
-                DataTestUtility.AssertEqualsWithDescription(
-                    "identifier]withclosesquarebracket", unquotedIdentifier,
-                    "Unexpected UnquotedIdentifier string.");
-            }
-        }
-
-        // This test validates behavior of SqlInitialCatalogConverter used to present database names in PropertyGrid
-        // with the SqlConnectionStringBuilder object presented in the control underneath.
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestInitialCatalogStandardValues()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                string currentDb = connection.Database;
-                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connection.ConnectionString);
-                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(builder);
-                PropertyDescriptor descriptor = properties["InitialCatalog"];
-
-                DataTestUtility.AssertEqualsWithDescription(
-                    "SqlInitialCatalogConverter", descriptor.Converter.GetType().Name,
-                    "Unexpected TypeConverter type.");
-
-                // GetStandardValues of this converter calls GetSchema("DATABASES")
-                var dbNames = descriptor.Converter.GetStandardValues(new DescriptorContext(descriptor, builder));
-                HashSet<string> searchSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
-                foreach (string name in dbNames)
-                {
-                    searchSet.Add(name);
-                }
-
-                // ensure master and current database exist there
-                Assert.True(searchSet.Contains("master"), "Cannot find database: master.");
-                Assert.True(searchSet.Contains(currentDb), $"Cannot find database: {currentDb}.");
-            }
-        }
-        #endregion
-
-        #region UtilityMethodsClasses
-        // primitive implementation of ITypeDescriptorContext to be used with component model APIs
-        private class DescriptorContext : ITypeDescriptorContext
-        {
-            SqlConnectionStringBuilder _instance;
-            PropertyDescriptor _descriptor;
-
-            public DescriptorContext(PropertyDescriptor descriptor, SqlConnectionStringBuilder instance)
-            {
-                _instance = instance;
-                _descriptor = descriptor;
-            }
-
-            public object Instance
-            {
-                get { return _instance; }
-            }
-
-            public IContainer Container
-            {
-                get { return null; }
-            }
-
-            public PropertyDescriptor PropertyDescriptor
-            {
-                get { return _descriptor; }
-            }
-
-            public void OnComponentChanged()
-            {
-                throw new NotImplementedException();
-            }
-
-            public bool OnComponentChanging()
-            {
-                throw new NotImplementedException();
-            }
-
-            public object GetService(Type serviceType)
-            {
-                throw new NotImplementedException();
-            }
-        }
-
-        private static void DumpDataTable(DataTable dataTable, int rowPrintCount)
-        {
-            Console.WriteLine("DumpDataTable");
-            Console.WriteLine("");
-
-            if (dataTable == null)
-            {
-                Console.WriteLine("DataTable object is null.");
-                return;
-            }
-            int columnCount = dataTable.Columns.Count;
-            int currentColumn;
-
-            int rowCount = dataTable.Rows.Count;
-            int currentRow;
-
-            Console.WriteLine("Table \"{0}\" has {1} columns", dataTable.TableName.ToString(), columnCount.ToString());
-            Console.WriteLine("Table \"{0}\" has {1} rows. At most the first {2} are dumped.", dataTable.TableName.ToString(), rowCount.ToString(), rowPrintCount.ToString());
-
-            if ((rowPrintCount != 0) && (rowPrintCount < rowCount))
-            {
-                rowCount = rowPrintCount;
-            }
-
-            for (currentColumn = 0; currentColumn < columnCount; currentColumn++)
-            {
-                DumpDataColumn(dataTable.Columns[currentColumn]);
-            }
-
-            for (currentRow = 0; currentRow < rowCount; currentRow++)
-            {
-                DumpDataRow(dataTable.Rows[currentRow], dataTable);
-            }
-
-            return;
-
-        }
-
-        private static void DumpDataRow(DataRow dataRow, DataTable dataTable)
-        {
-            Console.WriteLine(" ");
-            Console.WriteLine("<DumpDataRow>");
-
-            foreach (DataColumn dataColumn in dataTable.Columns)
-            {
-                Console.WriteLine("{0}.{1} = {2}", dataTable.TableName, dataColumn.ColumnName, dataRow[dataColumn, DataRowVersion.Current].ToString());
-            }
-            return;
-        }
-
-        private static void DumpDataColumn(DataColumn dataColumn)
-        {
-
-            Console.WriteLine("Column Name = {0}, Column Type =  {1}", dataColumn.ColumnName, dataColumn.DataType.ToString());
-            return;
-        }
-        #endregion
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs
deleted file mode 100644 (file)
index 63246a0..0000000
+++ /dev/null
@@ -1,205 +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.Transactions;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class TransactionEnlistmentTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestAutoEnlistment_TxScopeComplete()
-        {
-            RunTestSet(TestCase_AutoEnlistment_TxScopeComplete);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestAutoEnlistment_TxScopeNonComplete()
-        {
-            RunTestSet(TestCase_AutoEnlistment_TxScopeNonComplete);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestManualEnlistment_Enlist()
-        {
-            RunTestSet(TestCase_ManualEnlistment_Enlist);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestManualEnlistment_NonEnlist()
-        {
-            RunTestSet(TestCase_ManualEnlistment_NonEnlist);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestManualEnlistment_Enlist_TxScopeComplete()
-        {
-            RunTestSet(TestCase_ManualEnlistment_Enlist_TxScopeComplete);
-        }
-
-
-
-
-        private static void TestCase_AutoEnlistment_TxScopeComplete()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
-            builder.Enlist = true;
-            ConnectionString = builder.ConnectionString;
-
-            using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.MaxValue))
-            {
-                using (SqlConnection connection = new SqlConnection(ConnectionString))
-                {
-                    connection.Open();
-                    using (SqlCommand command = connection.CreateCommand())
-                    {
-                        command.CommandText = $"INSERT INTO {TestTableName} VALUES ({InputCol1}, '{InputCol2}')";
-                        command.ExecuteNonQuery();
-                    }
-                }
-                txScope.Complete();
-            }
-
-            DataTable result = DataTestUtility.RunQuery(ConnectionString, $"select col2 from {TestTableName} where col1 = {InputCol1}");
-            Assert.True(result.Rows.Count == 1);
-            Assert.True(string.Equals(result.Rows[0][0], InputCol2));
-        }
-
-        private static void TestCase_AutoEnlistment_TxScopeNonComplete()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
-            builder.Enlist = true;
-            ConnectionString = builder.ConnectionString;
-
-            using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.MaxValue))
-            {
-                using (SqlConnection connection = new SqlConnection(ConnectionString))
-                {
-                    connection.Open();
-                    using (SqlCommand command = connection.CreateCommand())
-                    {
-                        command.CommandText = $"INSERT INTO {TestTableName} VALUES ({InputCol1}, '{InputCol2}')";
-                        command.ExecuteNonQuery();
-                    }
-                }
-            }
-
-            DataTable result = DataTestUtility.RunQuery(ConnectionString, $"select col2 from {TestTableName} where col1 = {InputCol1}");
-            Assert.True(result.Rows.Count == 0);
-        }
-
-        private static void TestCase_ManualEnlistment_Enlist()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
-            builder.Enlist = false;
-            ConnectionString = builder.ConnectionString;
-
-            using (SqlConnection connection = new SqlConnection(ConnectionString))
-            {
-                connection.Open();
-                using (TransactionScope txScope = new TransactionScope())
-                {
-                    connection.EnlistTransaction(Transactions.Transaction.Current);
-                    using (SqlCommand command = connection.CreateCommand())
-                    {
-                        command.CommandText = $"INSERT INTO {TestTableName} VALUES ({InputCol1}, '{InputCol2}')";
-                        command.ExecuteNonQuery();
-                    }
-                }
-            }
-
-            DataTable result = DataTestUtility.RunQuery(ConnectionString, $"select col2 from {TestTableName} where col1 = {InputCol1}");
-            Assert.True(result.Rows.Count == 0);
-        }
-
-        private static void TestCase_ManualEnlistment_NonEnlist()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
-            builder.Enlist = false;
-            ConnectionString = builder.ConnectionString;
-
-            using (SqlConnection connection = new SqlConnection(ConnectionString))
-            {
-                connection.Open();
-                using (TransactionScope txScope = new TransactionScope())
-                {
-                    using (SqlCommand command = connection.CreateCommand())
-                    {
-                        command.CommandText = $"INSERT INTO {TestTableName} VALUES ({InputCol1}, '{InputCol2}')";
-                        command.ExecuteNonQuery();
-                    }
-                }
-            }
-
-            DataTable result = DataTestUtility.RunQuery(ConnectionString, $"select col2 from {TestTableName} where col1 = {InputCol1}");
-            Assert.True(result.Rows.Count == 1);
-            Assert.True(string.Equals(result.Rows[0][0], InputCol2));
-        }
-
-        private static void TestCase_ManualEnlistment_Enlist_TxScopeComplete()
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
-            builder.Enlist = false;
-            ConnectionString = builder.ConnectionString;
-
-            using (SqlConnection connection = new SqlConnection(ConnectionString))
-            {
-                connection.Open();
-                using (TransactionScope txScope = new TransactionScope())
-                {
-                    connection.EnlistTransaction(Transactions.Transaction.Current);
-                    using (SqlCommand command = connection.CreateCommand())
-                    {
-                        command.CommandText = $"INSERT INTO {TestTableName} VALUES ({InputCol1}, '{InputCol2}')";
-                        command.ExecuteNonQuery();
-                    }
-                    txScope.Complete();
-                }
-            }
-
-            DataTable result = DataTestUtility.RunQuery(ConnectionString, $"select col2 from {TestTableName} where col1 = {InputCol1}");
-            Assert.True(result.Rows.Count == 1);
-            Assert.True(string.Equals(result.Rows[0][0], InputCol2));
-        }
-
-
-
-
-        private static string TestTableName;
-        private static string ConnectionString;
-        private const int InputCol1 = 1;
-        private const string InputCol2 = "One";
-
-        private static void RunTestSet(Action TestCase)
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
-            builder.ConnectTimeout = 5;
-
-            builder.Pooling = true;
-            ConnectionString = builder.ConnectionString;
-
-            RunTestFormat(TestCase);
-
-            builder.Pooling = false;
-            ConnectionString = builder.ConnectionString;
-
-            RunTestFormat(TestCase);
-        }
-
-        private static void RunTestFormat(Action testCase)
-        {
-            TestTableName = DataTestUtility.GenerateTableName();
-            DataTestUtility.RunNonQuery(ConnectionString, $"create table {TestTableName} (col1 int, col2 text)");
-            try
-            {
-                testCase();
-            }
-            finally
-            {
-                DataTestUtility.RunNonQuery(ConnectionString, $"drop table {TestTableName}");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs
deleted file mode 100644 (file)
index 25df7f4..0000000
+++ /dev/null
@@ -1,358 +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;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class TransactionTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestMain()
-        {
-            new TransactionTestWorker((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString).StartTest();
-        }
-
-        private sealed class TransactionTestWorker
-        {
-            private readonly string _tempTableName1;
-            private readonly string _tempTableName2;
-            private string _connectionString;
-
-            public TransactionTestWorker(string connectionString)
-            {
-                _connectionString = connectionString;
-
-                _tempTableName1 = string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_');
-                _tempTableName2 = _tempTableName1 + "_2";
-            }
-
-            public void StartTest()
-            {
-                try
-                {
-                    PrepareTables();
-
-                    CommitTransactionTest();
-                    ResetTables();
-
-                    RollbackTransactionTest();
-                    ResetTables();
-
-                    ScopedTransactionTest();
-                    ResetTables();
-
-                    ExceptionTest();
-                    ResetTables();
-
-                    ReadUncommitedIsolationLevel_ShouldReturnUncommitedData();
-                    ResetTables();
-
-                    ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction();
-                    ResetTables();
-                }
-                finally
-                {
-                    //make sure to clean up
-                    DropTempTables();
-                }
-            }
-
-            private void PrepareTables()
-            {
-                using (var conn = new SqlConnection(_connectionString))
-                {
-                    conn.Open();
-                    SqlCommand command = new SqlCommand(string.Format("CREATE TABLE [{0}]([CustomerID] [nchar](5) NOT NULL PRIMARY KEY, [CompanyName] [nvarchar](40) NOT NULL, [ContactName] [nvarchar](30) NULL)", _tempTableName1), conn);
-                    command.ExecuteNonQuery();
-                    command.CommandText = "create table " + _tempTableName2 + "(col1 int, col2 varchar(32))";
-                    command.ExecuteNonQuery();
-                }
-            }
-
-            private void DropTempTables()
-            {
-                using (var conn = new SqlConnection(_connectionString))
-                {
-                    SqlCommand command = new SqlCommand(
-                            string.Format("DROP TABLE [{0}]; DROP TABLE [{1}]", _tempTableName1, _tempTableName2), conn);
-                    conn.Open();
-                    command.ExecuteNonQuery();
-                }
-            }
-
-            public void ResetTables()
-            {
-                using (SqlConnection connection = new SqlConnection(_connectionString))
-                {
-                    connection.Open();
-                    using (SqlCommand command = new SqlCommand(string.Format("TRUNCATE TABLE [{0}]; TRUNCATE TABLE [{1}]", _tempTableName1, _tempTableName2), connection))
-                    {
-                        command.ExecuteNonQuery();
-                    }
-                }
-            }
-
-            private void CommitTransactionTest()
-            {
-                using (SqlConnection connection = new SqlConnection(_connectionString))
-                {
-                    SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'", connection);
-
-                    connection.Open();
-
-                    SqlTransaction tx = connection.BeginTransaction();
-                    command.Transaction = tx;
-
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
-                    }
-
-                    using (SqlCommand command2 = connection.CreateCommand())
-                    {
-                        command2.Transaction = tx;
-
-                        command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
-                        command2.ExecuteNonQuery();
-                    }
-
-                    tx.Commit();
-
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        int count = 0;
-                        while (reader.Read()) { count++; }
-                        Assert.True(count == 1, "Error: incorrect number of rows in table after update.");
-                        Assert.Equal(1, count);
-                    }
-                }
-            }
-
-            private void RollbackTransactionTest()
-            {
-                using (SqlConnection connection = new SqlConnection(_connectionString))
-                {
-                    SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
-                        connection);
-                    connection.Open();
-
-                    SqlTransaction tx = connection.BeginTransaction();
-                    command.Transaction = tx;
-
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
-                    }
-
-                    using (SqlCommand command2 = connection.CreateCommand())
-                    {
-                        command2.Transaction = tx;
-
-                        command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
-                        command2.ExecuteNonQuery();
-                    }
-
-                    tx.Rollback();
-
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        Assert.False(reader.HasRows, "Error Rollback Test : incorrect number of rows in table after rollback.");
-                        int count = 0;
-                        while (reader.Read()) count++;
-                        Assert.Equal(0, count);
-                    }
-
-                    connection.Close();
-                }
-            }
-
-
-            private void ScopedTransactionTest()
-            {
-                using (SqlConnection connection = new SqlConnection(_connectionString))
-                {
-                    SqlCommand command = new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
-                        connection);
-
-                    connection.Open();
-
-                    SqlTransaction tx = connection.BeginTransaction("transName");
-                    command.Transaction = tx;
-
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
-                    }
-                    using (SqlCommand command2 = connection.CreateCommand())
-                    {
-                        command2.Transaction = tx;
-
-                        command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
-                        command2.ExecuteNonQuery();
-                    }
-                    tx.Save("saveName");
-
-                    //insert another one
-                    using (SqlCommand command2 = connection.CreateCommand())
-                    {
-                        command2.Transaction = tx;
-
-                        command2.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXW2', 'XY2', 'KK' );";
-                        command2.ExecuteNonQuery();
-                    }
-
-                    tx.Rollback("saveName");
-
-                    using (SqlDataReader reader = command.ExecuteReader())
-                    {
-                        Assert.True(reader.HasRows, "Error Scoped Transaction Test : incorrect number of rows in table after rollback to save state one.");
-                        int count = 0;
-                        while (reader.Read()) count++;
-                        Assert.Equal(1, count);
-                    }
-
-                    tx.Rollback();
-
-                    connection.Close();
-                }
-            }
-
-
-            private void ExceptionTest()
-            {
-                using (SqlConnection connection = new SqlConnection(_connectionString))
-                {
-                    connection.Open();
-
-                    SqlTransaction tx = connection.BeginTransaction();
-
-                    string invalidSaveStateMessage = SystemDataResourceManager.Instance.SQL_NullEmptyTransactionName;
-                    string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery");
-                    string transactionConflictErrorMessage = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
-                    string parallelTransactionErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection");
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
-                    {
-                        SqlCommand command = new SqlCommand("sql", connection);
-                        command.ExecuteNonQuery();
-                    }, executeCommandWithoutTransactionMessage);
-
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
-                    {
-                        SqlConnection con1 = new SqlConnection(_connectionString);
-                        con1.Open();
-
-                        SqlCommand command = new SqlCommand("sql", con1);
-                        command.Transaction = tx;
-                        command.ExecuteNonQuery();
-                    }, transactionConflictErrorMessage);
-
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
-                    {
-                        connection.BeginTransaction(null);
-                    }, parallelTransactionErrorMessage);
-
-                    DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() =>
-                    {
-                        connection.BeginTransaction("");
-                    }, parallelTransactionErrorMessage);
-
-                    DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
-                    {
-                        tx.Rollback(null);
-                    }, invalidSaveStateMessage);
-
-                    DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
-                    {
-                        tx.Rollback("");
-                    }, invalidSaveStateMessage);
-
-                    DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
-                    {
-                        tx.Save(null);
-                    }, invalidSaveStateMessage);
-
-                    DataTestUtility.AssertThrowsWrapper<ArgumentException>(() =>
-                    {
-                        tx.Save("");
-                    }, invalidSaveStateMessage);
-                }
-            }
-
-            private void ReadUncommitedIsolationLevel_ShouldReturnUncommitedData()
-            {
-                using (SqlConnection connection1 = new SqlConnection(_connectionString))
-                {
-                    connection1.Open();
-                    SqlTransaction tx1 = connection1.BeginTransaction();
-
-                    using (SqlCommand command1 = connection1.CreateCommand())
-                    {
-                        command1.Transaction = tx1;
-
-                        command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
-                        command1.ExecuteNonQuery();
-                    }
-                    using (SqlConnection connection2 = new SqlConnection(_connectionString))
-                    {
-                        SqlCommand command2 =
-                            new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
-                                connection2);
-                        connection2.Open();
-                        SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadUncommitted);
-                        command2.Transaction = tx2;
-
-                        using (SqlDataReader reader = command2.ExecuteReader())
-                        {
-                            int count = 0;
-                            while (reader.Read()) count++;
-                            Assert.True(count == 1, "Should Expected 1 row because Isolation Level is read uncommitted which should return uncommitted data.");
-                        }
-
-                        tx2.Rollback();
-                        connection2.Close();
-                    }
-
-                    tx1.Rollback();
-                    connection1.Close();
-                }
-            }
-
-            private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction()
-            {
-                using (SqlConnection connection1 = new SqlConnection(_connectionString))
-                {
-                    connection1.Open();
-                    SqlTransaction tx1 = connection1.BeginTransaction();
-
-                    using (SqlCommand command1 = connection1.CreateCommand())
-                    {
-                        command1.Transaction = tx1;
-                        command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
-                        command1.ExecuteNonQuery();
-                    }
-
-                    using (SqlConnection connection2 = new SqlConnection(_connectionString))
-                    {
-                        SqlCommand command2 =
-                            new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
-                                connection2);
-
-                        connection2.Open();
-                        SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted);
-                        command2.Transaction = tx2;
-
-                        DataTestUtility.AssertThrowsWrapper<SqlException>(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout as string);
-
-                        tx2.Rollback();
-                        connection2.Close();
-                    }
-
-                    tx1.Rollback();
-                    connection1.Close();
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.snk b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.snk
deleted file mode 100644 (file)
index a6583e2..0000000
Binary files a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.snk and /dev/null differ
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs
deleted file mode 100644 (file)
index f57126e..0000000
+++ /dev/null
@@ -1,376 +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.Generic;
-using System.Collections.ObjectModel;
-using System.Data.Common;
-using System.Data.SqlTypes;
-using System.IO;
-using System.Linq;
-using System.Text;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class SqlServerTypesTest
-    {
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void GetSchemaTableTest()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn))
-            {
-                conn.Open();
-                using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo))
-                {
-                    DataTable schemaTable = reader.GetSchemaTable();
-                    DataTestUtility.AssertEqualsWithDescription(1, schemaTable.Rows.Count, "Unexpected schema table row count.");
-
-                    string columnName = (string)(string)schemaTable.Rows[0][schemaTable.Columns["ColumnName"]];
-                    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.");
-
-                    string udtAssemblyName = (string)schemaTable.Rows[0][schemaTable.Columns["UdtAssemblyQualifiedName"]];
-                    Assert.True(udtAssemblyName?.StartsWith("Microsoft.SqlServer.Types.SqlHierarchyId"), "Unexpected UDT assembly name: " + udtAssemblyName);
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void GetValueTest()
-        {
-            using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn))
-            {
-                conn.Open();
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    Assert.True(reader.Read());
-
-                    // SqlHierarchyId is part of Microsoft.SqlServer.Types, which is not supported in Core
-                    Assert.Throws<FileNotFoundException>(() => reader.GetValue(0));
-                    Assert.Throws<FileNotFoundException>(() => reader.GetSqlValue(0));
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtZeroByte()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                SqlCommand command = connection.CreateCommand();
-                command.CommandText = "select hierarchyid::Parse('/') as col0";
-                using (SqlDataReader reader = command.ExecuteReader())
-                {
-                    Assert.True(reader.Read());
-                    Assert.False(reader.IsDBNull(0));
-                    SqlBytes sqlBytes = reader.GetSqlBytes(0);
-                    Assert.False(sqlBytes.IsNull, "Expected a zero length byte array");
-                    Assert.True(sqlBytes.Length == 0, "Expected a zero length byte array");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtSqlDataReaderGetSqlBytesSequentialAccess()
-        {
-            TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.SequentialAccess);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtSqlDataReaderGetSqlBytes()
-        {
-            TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.Default);
-        }
-
-        private static void TestUdtSqlDataReaderGetSqlBytes(CommandBehavior behavior)
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                SqlCommand command = connection.CreateCommand();
-                command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
-                using (SqlDataReader reader = command.ExecuteReader(behavior))
-                {
-                    Assert.True(reader.Read());
-
-                    SqlBytes sqlBytes = null;
-
-                    sqlBytes = reader.GetSqlBytes(0);
-                    Assert.Equal("5ade", ToHexString(sqlBytes.Value));
-
-                    sqlBytes = reader.GetSqlBytes(1);
-                    Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(sqlBytes.Value));
-
-                    sqlBytes = reader.GetSqlBytes(2);
-                    Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(sqlBytes.Value));
-
-                    if (behavior == CommandBehavior.Default)
-                    {
-                        sqlBytes = reader.GetSqlBytes(0);
-                        Assert.Equal("5ade", ToHexString(sqlBytes.Value));
-                    }
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtSqlDataReaderGetBytesSequentialAccess()
-        {
-            TestUdtSqlDataReaderGetBytes(CommandBehavior.SequentialAccess);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtSqlDataReaderGetBytes()
-        {
-            TestUdtSqlDataReaderGetBytes(CommandBehavior.Default);
-        }
-
-        private static void TestUdtSqlDataReaderGetBytes(CommandBehavior behavior)
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                SqlCommand command = connection.CreateCommand();
-                command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
-                using (SqlDataReader reader = command.ExecuteReader(behavior))
-                {
-                    Assert.True(reader.Read());
-
-                    int byteCount = 0;
-                    byte[] bytes = null;
-
-                    byteCount = (int)reader.GetBytes(0, 0, null, 0, 0);
-                    Assert.True(byteCount > 0);
-                    bytes = new byte[byteCount];
-                    reader.GetBytes(0, 0, bytes, 0, bytes.Length);
-                    Assert.Equal("5ade", ToHexString(bytes));
-
-                    byteCount = (int)reader.GetBytes(1, 0, null, 0, 0);
-                    Assert.True(byteCount > 0);
-                    bytes = new byte[byteCount];
-                    reader.GetBytes(1, 0, bytes, 0, bytes.Length);
-                    Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes));
-
-                    byteCount = (int)reader.GetBytes(2, 0, null, 0, 0);
-                    Assert.True(byteCount > 0);
-                    bytes = new byte[byteCount];
-                    reader.GetBytes(2, 0, bytes, 0, bytes.Length);
-                    Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes));
-
-                    if (behavior == CommandBehavior.Default)
-                    {
-                        byteCount = (int)reader.GetBytes(0, 0, null, 0, 0);
-                        Assert.True(byteCount > 0);
-                        bytes = new byte[byteCount];
-                        reader.GetBytes(0, 0, bytes, 0, bytes.Length);
-                        Assert.Equal("5ade", ToHexString(bytes));
-                    }
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtSqlDataReaderGetStreamSequentialAccess()
-        {
-            TestUdtSqlDataReaderGetStream(CommandBehavior.SequentialAccess);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtSqlDataReaderGetStream()
-        {
-            TestUdtSqlDataReaderGetStream(CommandBehavior.Default);
-        }
-
-        private static void TestUdtSqlDataReaderGetStream(CommandBehavior behavior)
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                SqlCommand command = connection.CreateCommand();
-                command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
-                using (SqlDataReader reader = command.ExecuteReader(behavior))
-                {
-                    Assert.True(reader.Read());
-
-                    MemoryStream buffer = null;
-                    byte[] bytes = null;
-
-                    buffer = new MemoryStream();
-                    using (Stream stream = reader.GetStream(0))
-                    {
-                        stream.CopyTo(buffer);
-                    }
-                    bytes = buffer.ToArray();
-                    Assert.Equal("5ade", ToHexString(bytes));
-
-                    buffer = new MemoryStream();
-                    using (Stream stream = reader.GetStream(1))
-                    {
-                        stream.CopyTo(buffer);
-                    }
-                    bytes = buffer.ToArray();
-                    Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes));
-
-                    buffer = new MemoryStream();
-                    using (Stream stream = reader.GetStream(2))
-                    {
-                        stream.CopyTo(buffer);
-                    }
-                    bytes = buffer.ToArray();
-                    Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes));
-
-                    if (behavior == CommandBehavior.Default)
-                    {
-                        buffer = new MemoryStream();
-                        using (Stream stream = reader.GetStream(0))
-                        {
-                            stream.CopyTo(buffer);
-                        }
-                        bytes = buffer.ToArray();
-                        Assert.Equal("5ade", ToHexString(bytes));
-                    }
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtSchemaMetadata()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-                SqlCommand command = connection.CreateCommand();
-                command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
-                using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly))
-                {
-                    ReadOnlyCollection<DbColumn> columns = reader.GetColumnSchema();
-
-                    DbColumn column = null;
-
-                    // Validate Microsoft.SqlServer.Types.SqlHierarchyId, Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91
-                    column = columns[0];
-                    Assert.Equal("col0", column.ColumnName);
-                    Assert.True(column.DataTypeName.EndsWith(".hierarchyid"), $"Unexpected DataTypeName \"{column.DataTypeName}\"");
-                    Assert.NotNull(column.UdtAssemblyQualifiedName);
-                    AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlHierarchyId");
-
-                    // Validate Microsoft.SqlServer.Types.SqlGeometry, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91
-                    column = columns[1];
-                    Assert.Equal("col1", column.ColumnName);
-                    Assert.True(column.DataTypeName.EndsWith(".geometry"), $"Unexpected DataTypeName \"{column.DataTypeName}\"");
-                    Assert.NotNull(column.UdtAssemblyQualifiedName);
-                    AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeometry");
-
-                    // Validate Microsoft.SqlServer.Types.SqlGeography, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91
-                    column = columns[2];
-                    Assert.Equal("col2", column.ColumnName);
-                    Assert.True(column.DataTypeName.EndsWith(".geography"), $"Unexpected DataTypeName \"{column.DataTypeName}\"");
-                    Assert.NotNull(column.UdtAssemblyQualifiedName);
-                    AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeography");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtParameterSetSqlByteValue()
-        {
-            const string ExpectedPointValue = "POINT (1 1)";
-            SqlBytes geometrySqlBytes = null;
-            string actualtPointValue = null;
-
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-
-                using (var command = connection.CreateCommand())
-                {
-                    command.CommandText = $"SELECT geometry::Parse('{ExpectedPointValue}')";
-                    using (var reader = command.ExecuteReader())
-                    {
-                        reader.Read();
-                        geometrySqlBytes = reader.GetSqlBytes(0);
-                    }
-                }
-
-                using (var command = connection.CreateCommand())
-                {
-                    command.CommandText = "SELECT @geometry.STAsText()";
-                    var parameter = command.Parameters.AddWithValue("@geometry", geometrySqlBytes);
-                    parameter.SqlDbType = SqlDbType.Udt;
-                    parameter.UdtTypeName = "geometry";
-                    actualtPointValue = Convert.ToString(command.ExecuteScalar());
-                }
-
-                Assert.Equal(ExpectedPointValue, actualtPointValue);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestUdtParameterSetRawByteValue()
-        {
-            const string ExpectedPointValue = "POINT (1 1)";
-            byte[] geometryBytes = null;
-            string actualtPointValue = null;
-
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            {
-                connection.Open();
-
-                using (var command = connection.CreateCommand())
-                {
-                    command.CommandText = $"SELECT geometry::Parse('{ExpectedPointValue}')";
-                    using (var reader = command.ExecuteReader())
-                    {
-                        reader.Read();
-                        geometryBytes = reader.GetSqlBytes(0).Buffer;
-                    }
-                }
-
-                using (var command = connection.CreateCommand())
-                {
-                    command.CommandText = "SELECT @geometry.STAsText()";
-                    var parameter = command.Parameters.AddWithValue("@geometry", geometryBytes);
-                    parameter.SqlDbType = SqlDbType.Udt;
-                    parameter.UdtTypeName = "geometry";
-                    actualtPointValue = Convert.ToString(command.ExecuteScalar());
-                }
-
-                Assert.Equal(ExpectedPointValue, actualtPointValue);
-            }
-        }
-
-        private static void AssertSqlUdtAssemblyQualifiedName(string assemblyQualifiedName, string expectedType)
-        {
-            List<string> parts = assemblyQualifiedName.Split(',').Select(x => x.Trim()).ToList();
-
-            string type = parts[0];
-            string assembly = parts.Count < 2 ? string.Empty : parts[1];
-            string version = parts.Count < 3 ? string.Empty : parts[2];
-            string culture = parts.Count < 4 ? string.Empty : parts[3];
-            string token = parts.Count < 5 ? string.Empty : parts[4];
-
-            Assert.Equal(expectedType, type);
-            Assert.Equal("Microsoft.SqlServer.Types", assembly);
-            Assert.StartsWith("Version", version);
-            Assert.StartsWith("Culture", culture);
-            Assert.StartsWith("PublicKeyToken", token);
-        }
-
-        private static string ToHexString(byte[] bytes)
-        {
-            StringBuilder hex = new StringBuilder(bytes.Length * 2);
-            foreach (byte b in bytes)
-            {
-                hex.AppendFormat("{0:x2}", b);
-            }
-
-            return hex.ToString();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Address.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Address.cs
deleted file mode 100644 (file)
index 426edfa..0000000
+++ /dev/null
@@ -1,194 +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.Data.SqlTypes;
-
-using Microsoft.SqlServer.Server;
-
-[Serializable]
-[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, MaxByteSize = 500)]
-public class Address : INullable, IBinarySerialize
-{
-    public static Address Null { get { return new Address(true); } }
-
-    //******************************************************
-    // Constructors
-    //******************************************************
-
-    // Constructor for a null value: Address.Null
-    // fNull is not used but needed because compiler doesn't let
-    // struct have parameterless constructors
-    private Address(bool fNull)
-    {
-        m_fNotNull = false;
-        m_firstline = SqlString.Null;
-        m_secondline = SqlString.Null;
-    }
-
-    public Address(SqlString line1, SqlString line2)
-    {
-        m_firstline = line1;
-        m_secondline = line2;
-        m_fNotNull = true;
-    }
-
-    public Address()
-    {
-        m_fNotNull = false;
-        m_firstline = SqlString.Null;
-        m_secondline = SqlString.Null;
-    }
-
-    //******************************************************
-    // INullable interface
-    //******************************************************
-
-    // INullable
-    public bool IsNull
-    {
-        get { return !m_fNotNull; }
-    }
-
-    //******************************************************
-    // Common static and instance methods for SQL UDTs
-    //******************************************************
-    public const int MaxByteSize = 500;
-    public const bool IsFixedLength = false;
-    public const bool IsByteOrdered = true;
-
-    public void Read(BinaryReader r)
-    {
-        m_firstline = new SqlString(r.ReadString());
-        m_secondline = new SqlString(r.ReadString());
-        m_fNotNull = BitConverter.ToBoolean(r.ReadBytes(1), 0);
-    }
-
-    public void Write(BinaryWriter w)
-    {
-        w.Write(m_firstline.ToString());
-        w.Write(m_secondline.ToString());
-        w.Write(m_fNotNull);
-    }
-
-    public void FillFromBytes(SqlBytes value)
-    {
-        if (value.IsNull)
-        {
-            m_fNotNull = false;
-            m_firstline = SqlString.Null;
-            m_secondline = SqlString.Null;
-            return;
-        }
-
-        System.Text.UnicodeEncoding e = new System.Text.UnicodeEncoding();
-        string str = e.GetString(value.Buffer);
-
-        string[] twolines = new string[2];
-        char[] seperator = { '|' };
-        twolines = str.Split(seperator);
-
-        m_firstline = twolines[0];
-        m_secondline = twolines.Length > 1 ? twolines[1] : SqlString.Null;
-        m_fNotNull = true;
-
-        return;
-    }
-
-    public void FillBytes(SqlBytes value)
-    {
-        if (IsNull)
-        {
-            if (value.IsNull)
-                return;
-            else
-            {
-                value.SetNull();
-                return;
-            }
-        }
-
-        SqlString str;
-        if ((object)m_secondline == null || m_secondline.IsNull)
-            str = m_firstline;
-        else
-        {
-            str = string.Concat(m_firstline, "|");
-            str = string.Concat(str, m_secondline);
-        }
-
-        byte[] stringData = str.GetUnicodeBytes();
-        int i;
-        for (i = 0; i < stringData.Length; i++)
-            value[i] = stringData[i];
-        value.SetLength(i);
-
-        return;
-    }
-
-    public override string ToString()
-    {
-        if (IsNull)
-            return "Null";
-        else
-            return Value.ToString();
-    }
-
-    public static Address Parse(SqlString s)
-    {
-        if (s.IsNull)
-            return Address.Null;
-
-        string str = s.ToString();
-        string[] twolines = new string[2];
-
-        // using || to indicate the separation between
-        // address line 1 and 2, assume it won't appear
-        // in any address
-        char[] seperator = { '|', '|' };
-        twolines = str.Split(seperator);
-
-        if (twolines.Length == 2)
-            return new Address(twolines[0], twolines[1]);
-        else
-            return new Address(twolines[0], SqlString.Null);
-    }
-
-    //******************************************************
-    // Address Specific Methods
-    //******************************************************
-    public SqlString GetFirstLine()
-    {
-        return m_firstline;
-    }
-
-    public SqlString GetSecondLine()
-    {
-        return m_secondline;
-    }
-
-    public SqlString Value
-    {
-        get
-        {
-            if (m_fNotNull)
-            {
-                if (m_secondline.IsNull)
-                    return m_firstline;
-                else
-                    return string.Concat(m_firstline, m_secondline);
-            }
-            else
-                throw new SqlNullValueException();
-        }
-    }
-
-    //******************************************************
-    // Address Private Members
-    //******************************************************
-    private SqlString m_firstline;
-    private SqlString m_secondline;
-    private bool m_fNotNull; //false if null, default ctor makes it null
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Address.csproj b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Address.csproj
deleted file mode 100644 (file)
index 2885005..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <Configurations>netstandard2.0-Debug;netstandard2.0-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="Address.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Configurations.props b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Address/Configurations.props
deleted file mode 100644 (file)
index d98b6db..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Circle.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Circle.cs
deleted file mode 100644 (file)
index ac8e848..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Text;
-using System.Data.SqlTypes;
-using System.IO;
-
-using Microsoft.SqlServer.Server;
-
-[Serializable]
-[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, MaxByteSize = 30)]
-public class Circle : INullable, IBinarySerialize
-{
-    private Point1 center = new Point1();
-    private int rad;
-
-    private bool fIsNull = false;
-
-    public static Circle Null { get { return new Circle(true); } }
-
-    public const int MaxByteSize = 30;
-    public const bool IsFixedLength = true;
-    public const bool IsByteOrdered = false;
-
-
-    public void Read(BinaryReader r)
-    {
-        center = new Point1();
-        center.Read(r);
-        rad = r.ReadInt32();
-        fIsNull = BitConverter.ToBoolean(r.ReadBytes(1), 0);
-    }
-
-    public void Write(BinaryWriter w)
-    {
-        center.Write(w);
-        w.Write(rad);
-        w.Write(fIsNull);
-    }
-
-    public Circle()
-    {
-        center.X = 0;
-        center.Y = 0;
-        rad = 0;
-        fIsNull = false;
-
-    }
-
-    public Circle(bool fNull)
-    {
-        fIsNull = true;
-    }
-
-    public bool IsNull
-    {
-        get
-        {
-            return fIsNull;
-        }
-    }
-
-    public void FillFromBytes(SqlBytes data)
-    {
-        if (data.IsNull)
-        {
-            fIsNull = true;
-            return;
-        }
-
-        if (data.Length != 12)
-            throw new ArgumentException();
-        byte[] value = data.Value;
-
-        //read x1,y1,x2,y2
-        center.X = BitConverter.ToInt32(value, 0);
-        center.Y = BitConverter.ToInt32(value, 4);
-        rad = BitConverter.ToInt32(value, 8);
-    }
-
-    public void FillBytes(SqlBytes data)
-    {
-        if (fIsNull)
-        {
-            if (data.IsNull)
-                return;
-            else
-            {
-                data.SetNull();
-                return;
-            }
-        }
-
-        byte[] bigbytes = new byte[12];
-        byte[] bytes = BitConverter.GetBytes(center.X);
-        bytes.CopyTo(bigbytes, 0);
-        bytes = BitConverter.GetBytes(center.Y);
-        bytes.CopyTo(bigbytes, 4);
-
-        bytes = BitConverter.GetBytes(rad);
-        bytes.CopyTo(bigbytes, 8);
-
-        int i;
-        for (i = 0; i < bigbytes.Length; i++)
-            data[i] = bigbytes[i];
-        data.SetLength(i);
-
-    }
-
-    //it should be x1,y1,x2,y2
-    public static Circle Parse(SqlString data)
-    {
-        string[] array = data.Value.Split(new char[] { ',' });
-
-        if (array.Length != 3)
-            throw new ArgumentException();
-        Circle circ = new Circle();
-
-        circ.center.X = int.Parse(array[0]);
-        circ.center.Y = int.Parse(array[1]);
-        circ.rad = int.Parse(array[2]);
-        return circ;
-    }
-
-    public override string ToString()
-    {
-        StringBuilder builder = new StringBuilder();
-        builder.Append(center.ToString());
-        builder.Append(",");
-        builder.Append(rad.ToString());
-
-        return builder.ToString();
-    }
-
-    public Point1 Center
-    {
-        get
-        {
-            return center;
-        }
-    }
-
-    public int Radius
-    {
-        get
-        {
-            return rad;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Circle.csproj b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Circle.csproj
deleted file mode 100644 (file)
index 7e70f7e..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <Configurations>netstandard2.0-Debug;netstandard2.0-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="Circle.cs" />
-    <Compile Include="Point1.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Configurations.props b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Configurations.props
deleted file mode 100644 (file)
index d98b6db..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Point1.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Circle/Point1.cs
deleted file mode 100644 (file)
index 54b6699..0000000
+++ /dev/null
@@ -1,182 +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.Data.SqlTypes;
-using System.Text;
-
-using Microsoft.SqlServer.Server;
-
-[Serializable]
-[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = true, MaxByteSize = 9)]
-public class Point1 : INullable, IBinarySerialize
-{
-    private int x;
-    private int y;
-    private bool fIsNull = false;
-
-    public static Point1 Null { get { return new Point1(true); } }
-    public const int MaxByteSize = 9;
-    public const bool IsFixedLength = true;
-    public const bool IsByteOrdered = false;
-
-    public void Read(BinaryReader r)
-    {
-        x = r.ReadInt32();
-        y = r.ReadInt32();
-        fIsNull = BitConverter.ToBoolean(r.ReadBytes(1), 0);
-    }
-
-    public void Write(BinaryWriter w)
-    {
-        w.Write(x);
-        w.Write(y);
-        w.Write(fIsNull);
-    }
-
-    public Point1()
-    {
-        x = 0;
-        y = 0;
-        fIsNull = false;
-    }
-
-    public Point1(bool fNull)
-    {
-        fIsNull = true;
-    }
-
-    public Point1(int ix, int iy)
-    {
-        x = ix;
-        y = iy;
-        fIsNull = false;
-    }
-
-    public bool IsNull
-    {
-        get
-        {
-            return fIsNull;
-        }
-    }
-
-    public void FillFromBytesInternal(byte[] data)
-    {
-        if (data.Length != 9)
-            throw new ArgumentException();
-
-        x = BitConverter.ToInt32(data, 0);
-        y = BitConverter.ToInt32(data, 4);
-
-    }
-
-    public void FillFromBytes(SqlBytes value)
-    {
-        if (value.IsNull)
-        {
-            fIsNull = true;
-            return;
-        }
-
-        byte[] bytes = value.Value;
-        FillFromBytesInternal(bytes);
-
-        fIsNull = false;
-        return;
-    }
-
-    public void FillBytes(SqlBytes value)
-    {
-        if (fIsNull)
-        {
-            if (value.IsNull)
-                return;
-            else
-            {
-                value.SetNull();
-                return;
-            }
-        }
-
-        byte[] bigbytes = new byte[9];
-        byte[] bytes = BitConverter.GetBytes(x);
-        bytes.CopyTo(bigbytes, 0);
-        bytes = BitConverter.GetBytes(y);
-        bytes.CopyTo(bigbytes, 4);
-
-        int i;
-        for (i = 0; i < bigbytes.Length; i++)
-            value[i] = bigbytes[i];
-        value.SetLength(i);
-
-        return;
-    }
-
-    public static Point1 Parse(SqlString data)
-    {
-        string[] array = data.Value.Split(new char[] { ',' });
-        int x;
-        int y;
-
-        if (array.Length != 2)
-            throw new ArgumentException();
-        x = int.Parse(array[0]);
-        y = int.Parse(array[1]);
-
-        return new Point1(x, y);
-    }
-
-    public override string ToString()
-    {
-        StringBuilder builder = new StringBuilder();
-        builder.Append(x);
-        builder.Append(",");
-        builder.Append(y);
-
-        return builder.ToString();
-    }
-
-    public int X
-    {
-        get
-        {
-            return x;
-        }
-        set
-        {
-            x = value;
-        }
-    }
-
-    public int Y
-    {
-        get
-        {
-            return y;
-        }
-        set
-        {
-            y = value;
-        }
-    }
-
-    public double Distance()
-    {
-        return DistanceFromXY(0, 0);
-    }
-
-    public double DistanceFrom(Point1 pFrom)
-    {
-        return DistanceFromXY(pFrom.x, pFrom.y);
-    }
-
-    public double DistanceFromXY(int ix, int iy)
-    {
-        return Math.Sqrt(Math.Pow(ix - x, 2.0) + Math.Pow(iy - y, 2.0));
-    }
-
-    public const int MaxByteSizeValue = 12;
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Configurations.props b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Configurations.props
deleted file mode 100644 (file)
index d98b6db..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Line.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Line.cs
deleted file mode 100644 (file)
index a6b1859..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Text;
-using System.Data.SqlTypes;
-using System.IO;
-
-using Microsoft.SqlServer.Server;
-
-[Serializable]
-[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, MaxByteSize = 20)]
-public class Line : INullable, IBinarySerialize
-{
-    private Point start = new Point();
-    private Point end = new Point();
-
-    private bool fIsNull = false;
-
-    public static Line Null { get { return new Line(true); } }
-
-    public const int MaxByteSize = 20;
-    public const bool IsFixedLength = true;
-    public const bool IsByteOrdered = false;
-
-    public Line()
-    {
-        start.X = start.Y = end.X = end.Y = 0;
-    }
-
-    public Line(bool fNull)
-    {
-        fIsNull = true;
-    }
-
-    public Line(Point ix, Point iy)
-    {
-        start.X = ix.X;
-        start.Y = ix.Y;
-        end.X = iy.X;
-        end.Y = iy.Y;
-    }
-
-    public bool IsNull
-    {
-        get
-        {
-            return fIsNull;
-        }
-    }
-
-    public void Read(BinaryReader r)
-    {
-        start = new Point();
-        start.Read(r);
-        end = new Point();
-        end.Read(r);
-        fIsNull = BitConverter.ToBoolean(r.ReadBytes(1), 0);
-    }
-
-    public void Write(BinaryWriter w)
-    {
-        start.Write(w);
-        end.Write(w);
-        w.Write(fIsNull);
-    }
-
-    public void FillFromBytes(SqlBytes data)
-    {
-        if (data.IsNull)
-        {
-            fIsNull = true;
-            return;
-        }
-
-        if (data.Length != 16)
-            throw new ArgumentException();
-        byte[] value = data.Value;
-
-        //read x1,y1,x2,y2
-        start.X = BitConverter.ToInt32(value, 0);
-        start.Y = BitConverter.ToInt32(value, 4);
-        end.X = BitConverter.ToInt32(value, 8);
-        end.Y = BitConverter.ToInt32(value, 12);
-    }
-
-    public void FillBytes(SqlBytes data)
-    {
-        if (fIsNull)
-        {
-            if (data.IsNull)
-                return;
-            else
-            {
-                data.SetNull();
-                return;
-            }
-        }
-
-        byte[] bigbytes = new byte[16];
-        byte[] bytes = BitConverter.GetBytes(start.X);
-        bytes.CopyTo(bigbytes, 0);
-        bytes = BitConverter.GetBytes(start.Y);
-        bytes.CopyTo(bigbytes, 4);
-
-        bytes = BitConverter.GetBytes(end.X);
-        bytes.CopyTo(bigbytes, 8);
-        bytes = BitConverter.GetBytes(end.Y);
-        bytes.CopyTo(bigbytes, 12);
-
-        int i;
-        for (i = 0; i < bigbytes.Length; i++)
-            data[i] = bigbytes[i];
-        data.SetLength(i);
-    }
-
-    //it should be x1,y1,x2,y2
-    public static Line Parse(SqlString data)
-    {
-        string[] array = data.Value.Split(new char[] { ',' });
-
-        if (array.Length != 4)
-            throw new ArgumentException();
-        Line line = new Line();
-        line.start.X = int.Parse(array[0]);
-        line.start.Y = int.Parse(array[1]);
-        line.end.X = int.Parse(array[2]);
-        line.end.Y = int.Parse(array[3]);
-
-        return line;
-    }
-
-    public override string ToString()
-    {
-        StringBuilder builder = new StringBuilder();
-        builder.Append(start.ToString());
-        builder.Append(",");
-        builder.Append(end.ToString());
-
-        return builder.ToString();
-    }
-
-    public double Length()
-    {
-        return end.DistanceFrom(start);
-    }
-
-    public Point Start
-    {
-        get
-        {
-            return start;
-        }
-    }
-
-    public Point End
-    {
-        get
-        {
-            return end;
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Point.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Point.cs
deleted file mode 100644 (file)
index ee3fecd..0000000
+++ /dev/null
@@ -1,181 +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.Data.SqlTypes;
-using System.Text;
-
-using Microsoft.SqlServer.Server;
-
-[Serializable]
-[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = true, MaxByteSize = 9)]
-public class Point : INullable, IBinarySerialize
-{
-    private int x;
-    private int y;
-    private bool fIsNull = false;
-
-    public static Point Null { get { return new Point(true); } }
-    public const int MaxByteSize = 9;
-    public const bool IsFixedLength = true;
-    public const bool IsByteOrdered = false;
-
-    public void Read(BinaryReader r)
-    {
-        x = r.ReadInt32();
-        y = r.ReadInt32();
-        fIsNull = BitConverter.ToBoolean(r.ReadBytes(1), 0);
-    }
-
-    public void Write(BinaryWriter w)
-    {
-        w.Write(x);
-        w.Write(y);
-        w.Write(fIsNull);
-    }
-
-    public Point()
-    {
-        x = 0;
-        y = 0;
-        fIsNull = false;
-    }
-
-    public Point(bool fNull)
-    {
-        fIsNull = true;
-    }
-
-    public Point(int ix, int iy)
-    {
-        x = ix;
-        y = iy;
-        fIsNull = false;
-    }
-
-    public bool IsNull
-    {
-        get
-        {
-            return fIsNull;
-        }
-    }
-
-    public void FillFromBytesInternal(byte[] data)
-    {
-        if (data.Length != 9)
-            throw new ArgumentException();
-
-        x = BitConverter.ToInt32(data, 0);
-        y = BitConverter.ToInt32(data, 4);
-    }
-
-    public void FillFromBytes(SqlBytes value)
-    {
-        if (value.IsNull)
-        {
-            fIsNull = true;
-            return;
-        }
-
-        byte[] bytes = value.Value;
-        FillFromBytesInternal(bytes);
-
-        fIsNull = false;
-        return;
-    }
-
-    public void FillBytes(SqlBytes value)
-    {
-        if (fIsNull)
-        {
-            if (value.IsNull)
-                return;
-            else
-            {
-                value.SetNull();
-                return;
-            }
-        }
-
-        byte[] bigbytes = new byte[9];
-        byte[] bytes = BitConverter.GetBytes(x);
-        bytes.CopyTo(bigbytes, 0);
-        bytes = BitConverter.GetBytes(y);
-        bytes.CopyTo(bigbytes, 4);
-
-        int i;
-        for (i = 0; i < bigbytes.Length; i++)
-            value[i] = bigbytes[i];
-        value.SetLength(i);
-
-        return;
-    }
-
-    public static Point Parse(SqlString data)
-    {
-        string[] array = data.Value.Split(new char[] { ',' });
-        int x;
-        int y;
-
-        if (array.Length != 2)
-            throw new ArgumentException();
-        x = int.Parse(array[0]);
-        y = int.Parse(array[1]);
-
-        return new Point(x, y);
-    }
-
-    public override string ToString()
-    {
-        StringBuilder builder = new StringBuilder();
-        builder.Append(x);
-        builder.Append(",");
-        builder.Append(y);
-
-        return builder.ToString();
-    }
-
-    public int X
-    {
-        get
-        {
-            return x;
-        }
-        set
-        {
-            x = value;
-        }
-    }
-
-    public int Y
-    {
-        get
-        {
-            return y;
-        }
-        set
-        {
-            y = value;
-        }
-    }
-
-    public double Distance()
-    {
-        return DistanceFromXY(0, 0);
-    }
-
-    public double DistanceFrom(Point pFrom)
-    {
-        return DistanceFromXY(pFrom.x, pFrom.y);
-    }
-
-    public double DistanceFromXY(int ix, int iy)
-    {
-        return Math.Sqrt(Math.Pow(ix - x, 2.0) + Math.Pow(iy - y, 2.0));
-    }
-
-    public const int MaxByteSizeValue = 12;
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Shapes.csproj b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Shapes/Shapes.csproj
deleted file mode 100644 (file)
index 23e8e2e..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <Configurations>netstandard2.0-Debug;netstandard2.0-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="Line.cs" />
-    <Compile Include="Point.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Configurations.props b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Configurations.props
deleted file mode 100644 (file)
index d98b6db..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Utf8String.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Utf8String.cs
deleted file mode 100644 (file)
index 677250b..0000000
+++ /dev/null
@@ -1,314 +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.Data.SqlTypes;
-using System.Globalization;
-
-using Microsoft.SqlServer.Server;
-
-namespace Microsoft.Samples.SqlServer
-{
-    [Serializable]
-    [Microsoft.SqlServer.Server.SqlUserDefinedType(Microsoft.SqlServer.Server.Format.UserDefined, IsByteOrdered = true, MaxByteSize = 8000)]
-    public class Utf8String : INullable, IComparable, Microsoft.SqlServer.Server.IBinarySerialize
-    {
-        #region conversion to/from Unicode strings
-        /// <summary>
-        /// Parse the given string and return a utf8 representation for it.
-        /// </summary>
-        /// <param name="sqlString"></param>
-        /// <returns></returns>
-        public static Utf8String Parse(SqlString sqlString)
-        {
-            if (sqlString.IsNull)
-                return Utf8String.Null;
-
-            return new Utf8String(sqlString.Value);
-        }
-
-        /// <summary>
-        /// Get/Set the utf8 bytes for this string.
-        /// </summary>
-        public SqlBinary Utf8Bytes
-        {
-            get
-            {
-                if (this.IsNull)
-                    return SqlBinary.Null;
-
-                if (this.m_Bytes != null)
-                    return this.m_Bytes;
-
-                if (this.m_String != null)
-                {
-                    this.m_Bytes = System.Text.Encoding.UTF8.GetBytes(this.m_String);
-                    return new SqlBinary(this.m_Bytes);
-                }
-
-                throw new NotSupportedException("cannot return bytes for empty instance");
-            }
-            set
-            {
-                if (value.IsNull)
-                {
-                    this.m_Bytes = null;
-                    this.m_String = null;
-                }
-                else
-                {
-                    this.m_Bytes = value.Value;
-                    this.m_String = null;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Return a unicode string for this type.
-        /// </summary>
-        [Microsoft.SqlServer.Server.SqlMethod(IsDeterministic = true, IsPrecise = true, DataAccess = Microsoft.SqlServer.Server.DataAccessKind.None, SystemDataAccess = Microsoft.SqlServer.Server.SystemDataAccessKind.None)]
-        public override string ToString()
-        {
-            if (this.IsNull)
-                return null;
-
-            if (this.m_String != null)
-                return this.m_String;
-
-            if (this.m_Bytes != null)
-            {
-                this.m_String = System.Text.Encoding.UTF8.GetString(this.m_Bytes);
-                return this.m_String;
-            }
-
-            throw new NotSupportedException("dont know how to return string from empty instance");
-        }
-
-        /// <summary>
-        /// Return a SqlStr
-        /// </summary>
-        public SqlString ToSqlString()
-        {
-            if (this.IsNull)
-                return SqlString.Null;
-
-            return new SqlString(this.ToString());
-        }
-
-        private SqlString GetSortKeyUsingCultureInternal(CultureInfo culture, bool ignoreCase,
-            bool ignoreNonSpace, bool ignoreWidth)
-        {
-            if (this.IsNull)
-                return SqlString.Null;
-
-            SqlCompareOptions compareOptions = SqlCompareOptions.None;
-            if (ignoreCase)
-                compareOptions = compareOptions | SqlCompareOptions.IgnoreCase;
-
-            if (ignoreNonSpace)
-                compareOptions = compareOptions | SqlCompareOptions.IgnoreNonSpace;
-
-            if (ignoreWidth)
-                compareOptions = compareOptions | SqlCompareOptions.IgnoreWidth;
-
-            return new SqlString(this.ToString(), culture.LCID, compareOptions);
-        }
-
-        [Microsoft.SqlServer.Server.SqlMethod(IsDeterministic = true, IsPrecise = true)]
-        public SqlString GetSortKeyUsingCulture(string cultureName, bool ignoreCase,
-            bool ignoreNonSpace, bool ignoreWidth)
-        {
-            CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
-            if (culture == null)
-                throw new ArgumentException(string.Format(
-                    CultureInfo.InvariantCulture,
-                    "Culture {0} not recognized.", cultureName));
-
-            return this.GetSortKeyUsingCultureInternal(culture, ignoreCase,
-                ignoreNonSpace, ignoreWidth);
-        }
-
-        [Microsoft.SqlServer.Server.SqlMethod(IsDeterministic = false)]
-        public SqlString GetSortKey(bool ignoreCase, bool ignoreNonSpace, bool ignoreWidth)
-        {
-            return this.GetSortKeyUsingCultureInternal(CultureInfo.CurrentCulture,
-                ignoreCase, ignoreNonSpace, ignoreWidth);
-        }
-
-        #endregion
-
-        #region comparison operators
-        public override bool Equals(object obj)
-        {
-            return this.CompareTo(obj) == 0;
-        }
-
-        public static bool operator ==(Utf8String utf8String, Utf8String other)
-        {
-            return utf8String.Equals(other);
-        }
-
-        public static bool operator !=(Utf8String utf8String, Utf8String other)
-        {
-            return !(utf8String == other);
-        }
-
-        public static bool operator <(Utf8String utf8String, Utf8String other)
-        {
-            return (utf8String.CompareTo(other) < 0);
-        }
-
-        public static bool operator >(Utf8String utf8String, Utf8String other)
-        {
-            return (utf8String.CompareTo(other) > 0);
-        }
-
-        private int CompareUsingCultureInternal(Utf8String other, CultureInfo culture, bool ignoreCase,
-            bool ignoreNonSpace, bool ignoreWidth)
-        {
-            // By definition
-            if (other == null)
-                return 1;
-
-            if (this.IsNull)
-                if (other.IsNull)
-                    return 0;
-                else
-                    return -1;
-
-            if (other.IsNull)
-                return 1;
-
-            return this.GetSortKeyUsingCultureInternal(culture, ignoreCase, ignoreNonSpace,
-                ignoreWidth).CompareTo(other.GetSortKeyUsingCultureInternal(culture, ignoreCase,
-                ignoreNonSpace, ignoreWidth));
-        }
-
-        public int CompareUsingCulture(Utf8String other, string cultureName, bool ignoreCase,
-            bool ignoreNonSpace, bool ignoreWidth)
-        {
-            CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
-            if (culture == null)
-                throw new ArgumentException(string.Format(
-                    CultureInfo.InvariantCulture,
-                    "Culture {0} not recognized.", cultureName));
-
-            return this.CompareUsingCultureInternal(other, culture, ignoreCase,
-                ignoreNonSpace, ignoreWidth);
-        }
-
-        public int Compare(Utf8String other, bool ignoreCase,
-            bool ignoreNonSpace, bool ignoreWidth)
-        {
-            return this.CompareUsingCultureInternal(other, CultureInfo.CurrentCulture, ignoreCase,
-                ignoreNonSpace, ignoreWidth);
-        }
-
-        public override int GetHashCode()
-        {
-            if (this.IsNull)
-                return 0;
-
-            return this.ToString().GetHashCode();
-        }
-
-        public int CompareTo(object obj)
-        {
-            if (obj == null)
-                return 1; //by definition
-
-            Utf8String s = obj as Utf8String;
-
-            if (s == null)
-                throw new ArgumentException("the argument to compare is not a Utf8String");
-
-            if (this.IsNull)
-            {
-                if (s.IsNull)
-                    return 0;
-
-                return -1;
-            }
-
-            if (s.IsNull)
-                return 1;
-
-            return this.ToString().CompareTo(s.ToString());
-        }
-
-        #endregion
-
-        #region private state and constructors
-        private string m_String;
-
-        private byte[] m_Bytes;
-
-        public Utf8String(string value)
-        {
-            this.m_String = value;
-        }
-
-        public Utf8String(byte[] bytes)
-        {
-            this.m_Bytes = bytes;
-        }
-        #endregion
-
-        #region UserDefinedType boilerplate code
-
-        public bool IsNull
-        {
-            get
-            {
-                return this.m_String == null && this.m_Bytes == null;
-            }
-        }
-
-        public static Utf8String Null
-        {
-            get
-            {
-                Utf8String str = new Utf8String((string)null);
-
-                return str;
-            }
-        }
-
-        public Utf8String()
-        {
-        }
-        #endregion
-
-        #region IBinarySerialize Members
-        public void Write(System.IO.BinaryWriter w)
-        {
-            byte header = (byte)(this.IsNull ? 1 : 0);
-
-            w.Write(header);
-            if (header == 1)
-                return;
-
-            byte[] bytes = this.Utf8Bytes.Value;
-
-            w.Write(bytes.Length);
-            w.Write(bytes);
-        }
-
-        public void Read(System.IO.BinaryReader r)
-        {
-            byte header = r.ReadByte();
-
-            if ((header & 1) > 0)
-            {
-                this.m_Bytes = null;
-                return;
-            }
-
-            int length = r.ReadInt32();
-
-            this.m_Bytes = r.ReadBytes(length);
-        }
-        #endregion
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Utf8String.csproj b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UDTs/Utf8String/Utf8String.csproj
deleted file mode 100644 (file)
index a7d615f..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <Configurations>netstandard2.0-Debug;netstandard2.0-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="Utf8String.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtBulkCopyTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtBulkCopyTest.cs
deleted file mode 100644 (file)
index af51e58..0000000
+++ /dev/null
@@ -1,124 +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;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class UdtBulkCopyTest
-    {
-        private string _connStr;
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void RunCopyTest()
-        {
-            _connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { InitialCatalog = DataTestUtility.UdtTestDbName }).ConnectionString;
-            SqlConnection conn = new SqlConnection(_connStr);
-
-            string cities = DataTestUtility.GetUniqueNameForSqlServer("UdtBulkCopy_cities");
-            string customers = DataTestUtility.GetUniqueNameForSqlServer("UdtBulkCopy_customers");
-            string circles = DataTestUtility.GetUniqueNameForSqlServer("UdtBulkCopy_circles");
-
-            conn.Open();
-            try
-            {
-                ExecuteNonQueryCommand($"create table {cities} (name sysname, location Point)", _connStr);
-                ExecuteNonQueryCommand($"create table {customers} (name nvarchar(30), address Address)", _connStr);
-                ExecuteNonQueryCommand($"create table {circles} (num int, def Circle)", _connStr);
-
-                string expectedResults =
-                    "ColumnName[0] = name" + Environment.NewLine +
-                    "DataType[0] = nvarchar" + Environment.NewLine +
-                    "FieldType[0] = System.String" + Environment.NewLine +
-                    "ColumnName[1] = location" + Environment.NewLine +
-                    "DataType[1] = UdtTestDb.dbo.Point" + Environment.NewLine +
-                    "FieldType[1] = Point" + Environment.NewLine +
-                    "   redmond, p.X =   3, p.Y =   3, p.Distance() = 5" + Environment.NewLine +
-                    "  bellevue, p.X =   6, p.Y =   6, p.Distance() = 10" + Environment.NewLine +
-                    "   seattle, p.X =  10, p.Y =  10, p.Distance() = 14.866068747318506" + Environment.NewLine +
-                    "  portland, p.X =  20, p.Y =  20, p.Distance() = 25" + Environment.NewLine +
-                    "        LA, p.X =   3, p.Y =   3, p.Distance() = 5" + Environment.NewLine +
-                    "       SFO, p.X =   6, p.Y =   6, p.Distance() = 10" + Environment.NewLine +
-                    " beaverton, p.X =  10, p.Y =  10, p.Distance() = 14.866068747318506" + Environment.NewLine +
-                    "  new york, p.X =  20, p.Y =  20, p.Distance() = 25" + Environment.NewLine +
-                    "     yukon, p.X =  20, p.Y =  20, p.Distance() = 32.01562118716424" + Environment.NewLine;
-
-                CopyTableTest(_connStr, "cities", cities, expectedResults);
-
-                expectedResults =
-                    "ColumnName[0] = name" + Environment.NewLine +
-                    "DataType[0] = nvarchar" + Environment.NewLine +
-                    "FieldType[0] = System.String" + Environment.NewLine +
-                    "ColumnName[1] = address" + Environment.NewLine +
-                    "DataType[1] = UdtTestDb.dbo.Address" + Environment.NewLine +
-                    "FieldType[1] = Address" + Environment.NewLine +
-                    "     first, Address 1  Address 2" + Environment.NewLine +
-                    "    second, 123 Park Lane  New York" + Environment.NewLine +
-                    "     third, 21 Forest grove  Portland" + Environment.NewLine +
-                    "    fourth, 34 Lake Blvd  Seattle" + Environment.NewLine +
-                    "     fifth, A2 Meadows  Bellevue" + Environment.NewLine;
-
-                CopyTableTest(_connStr, "customers", customers, expectedResults);
-
-                expectedResults =
-                    "ColumnName[0] = num" + Environment.NewLine +
-                    "DataType[0] = int" + Environment.NewLine +
-                    "FieldType[0] = System.Int32" + Environment.NewLine +
-                    "ColumnName[1] = def" + Environment.NewLine +
-                    "DataType[1] = UdtTestDb.dbo.Circle" + Environment.NewLine +
-                    "FieldType[1] = Circle" + Environment.NewLine +
-                    "         1, Center = 1,2" + Environment.NewLine +
-                    "         2, Center = 3,4" + Environment.NewLine +
-                    "         3, Center = 11,23" + Environment.NewLine +
-                    "         4, Center = 444,555" + Environment.NewLine +
-                    "         5, Center = 1,2" + Environment.NewLine +
-                    "         6, Center = 3,4" + Environment.NewLine +
-                    "         7, Center = 11,23" + Environment.NewLine +
-                    "         8, Center = 444,245" + Environment.NewLine;
-
-                CopyTableTest(_connStr, "circles", circles, expectedResults);
-            }
-            finally
-            {
-                ExecuteNonQueryCommand($"drop table {cities}", _connStr);
-                ExecuteNonQueryCommand($"drop table {customers}", _connStr);
-                ExecuteNonQueryCommand($"drop table {circles}", _connStr);
-            }
-        }
-
-        private void ExecuteNonQueryCommand(string cmdText, string connStr)
-        {
-            using (SqlConnection conn = new SqlConnection(connStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                conn.Open();
-                cmd.CommandText = cmdText;
-                cmd.ExecuteNonQuery();
-            }
-        }
-
-        private void CopyTableTest(string connStr, string sourceTable, string targetTable, string expectedResults)
-        {
-            using (SqlConnection srcConn = new SqlConnection(connStr))
-            {
-                srcConn.Open();
-
-                SqlCommand cmd = srcConn.CreateCommand();
-
-                cmd.CommandText = "select * from " + sourceTable;
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                using (SqlBulkCopy bc = new SqlBulkCopy(connStr))
-                {
-                    bc.DestinationTableName = targetTable;
-                    bc.WriteToServer(reader);
-                }
-                cmd.CommandText = "select * from " + targetTable;
-
-                DataTestUtility.AssertEqualsWithDescription(
-                    expectedResults, UdtTestHelpers.DumpReaderString(cmd.ExecuteReader()),
-                    "Unexpected bulk copy results.");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs
deleted file mode 100644 (file)
index 4dc7e96..0000000
+++ /dev/null
@@ -1,293 +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.Data.SqlTypes;
-using Microsoft.Samples.SqlServer;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class UdtTest
-    {
-        private string _connStr;
-
-        public UdtTest()
-        {
-            _connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { InitialCatalog = DataTestUtility.UdtTestDbName }).ConnectionString;
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void ReaderTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                SqlCommand com = new SqlCommand()
-                {
-                    Connection = conn,
-                    CommandText = "select * from TestTable"
-                };
-
-                SqlDataReader reader = com.ExecuteReader();
-
-                Utf8String[] expectedValues =
-                    {
-                        new Utf8String("a"),
-                        new Utf8String("is"),
-                        new Utf8String("test"),
-                        new Utf8String("this")
-                    };
-                int currentValue = 0;
-                do
-                {
-                    while (reader.Read())
-                    {
-                        DataTestUtility.AssertEqualsWithDescription(1, reader.FieldCount, "Unexpected FieldCount.");
-                        DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue], reader.GetValue(0), "Unexpected Value.");
-                        DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue], reader.GetSqlValue(0), "Unexpected SQL Value.");
-
-                        currentValue++;
-                    }
-                }
-                while (reader.NextResult());
-
-                DataTestUtility.AssertEqualsWithDescription(expectedValues.Length, currentValue, "Received less values than expected.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void ExecuteScalarTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                SqlCommand com = new SqlCommand()
-                {
-                    Connection = conn,
-                    CommandText = "select * from TestTable"
-                };
-
-                DataTestUtility.AssertEqualsWithDescription(new Utf8String("a"), com.ExecuteScalar(), "Unexpected value.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void InputParameterTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                SqlCommand com = new SqlCommand()
-                {
-                    Connection = conn,
-                    CommandText = "insert into TestTable values (@p);" +
-                                  "SELECT * FROM TestTable"
-                };
-                SqlParameter p = com.Parameters.Add("@p", SqlDbType.Udt);
-                p.UdtTypeName = "Utf8String";
-                p.Value = new Utf8String("this is an input param test");
-
-                using (SqlTransaction trans = conn.BeginTransaction())
-                {
-                    com.Transaction = trans;
-                    SqlDataReader reader = com.ExecuteReader();
-
-                    Utf8String[] expectedValues =
-                    {
-                        new Utf8String("a"),
-                        new Utf8String("is"),
-                        new Utf8String("test"),
-                        new Utf8String("this"),
-                        new Utf8String("this is an input param test")
-                    };
-
-                    int currentValue = 0;
-                    do
-                    {
-                        while (reader.Read())
-                        {
-                            DataTestUtility.AssertEqualsWithDescription(1, reader.FieldCount, "Unexpected FieldCount.");
-                            DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue], reader.GetValue(0), "Unexpected Value.");
-                            currentValue++;
-                        }
-                    }
-                    while (reader.NextResult());
-                    DataTestUtility.AssertEqualsWithDescription(expectedValues.Length, currentValue, "Received less values than expected.");
-
-                    reader.Close();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void OutputParameterTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                SqlCommand com = new SqlCommand()
-                {
-                    Connection = conn,
-                    CommandText = "UDTTest",
-                    CommandType = CommandType.StoredProcedure
-                };
-
-                SqlParameter p = com.Parameters.Add("@value", SqlDbType.Udt);
-                p.UdtTypeName = "Utf8String";
-                p.Direction = ParameterDirection.Output;
-
-                SqlDataReader reader = com.ExecuteReader();
-
-                do
-                {
-                    while (reader.Read())
-                    {
-                        DataTestUtility.AssertEqualsWithDescription(0, reader.FieldCount, "Should not have any reader results.");
-                    }
-                }
-                while (reader.NextResult());
-
-                reader.Close();
-
-                DataTestUtility.AssertEqualsWithDescription(new Utf8String("this is an outparam test"), p.Value, "Unexpected parameter value.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void FillTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-                DataSet ds = new DataSet();
-
-                SqlDataAdapter adapter = new SqlDataAdapter("select * from TestTable", conn);
-                adapter.Fill(ds);
-
-                Utf8String[] expectedValues =
-                {
-                    new Utf8String("a"),
-                    new Utf8String("is"),
-                    new Utf8String("test"),
-                    new Utf8String("this")
-                };
-                VerifyDataSet(ds, expectedValues);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UpdateTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-                DataSet ds = new DataSet();
-
-                using (SqlTransaction trans = conn.BeginTransaction())
-                {
-                    SqlDataAdapter adapter = new SqlDataAdapter("select * from TestTable", conn);
-                    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
-                    adapter.SelectCommand.Transaction = trans;
-
-                    adapter.Fill(ds);
-
-                    ds.Tables[0].Rows[0][0] = new Utf8String("updated");
-
-                    adapter.Update(ds);
-
-                    ds.Reset();
-
-                    adapter.Fill(ds);
-                }
-
-                Utf8String[] expectedValues =
-                {
-                    new Utf8String("is"),
-                    new Utf8String("test"),
-                    new Utf8String("this"),
-                    new Utf8String("updated")
-                };
-                VerifyDataSet(ds, expectedValues);
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void NullTest()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                SqlCommand com = new SqlCommand()
-                {
-                    Connection = conn,
-                    CommandText = "insert into TestTableNull values (@p);" +
-                                  "SELECT * FROM TestTableNull"
-                };
-                SqlParameter p = com.Parameters.Add("@p", SqlDbType.Udt);
-                p.UdtTypeName = "Utf8String";
-                p.Value = DBNull.Value;
-
-                using (SqlTransaction trans = conn.BeginTransaction())
-                {
-                    com.Transaction = trans;
-                    SqlDataReader reader = com.ExecuteReader();
-
-                    Utf8String[] expectedValues =
-                        {
-                            new Utf8String("this"),
-                            new Utf8String("is"),
-                            new Utf8String("a"),
-                            new Utf8String("test")
-                        };
-
-                    int currentValue = 0;
-                    do
-                    {
-                        while (reader.Read())
-                        {
-                            DataTestUtility.AssertEqualsWithDescription(1, reader.FieldCount, "Unexpected FieldCount.");
-                            if (currentValue < expectedValues.Length)
-                            {
-                                DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue], reader.GetValue(0), "Unexpected Value.");
-                                DataTestUtility.AssertEqualsWithDescription(expectedValues[currentValue], reader.GetSqlValue(0), "Unexpected SQL Value.");
-                            }
-                            else
-                            {
-                                DataTestUtility.AssertEqualsWithDescription(DBNull.Value, reader.GetValue(0), "Unexpected Value.");
-
-                                Utf8String sqlValue = (Utf8String)reader.GetSqlValue(0);
-                                INullable iface = sqlValue as INullable;
-                                Assert.True(iface != null, "Expected interface cast to return a non-null value.");
-                                Assert.True(iface.IsNull, "Expected interface cast to have IsNull==true.");
-                            }
-
-                            currentValue++;
-                            Assert.True(currentValue <= (expectedValues.Length + 1), "Expected to only hit one extra result.");
-                        }
-                    }
-                    while (reader.NextResult());
-                    DataTestUtility.AssertEqualsWithDescription(currentValue, (expectedValues.Length + 1), "Did not hit all expected values.");
-
-                    reader.Close();
-                }
-            }
-        }
-
-        private void VerifyDataSet(DataSet ds, Utf8String[] expectedValues)
-        {
-            DataTestUtility.AssertEqualsWithDescription(1, ds.Tables.Count, "Unexpected tables count.");
-            DataTestUtility.AssertEqualsWithDescription(ds.Tables[0].Rows.Count, expectedValues.Length, "Unexpected rows count.");
-            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
-            {
-                DataTestUtility.AssertEqualsWithDescription(1, ds.Tables[0].Columns.Count, "Unexpected columns count.");
-                DataTestUtility.AssertEqualsWithDescription(expectedValues[i], ds.Tables[0].Rows[i][0], "Unexpected value.");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs
deleted file mode 100644 (file)
index 777b4d0..0000000
+++ /dev/null
@@ -1,711 +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.Data.SqlTypes;
-using System.Reflection;
-using System.Text;
-using Microsoft.SqlServer.Server;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public class UdtTest2
-    {
-        private string _connStr = null;
-
-        public UdtTest2()
-        {
-            _connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { InitialCatalog = DataTestUtility.UdtTestDbName }).ConnectionString;
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_Early()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                conn.Open();
-
-                cmd.Transaction = conn.BeginTransaction();
-                cmd.CommandText = "vicinity"; // select proc
-                cmd.CommandType = CommandType.StoredProcedure;
-
-                SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.Udt);
-                p.UdtTypeName = "UdtTestDb.dbo.Point";
-                Point pt = new Point()
-                {
-                    X = 250,
-                    Y = 250
-                };
-                p.Value = pt;
-
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTestUtility.AssertEqualsWithDescription(
-                        (new Point(250, 250)).ToString(), p.Value.ToString(),
-                        "Unexpected Point value.");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_Binary()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("vicinity", conn))
-            {
-                conn.Open();
-                cmd.CommandType = CommandType.StoredProcedure;
-
-                SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.VarBinary, 8);
-                p.Direction = ParameterDirection.Input;
-
-                byte[] value = new byte[8];
-                value[0] = 0xF0;
-                value[1] = 0;
-                value[2] = 0;
-                value[3] = 0;
-                value[4] = 0xF0;
-                value[5] = 0;
-                value[6] = 0;
-                value[7] = 0;
-                p.Value = new SqlBinary(value);
-
-                DataTestUtility.AssertThrowsWrapper<SqlException>(
-                    () => cmd.ExecuteReader(),
-                    "Error converting data type varbinary to Point.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_Invalid2()
-        {
-            string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
-            string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2");
-
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                conn.Open();
-
-                cmd.Transaction = conn.BeginTransaction();
-                cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = "create proc " + spInsertCustomer + "(@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
-                cmd.ExecuteNonQuery();
-                try
-                {
-                    cmd.CommandText = spInsertCustomer;
-                    cmd.CommandType = CommandType.StoredProcedure;
-
-                    SqlParameter pName = cmd.Parameters.Add("@fname", SqlDbType.NVarChar, 20);
-                    SqlParameter p = cmd.Parameters.Add("@addr", SqlDbType.Udt);
-
-                    Address addr = Address.Parse("customer whose name is address");
-                    p.UdtTypeName = "UdtTestDb.dbo.Address";
-                    p.Value = addr;
-                    pName.Value = addr;
-
-                    DataTestUtility.AssertThrowsWrapper<InvalidCastException>(
-                        () => cmd.ExecuteReader(),
-                        "Failed to convert parameter value from a Address to a String.");
-                }
-                finally
-                {
-                    cmd.Transaction.Rollback();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_Invalid()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("vicinity", conn))
-            {
-                conn.Open();
-                cmd.CommandType = CommandType.StoredProcedure;
-
-                SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.Udt);
-                p.UdtTypeName = "UdtTestDb.dbo.Point";
-                p.Value = 32;
-
-                DataTestUtility.AssertThrowsWrapper<ArgumentException>(
-                    () => cmd.ExecuteReader(),
-                    "Specified type is not registered on the target server. System.Int32");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_TypedNull()
-        {
-            string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
-            string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2_Customer");
-
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                conn.Open();
-
-                cmd.Transaction = conn.BeginTransaction();
-                cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
-                cmd.ExecuteNonQuery();
-
-                // create proc sp_insert_customer(@name nvarchar(30), @addr Address OUTPUT)
-                // AS
-                // insert into customers values (@name, @addr)
-                cmd.CommandText = "create proc " + spInsertCustomer + " (@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
-                cmd.ExecuteNonQuery();
-                try
-                {
-                    cmd.CommandText = spInsertCustomer;
-                    cmd.CommandType = CommandType.StoredProcedure;
-
-                    Address addr = Address.Parse("123 baker st || Redmond");
-                    SqlParameter pName = cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);
-                    SqlParameter p = cmd.Parameters.Add("@addr", SqlDbType.Udt);
-
-                    p.UdtTypeName = "UdtTestDb.dbo.Address";
-                    p.Value = Address.Null;
-                    pName.Value = "john";
-                    cmd.ExecuteNonQuery();
-
-                    DataTestUtility.AssertEqualsWithDescription(
-                        Address.Null.ToString(), p.Value.ToString(),
-                        "Unexpected parameter value.");
-                }
-                finally
-                {
-                    cmd.Transaction.Rollback();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_NullInput()
-        {
-            string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
-            string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2_Customer");
-
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = conn.CreateCommand())
-            {
-                conn.Open();
-
-                cmd.Transaction = conn.BeginTransaction();
-                cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
-                cmd.ExecuteNonQuery();
-                cmd.CommandText = "create proc " + spInsertCustomer + "(@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
-                cmd.ExecuteNonQuery();
-                try
-                {
-                    cmd.CommandText = spInsertCustomer;
-                    cmd.CommandType = CommandType.StoredProcedure;
-
-                    SqlParameter pName = cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);
-                    SqlParameter p = cmd.Parameters.Add("@addr", SqlDbType.Udt);
-
-                    p.UdtTypeName = "UdtTestDb.dbo.Address";
-                    p.Value = null;
-                    pName.Value = "john";
-
-                    string spInsertCustomerNoBrackets = spInsertCustomer;
-                    if (spInsertCustomer.StartsWith("[") && spInsertCustomer.EndsWith("]"))
-                        spInsertCustomerNoBrackets = spInsertCustomer.Substring(1, spInsertCustomer.Length - 2);
-                    string errorMsg = "Procedure or function '" + spInsertCustomerNoBrackets + "' expects parameter '@addr', which was not supplied.";
-
-                    DataTestUtility.AssertThrowsWrapper<SqlException>(
-                        () => cmd.ExecuteNonQuery(),
-                        errorMsg);
-                }
-                finally
-                {
-                    cmd.Transaction.Rollback();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_InputOutput()
-        {
-            string spInsertCity = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCity");
-            string tableName = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2");
-
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            {
-                conn.Open();
-
-                SqlTransaction tx = conn.BeginTransaction();
-                SqlCommand cmd = conn.CreateCommand();
-
-                cmd.Transaction = tx;
-
-                // create the table
-                cmd.CommandText = "create table " + tableName + " (name sysname,location Point)";
-                cmd.ExecuteNonQuery();
-
-                // create sp
-                cmd.CommandText = "create proc " + spInsertCity + "(@name sysname, @location Point OUTPUT)" + " AS insert into " + tableName + " values (@name, @location)";
-                cmd.ExecuteNonQuery();
-                try
-                {
-                    cmd.CommandText = spInsertCity;
-                    cmd.CommandType = CommandType.StoredProcedure;
-
-                    SqlParameter pName = cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);
-                    SqlParameter p = cmd.Parameters.Add("@location", SqlDbType.Udt);
-
-                    Point pt = new Point(100, 100);
-                    p.UdtTypeName = "Point";
-                    p.Direction = ParameterDirection.InputOutput;
-                    p.Value = pt;
-                    pName.Value = "newcity";
-
-                    cmd.ExecuteNonQuery();
-                    DataTestUtility.AssertEqualsWithDescription(
-                        "141.4213562373095", ((Point)(p.Value)).Distance().ToString(),
-                        "Unexpected distance value.");
-                    DataTestUtility.AssertEqualsWithDescription(
-                        "141.4213562373095", ((Point)(p.Value)).Distance().ToString(),
-                        "Unexpected distance value after reading out param again.");
-
-                    cmd.Parameters.Clear();
-                    cmd.CommandType = CommandType.Text;
-                    cmd.CommandText = "select * from " + tableName;
-                    using (SqlDataReader reader = cmd.ExecuteReader())
-                    {
-                        string expectedValue = "   newcity, p.X = 100, p.Y = 100, p.Distance() = 141.4213562373095" + Environment.NewLine;
-                        DataTestUtility.AssertEqualsWithDescription(
-                            expectedValue, UdtTestHelpers.DumpReaderString(reader, false),
-                            "Unexpected reader dump string.");
-                    }
-                }
-                finally
-                {
-                    tx.Rollback();
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTFields_WrongType()
-        {
-            using (SqlConnection cn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("select name,location from cities order by name", cn))
-            {
-                cn.Open();
-                cmd.CommandType = CommandType.Text;
-
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    reader.Read();
-
-                    DataTestUtility.AssertEqualsWithDescription(
-                        "beaverton", reader.GetValue(0),
-                        "Unexpected reader value.");
-                    DataTestUtility.AssertEqualsWithDescription(
-                        "14.866068747318506", ((Point)reader.GetValue(1)).Distance().ToString(),
-                        "Unexpected distance value.");
-
-                    reader.Read();
-
-                    // retrieve the UDT as a string
-                    DataTestUtility.AssertThrowsWrapper<InvalidCastException>(
-                        () => reader.GetString(1),
-                        "Unable to cast object of type 'System.Byte[]' to type 'System.String'.");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDT_DataSetFill()
-        {
-            using (SqlConnection cn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("select * from cities", cn))
-            using (SqlDataAdapter adapter = new SqlDataAdapter("select * from cities", cn))
-            {
-                cn.Open();
-
-                cmd.CommandType = CommandType.Text;
-                adapter.SelectCommand = cmd;
-
-                DataSet ds = new DataSet("newset");
-
-                adapter.Fill(ds);
-                DataTestUtility.AssertEqualsWithDescription(
-                    1, ds.Tables.Count,
-                    "Unexpected Tables count.");
-                DataTestUtility.AssertEqualsWithDescription(
-                    typeof(Point), ds.Tables[0].Columns[1].DataType,
-                    "Unexpected DataType.");
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_DeriveParameters_CheckAutoFixSuccess()
-        {
-            // the type and sproc must be commited to the database or this test will deadlock with a schema lock violation
-            // if you are missing these database entities then you should look for an updated version of the database creation script
-
-            string sprocName = "sp_insert_customers";
-            string typeName = "CustomerAddress";
-            string customerAddressTypeIncorrectName = $"{DataTestUtility.UdtTestDbName}.dbo.{typeName.Trim('[',']')}";
-            string customerAddressTypeCorrectedName = $"[dbo].[{typeName.Trim('[',']')}]";
-            string customerParameterName = "@customers";
-
-            Address addr = Address.Parse("123 baker st || Redmond");
-            DataTable table = new DataTable();
-            table.Columns.Add();
-            table.Columns.Add();
-            table.Rows.Add("john", addr);
-
-            using (SqlConnection connection = new SqlConnection(_connStr))
-            {
-                connection.Open();
-                using (SqlTransaction transaction = connection.BeginTransaction())
-                using (SqlCommand cmd = new SqlCommand(sprocName, connection, transaction))
-                {
-                    try
-                    {
-                        cmd.CommandType = CommandType.StoredProcedure;
-
-                        SqlCommandBuilder.DeriveParameters(cmd);
-
-                        Assert.NotNull(cmd.Parameters);
-                        Assert.Equal(2, cmd.Parameters.Count); // [return_value, table]
-
-                        SqlParameter p = cmd.Parameters[1];
-
-                        Assert.Equal(customerParameterName, p.ParameterName);
-                        Assert.Equal(SqlDbType.Structured, p.SqlDbType);
-                        Assert.Equal(customerAddressTypeIncorrectName, p.TypeName); // the 3 part name is incorrect but needs to be maintained for compatibility
-                        p.Value = table;
-
-                        cmd.ExecuteNonQuery();
-
-                        Assert.Equal(customerAddressTypeCorrectedName, p.TypeName); // check that the auto fix has been applied correctly
-                    }
-                    finally
-                    {
-                        try
-                        {
-                            transaction.Rollback();
-                        }
-                        catch
-                        {
-                            // ignore rollback failure exceptions to preserve original thrown error in test result
-                        }
-                    }
-                }
-
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void UDTParams_DeriveParameters_CheckAutoFixOverride()
-        {
-            // the type and sproc must be commited to the database or this test will deadlock with a schema lock violation
-            // if you are missing these database entities then you should look for an updated version of the database creation script
-
-            string sprocName = "sp_insert_customers";
-            string typeName = "CustomerAddress";
-            string customerAddressTypeIncorrectName = $"{DataTestUtility.UdtTestDbName}.dbo.{typeName.Trim('[', ']')}";
-            string customerAddressTypeCorrectedName = $"[dbo].[{typeName.Trim('[', ']')}]";
-            string customerParameterName = "@customers";
-
-            Address addr = Address.Parse("123 baker st || Redmond");
-            DataTable table = new DataTable();
-            table.Columns.Add();
-            table.Columns.Add();
-            table.Rows.Add("john", addr);
-
-            using (SqlConnection connection = new SqlConnection(_connStr))
-            {
-                connection.Open();
-                using (SqlTransaction transaction = connection.BeginTransaction())
-                using (SqlCommand cmd = new SqlCommand(sprocName, connection, transaction))
-                {
-                    try
-                    {
-                        cmd.CommandType = CommandType.StoredProcedure;
-
-                        SqlCommandBuilder.DeriveParameters(cmd);
-
-                        Assert.NotNull(cmd.Parameters);
-                        Assert.Equal(2, cmd.Parameters.Count); // [return_value, table]
-
-                        SqlParameter p = cmd.Parameters[1];
-
-                        Assert.Equal(customerParameterName, p.ParameterName);
-                        Assert.Equal(SqlDbType.Structured, p.SqlDbType);
-                        Assert.Equal(customerAddressTypeIncorrectName, p.TypeName); // the 3 part name is incorrect but needs to be maintained for compatibility
-                        p.Value = table;
-
-                        p.TypeName = customerAddressTypeIncorrectName; // force using the incorrect name by manually setting it
-
-                        Assert.Throws<SqlException>(
-                            () => cmd.ExecuteNonQuery()
-                        );
-                    }
-                    finally
-                    {
-                        try
-                        {
-                            transaction.Rollback();
-                        }
-                        catch
-                        {
-                            // ignore rollback failure exceptions to preserve original thrown error in test result
-                        }
-                    }
-                }
-
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Reader_PointEarly()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("select name, location from cities", conn))
-            {
-                conn.Open();
-
-                string expectedReaderValues =
-                    "ColumnName[0] = name" + Environment.NewLine +
-                    "DataType[0] = nvarchar" + Environment.NewLine +
-                    "FieldType[0] = System.String" + Environment.NewLine +
-                    "ColumnName[1] = location" + Environment.NewLine +
-                    "DataType[1] = UdtTestDb.dbo.Point" + Environment.NewLine +
-                    "FieldType[1] = Point" + Environment.NewLine +
-                    "   redmond, p.X =   3, p.Y =   3, p.Distance() = 5" + Environment.NewLine +
-                    "  bellevue, p.X =   6, p.Y =   6, p.Distance() = 10" + Environment.NewLine +
-                    "   seattle, p.X =  10, p.Y =  10, p.Distance() = 14.866068747318506" + Environment.NewLine +
-                    "  portland, p.X =  20, p.Y =  20, p.Distance() = 25" + Environment.NewLine +
-                    "        LA, p.X =   3, p.Y =   3, p.Distance() = 5" + Environment.NewLine +
-                    "       SFO, p.X =   6, p.Y =   6, p.Distance() = 10" + Environment.NewLine +
-                    " beaverton, p.X =  10, p.Y =  10, p.Distance() = 14.866068747318506" + Environment.NewLine +
-                    "  new york, p.X =  20, p.Y =  20, p.Distance() = 25" + Environment.NewLine +
-                    "     yukon, p.X =  20, p.Y =  20, p.Distance() = 32.01562118716424" + Environment.NewLine;
-
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTestUtility.AssertEqualsWithDescription(
-                        expectedReaderValues, UdtTestHelpers.DumpReaderString(reader),
-                        "Unexpected reader values.");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Reader_LineEarly()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("select * from lines", conn))
-            {
-                conn.Open();
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    Line l = null;
-                    Point p = null;
-                    int x = 0, y = 0;
-                    double length = 0;
-
-                    string expectedReaderValues =
-                        "ids (int);pos (UdtTestDb.dbo.Line);";
-
-                    StringBuilder builder = new StringBuilder();
-                    for (int i = 0; i < reader.FieldCount; i++)
-                    {
-                        builder.Append(reader.GetName(i) + " (" + reader.GetDataTypeName(i) + ");");
-                    }
-                    DataTestUtility.AssertEqualsWithDescription(
-                        expectedReaderValues, builder.ToString(),
-                        "Unexpected reader values.");
-
-                    string expectedLineValues =
-                        "1, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
-                        "2, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
-                        "3, IsNull = False, Length = 9.848857801796104" + Environment.NewLine +
-                        "4, IsNull = False, Length = 214.1074496602115" + Environment.NewLine +
-                        "5, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
-                        "6, IsNull = False, Length = 2.8284271247461903" + Environment.NewLine +
-                        "7, IsNull = False, Length = 9.848857801796104" + Environment.NewLine +
-                        "8, IsNull = False, Length = 214.1074496602115" + Environment.NewLine;
-
-                    builder = new StringBuilder();
-                    while (reader.Read())
-                    {
-                        builder.Append(reader.GetValue(0).ToString() + ", ");
-                        l = (Line)reader.GetValue(1);
-                        if (!l.IsNull)
-                        {
-                            p = l.Start;
-                            x = p.X;
-                            y = p.Y;
-                            length = l.Length();
-                        }
-
-                        builder.Append("IsNull = " + l.IsNull + ", ");
-                        builder.Append("Length = " + length);
-                        builder.AppendLine();
-                    }
-                    DataTestUtility.AssertEqualsWithDescription(
-                        expectedLineValues, builder.ToString(),
-                        "Unexpected Line values.");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Reader_PointLate()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("select name, location from cities", conn))
-            {
-                conn.Open();
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    string expectedReaderValues =
-                        "ColumnName[0] = name" + Environment.NewLine +
-                        "DataType[0] = nvarchar" + Environment.NewLine +
-                        "FieldType[0] = System.String" + Environment.NewLine +
-                        "ColumnName[1] = location" + Environment.NewLine +
-                        "DataType[1] = UdtTestDb.dbo.Point" + Environment.NewLine +
-                        "FieldType[1] = Point" + Environment.NewLine +
-                        "   redmond, p.X =   3, p.Y =   3, p.Distance() = 5" + Environment.NewLine +
-                        "  bellevue, p.X =   6, p.Y =   6, p.Distance() = 10" + Environment.NewLine +
-                        "   seattle, p.X =  10, p.Y =  10, p.Distance() = 14.866068747318506" + Environment.NewLine +
-                        "  portland, p.X =  20, p.Y =  20, p.Distance() = 25" + Environment.NewLine +
-                        "        LA, p.X =   3, p.Y =   3, p.Distance() = 5" + Environment.NewLine +
-                        "       SFO, p.X =   6, p.Y =   6, p.Distance() = 10" + Environment.NewLine +
-                        " beaverton, p.X =  10, p.Y =  10, p.Distance() = 14.866068747318506" + Environment.NewLine +
-                        "  new york, p.X =  20, p.Y =  20, p.Distance() = 25" + Environment.NewLine +
-                        "     yukon, p.X =  20, p.Y =  20, p.Distance() = 32.01562118716424" + Environment.NewLine;
-
-                    DataTestUtility.AssertEqualsWithDescription(
-                    expectedReaderValues, UdtTestHelpers.DumpReaderString(reader),
-                    "Unexpected reader values.");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void Reader_CircleLate()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("select * from circles", conn))
-            {
-                conn.Open();
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    string expectedReaderValues =
-                        "ColumnName[0] = num" + Environment.NewLine +
-                        "DataType[0] = int" + Environment.NewLine +
-                        "FieldType[0] = System.Int32" + Environment.NewLine +
-                        "ColumnName[1] = def" + Environment.NewLine +
-                        "DataType[1] = UdtTestDb.dbo.Circle" + Environment.NewLine +
-                        "FieldType[1] = Circle" + Environment.NewLine +
-                        "         1, Center = 1,2" + Environment.NewLine +
-                        "         2, Center = 3,4" + Environment.NewLine +
-                        "         3, Center = 11,23" + Environment.NewLine +
-                        "         4, Center = 444,555" + Environment.NewLine +
-                        "         5, Center = 1,2" + Environment.NewLine +
-                        "         6, Center = 3,4" + Environment.NewLine +
-                        "         7, Center = 11,23" + Environment.NewLine +
-                        "         8, Center = 444,245" + Environment.NewLine;
-
-                    DataTestUtility.AssertEqualsWithDescription(
-                        expectedReaderValues, UdtTestHelpers.DumpReaderString(reader),
-                        "Unexpected reader values.");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestSchemaTable()
-        {
-            using (SqlConnection conn = new SqlConnection(_connStr))
-            using (SqlCommand cmd = new SqlCommand("select * from lines", conn))
-            {
-                conn.Open();
-                cmd.CommandType = CommandType.Text;
-
-                using (SqlDataReader reader = cmd.ExecuteReader())
-                {
-                    DataTable t = reader.GetSchemaTable();
-
-                    string expectedSchemaTableValues =
-                        "ids, 0, 4, 10, 255, False, , , , ids, , , System.Int32, True, 8, , , False, False, False, , False, False, System.Data.SqlTypes.SqlInt32, int, , , , , 8, False, " + Environment.NewLine +
-                        "pos, 1, 20, 255, 255, False, , , , pos, , , Line, True, 29, , , False, False, False, , False, False, Line, UdtTestDb.dbo.Line, , , , Line, Shapes, Version=1.2.0.0, Culture=neutral, PublicKeyToken=a3e3aa32e6a16344, 29, False, " + Environment.NewLine;
-
-                    StringBuilder builder = new StringBuilder();
-                    foreach (DataRow row in t.Rows)
-                    {
-                        foreach (DataColumn col in t.Columns)
-                            builder.Append(row[col] + ", ");
-
-                        builder.AppendLine();
-                    }
-                    DataTestUtility.AssertEqualsWithDescription(
-                        expectedSchemaTableValues, builder.ToString(),
-                        "Unexpected DataTable values from GetSchemaTable.");
-
-                    string expectedReaderValues =
-                        "ids1" + Environment.NewLine +
-                        "pos1,2,3,4" + Environment.NewLine +
-                        "ids2" + Environment.NewLine +
-                        "pos3,4,5,6" + Environment.NewLine +
-                        "ids3" + Environment.NewLine +
-                        "pos11,23,15,32" + Environment.NewLine +
-                        "ids4" + Environment.NewLine +
-                        "pos444,555,245,634" + Environment.NewLine +
-                        "ids5" + Environment.NewLine +
-                        "pos1,2,3,4" + Environment.NewLine +
-                        "ids6" + Environment.NewLine +
-                        "pos3,4,5,6" + Environment.NewLine +
-                        "ids7" + Environment.NewLine +
-                        "pos11,23,15,32" + Environment.NewLine +
-                        "ids8" + Environment.NewLine +
-                        "pos444,555,245,634" + Environment.NewLine;
-                    builder = new StringBuilder();
-                    while (reader.Read())
-                    {
-                        for (int i = 0; i < reader.FieldCount; i++)
-                        {
-                            builder.Append(reader.GetName(i) + reader.GetValue(i).ToString());
-                            builder.AppendLine();
-                        }
-                    }
-                    DataTestUtility.AssertEqualsWithDescription(
-                        expectedReaderValues, builder.ToString(),
-                        "Unexpected Reader values.");
-                }
-            }
-        }
-
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsUdtTestDatabasePresent), nameof(DataTestUtility.AreConnStringsSetup))]
-        public void TestSqlUserDefinedAggregateAttributeMaxByteSize()
-        {
-            Func<int, SqlUserDefinedAggregateAttribute> create
-                    = (size) => new SqlUserDefinedAggregateAttribute(Format.UserDefined) { MaxByteSize = size };
-
-            SqlUserDefinedAggregateAttribute attribute1 = create(-1);
-            SqlUserDefinedAggregateAttribute attribute2 = create(0);
-            SqlUserDefinedAggregateAttribute attribute3 = create(SqlUserDefinedAggregateAttribute.MaxByteSizeValue);
-
-            string udtError = SystemDataResourceManager.Instance.SQLUDT_MaxByteSizeValue;
-            string errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", 8001, udtError)).Message;
-
-            DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(
-                () => create(SqlUserDefinedAggregateAttribute.MaxByteSizeValue + 1),
-                errorMessage);
-
-            errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", -2, udtError)).Message;
-            DataTestUtility.AssertThrowsWrapper<ArgumentOutOfRangeException>(
-                () => create(-2),
-                errorMessage);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTestHelpers.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTestHelpers.cs
deleted file mode 100644 (file)
index 6351065..0000000
+++ /dev/null
@@ -1,83 +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.IO;
-using System.Reflection;
-using System.Text;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    internal static class UdtTestHelpers
-    {
-        internal static string DumpReaderString(SqlDataReader reader)
-        {
-            return DumpReaderString(reader, true);
-        }
-
-        internal static string DumpReaderString(SqlDataReader reader, bool showMetaData)
-        {
-            int i;
-            int x = 0, y = 0;
-            double d;
-            object o = 0;
-            bool fNull;
-            StringBuilder builder = new StringBuilder();
-
-            if (showMetaData)
-            {
-                for (i = 0; i < reader.FieldCount; i++)
-                {
-                    builder.AppendLine($"ColumnName[{i}] = {reader.GetName(i)}");
-                    builder.AppendLine($"DataType[{i}] = {reader.GetDataTypeName(i)}");
-                    builder.AppendLine($"FieldType[{i}] = {reader.GetFieldType(i)}");
-                }
-            }
-
-            while (reader.Read())
-            {
-                for (i = 0; i < reader.FieldCount; i++)
-                {
-                    if (i > 0)
-                    {
-                        builder.Append(", ");
-                    }
-
-                    object fieldValue = reader.GetValue(i);
-
-                    if (fieldValue is Point)
-                    {
-                        fNull = (bool)fieldValue.GetType().InvokeMember("IsNull", BindingFlags.GetProperty, null, fieldValue, null);
-                        if (!fNull)
-                        {
-                            x = (int)fieldValue.GetType().InvokeMember("X", BindingFlags.GetProperty, null, fieldValue, null);
-                            y = (int)fieldValue.GetType().InvokeMember("X", BindingFlags.GetProperty, null, fieldValue, null);
-                            d = (double)fieldValue.GetType().InvokeMember("Distance", BindingFlags.Public | BindingFlags.Default | BindingFlags.Instance | BindingFlags.InvokeMethod, null, fieldValue, new object[] { });
-                            builder.Append(string.Format("p.X = {0,3}, p.Y = {1,3}, p.Distance() = {2}", x, y, d));
-                        }
-                        else
-                        {
-                            builder.Append("null");
-                        }
-                    }
-                    else if (fieldValue is Circle)
-                    {
-                        fNull = (bool)fieldValue.GetType().InvokeMember("IsNull", BindingFlags.GetProperty, null, fieldValue, null);
-                        if (!fNull)
-                        {
-                            o = fieldValue.GetType().InvokeMember("Center", BindingFlags.Public | BindingFlags.Default | BindingFlags.Instance | BindingFlags.GetProperty, null, fieldValue, new object[] { });
-                            builder.Append("Center = " + o);
-                        }
-                    }
-                    else
-                    {
-                        builder.Append(string.Format("{0,10}", fieldValue.ToString()));
-                    }
-                }
-                builder.AppendLine();
-            }
-            return builder.ToString();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Utf8SupportTest/Utf8SupportTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/Utf8SupportTest/Utf8SupportTest.cs
deleted file mode 100644 (file)
index 6fa4884..0000000
+++ /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 Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class Utf8SupportTest
-    {
-        [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsUTF8Supported))]
-        public static void CheckSupportUtf8ConnectionProperty()
-        {
-            using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
-            using (SqlCommand command = new SqlCommand())
-            {
-                command.Connection = connection;
-                command.CommandText = "SELECT CONNECTIONPROPERTY('SUPPORT_UTF8')";
-                connection.Open();
-
-                using (SqlDataReader reader = command.ExecuteReader())
-                {
-                    while (reader.Read())
-                    {
-                        Assert.Equal(1, reader.GetInt32(0));
-                    }
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/WeakRefTest/WeakRefTest.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/WeakRefTest/WeakRefTest.cs
deleted file mode 100644 (file)
index f5b3f38..0000000
+++ /dev/null
@@ -1,237 +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.CompilerServices;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class WeakRefTest
-    {
-        private const string COMMAND_TEXT_1 = "SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country from Employees";
-        private const string COMMAND_TEXT_2 = "SELECT LastName from Employees";
-        private const string COLUMN_NAME_2 = "LastName";
-        private const string CHANGE_DATABASE_NAME = "master";
-
-        private enum ReaderTestType
-        {
-            ReaderClose,
-            ReaderDispose,
-            ReaderGC,
-            ConnectionClose,
-            ReaderGCConnectionClose,
-        }
-
-        private enum ReaderVerificationType
-        {
-            ExecuteReader,
-            ChangeDatabase,
-            BeginTransaction,
-            EnlistDistributedTransaction,
-        }
-
-        private enum TransactionTestType
-        {
-            TransactionRollback,
-            TransactionDispose,
-            TransactionGC,
-            ConnectionClose,
-            TransactionGCConnectionClose,
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestReaderNonMars()
-        {
-            string connString =
-                (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
-                {
-                    MaxPoolSize = 1
-                }
-                ).ConnectionString;
-
-            TestReaderNonMarsCase("Case 1: ExecuteReader, Close, ExecuteReader.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.ExecuteReader);
-            TestReaderNonMarsCase("Case 2: ExecuteReader, Dispose, ExecuteReader.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.ExecuteReader);
-            TestReaderNonMarsCase("Case 3: ExecuteReader, GC, ExecuteReader.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.ExecuteReader);
-            TestReaderNonMarsCase("Case 4: ExecuteReader, Connection Close, ExecuteReader.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.ExecuteReader);
-            TestReaderNonMarsCase("Case 5: ExecuteReader, GC, Connection Close, ExecuteReader.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ExecuteReader);
-
-            TestReaderNonMarsCase("Case 6: ExecuteReader, Close, ChangeDatabase.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.ChangeDatabase);
-            TestReaderNonMarsCase("Case 7: ExecuteReader, Dispose, ChangeDatabase.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.ChangeDatabase);
-            TestReaderNonMarsCase("Case 8: ExecuteReader, GC, ChangeDatabase.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.ChangeDatabase);
-            TestReaderNonMarsCase("Case 9: ExecuteReader, Connection Close, ChangeDatabase.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.ChangeDatabase);
-            TestReaderNonMarsCase("Case 10: ExecuteReader, GC, Connection Close, ChangeDatabase.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ChangeDatabase);
-
-            TestReaderNonMarsCase("Case 11: ExecuteReader, Close, BeginTransaction.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.BeginTransaction);
-            TestReaderNonMarsCase("Case 12: ExecuteReader, Dispose, BeginTransaction.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.BeginTransaction);
-            TestReaderNonMarsCase("Case 13: ExecuteReader, GC, BeginTransaction.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.BeginTransaction);
-            TestReaderNonMarsCase("Case 14: ExecuteReader, Connection Close, BeginTransaction.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.BeginTransaction);
-            TestReaderNonMarsCase("Case 15: ExecuteReader, GC, Connection Close, BeginTransaction.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.BeginTransaction);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestTransactionSingle()
-        {
-            string connString =
-                (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
-                {
-                    MaxPoolSize = 1
-                }).ConnectionString;
-
-            TestTransactionSingleCase("Case 1: BeginTransaction, Rollback.", connString, TransactionTestType.TransactionRollback);
-            TestTransactionSingleCase("Case 2: BeginTransaction, Dispose.", connString, TransactionTestType.TransactionDispose);
-            TestTransactionSingleCase("Case 3: BeginTransaction, GC.", connString, TransactionTestType.TransactionGC);
-            TestTransactionSingleCase("Case 4: BeginTransaction, Connection Close.", connString, TransactionTestType.ConnectionClose);
-            TestTransactionSingleCase("Case 5: BeginTransaction, GC, Connection Close.", connString, TransactionTestType.TransactionGCConnectionClose);
-        }
-
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static void TestReaderNonMarsCase(string caseName, string connectionString, ReaderTestType testType, ReaderVerificationType verificationType)
-        {
-            WeakReference weak = null;
-
-            using (SqlConnection con = new SqlConnection(connectionString))
-            {
-                con.Open();
-
-                using (SqlCommand cmd = con.CreateCommand())
-                {
-                    cmd.CommandText = COMMAND_TEXT_1;
-
-                    SqlDataReader gch = null;
-                    if ((testType != ReaderTestType.ReaderGC) && (testType != ReaderTestType.ReaderGCConnectionClose))
-                        gch = cmd.ExecuteReader();
-
-                    switch (testType)
-                    {
-                        case ReaderTestType.ReaderClose:
-                            gch.Dispose();
-                            break;
-                        case ReaderTestType.ReaderDispose:
-                            gch.Dispose();
-                            break;
-                        case ReaderTestType.ReaderGC:
-                            weak = OpenNullifyReader(cmd);
-                            GC.Collect();
-                            GC.WaitForPendingFinalizers();
-                            Assert.False(weak.IsAlive, "Reader is still alive!");
-                            break;
-
-                        case ReaderTestType.ConnectionClose:
-                            GC.SuppressFinalize(gch);
-                            con.Close();
-                            con.Open();
-                            break;
-
-                        case ReaderTestType.ReaderGCConnectionClose:
-                            weak = OpenNullifyReader(cmd);
-                            GC.Collect();
-                            GC.WaitForPendingFinalizers();
-
-                            Assert.False(weak.IsAlive, "Reader is still alive!");
-                            con.Close();
-                            con.Open();
-                            break;
-                    }
-
-                    switch (verificationType)
-                    {
-                        case ReaderVerificationType.ExecuteReader:
-                            cmd.CommandText = COMMAND_TEXT_2;
-                            using (SqlDataReader rdr = cmd.ExecuteReader())
-                            {
-                                rdr.Read();
-                                Assert.Equal(1, rdr.FieldCount);
-                                Assert.Equal(rdr.GetName(0), COLUMN_NAME_2);
-                            }
-                            break;
-
-                        case ReaderVerificationType.ChangeDatabase:
-                            con.ChangeDatabase(CHANGE_DATABASE_NAME);
-                            Assert.Equal(con.Database, CHANGE_DATABASE_NAME);
-                            break;
-
-                        case ReaderVerificationType.BeginTransaction:
-                            cmd.Transaction = con.BeginTransaction();
-                            cmd.CommandText = "select @@trancount";
-                            int tranCount = (int)cmd.ExecuteScalar();
-                            Assert.Equal(1, tranCount);
-                            break;
-                    }
-                }
-            }
-        }
-
-        private static WeakReference OpenNullifyReader(SqlCommand cmd)
-        {
-            SqlDataReader reader = cmd.ExecuteReader();
-            WeakReference weak = new WeakReference(reader);
-            reader = null;
-            return weak;
-        }
-
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static void TestTransactionSingleCase(string caseName, string connectionString, TransactionTestType testType)
-        {
-            WeakReference weak = null;
-
-            using (SqlConnection con = new SqlConnection(connectionString))
-            {
-                con.Open();
-
-                SqlTransaction gch = null;
-                if ((testType != TransactionTestType.TransactionGC) && (testType != TransactionTestType.TransactionGCConnectionClose))
-                    gch = con.BeginTransaction();
-
-                switch (testType)
-                {
-                    case TransactionTestType.TransactionRollback:
-                        gch.Rollback();
-                        break;
-
-                    case TransactionTestType.TransactionDispose:
-                        gch.Dispose();
-                        break;
-
-                    case TransactionTestType.TransactionGC:
-                        weak = OpenNullifyTransaction(con);
-                        GC.Collect();
-                        GC.WaitForPendingFinalizers();
-
-                        Assert.False(weak.IsAlive, "Transaction is still alive!");
-                        break;
-                    case TransactionTestType.ConnectionClose:
-                        GC.SuppressFinalize(gch);
-                        con.Close();
-                        con.Open();
-                        break;
-
-                    case TransactionTestType.TransactionGCConnectionClose:
-                        weak = OpenNullifyTransaction(con);
-                        GC.Collect();
-                        GC.WaitForPendingFinalizers();
-
-                        Assert.False(weak.IsAlive, "Transaction is still alive!");
-                        con.Close();
-                        con.Open();
-                        break;
-                }
-
-                using (SqlCommand cmd = con.CreateCommand())
-                {
-                    cmd.CommandText = "select @@trancount";
-                    int tranCount = (int)cmd.ExecuteScalar();
-                    Assert.Equal(0, tranCount);
-                }
-            }
-        }
-
-        private static WeakReference OpenNullifyTransaction(SqlConnection connection)
-        {
-            SqlTransaction transaction = connection.BeginTransaction();
-            WeakReference weak = new WeakReference(transaction);
-            transaction = null;
-            return weak;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/WeakRefTestYukonSpecific/WeakRefTestYukonSpecific.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/SQL/WeakRefTestYukonSpecific/WeakRefTestYukonSpecific.cs
deleted file mode 100644 (file)
index 8b26c00..0000000
+++ /dev/null
@@ -1,253 +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.CompilerServices;
-using Xunit;
-
-namespace System.Data.SqlClient.ManualTesting.Tests
-{
-    public static class WeakRefTestYukonSpecific
-    {
-        private const string COMMAND_TEXT_1 = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax from Customers";
-        private const string COMMAND_TEXT_2 = "SELECT CompanyName from Customers";
-        private const string COLUMN_NAME_2 = "CompanyName";
-        private const string DATABASE_NAME = "master";
-        private const int CONCURRENT_COMMANDS = 5;
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestReaderMars()
-        {
-            string connectionString =
-                (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
-                {
-                    MultipleActiveResultSets = true,
-                    MaxPoolSize = 1
-                }).ConnectionString;
-
-            TestReaderMarsCase("Case 1: ExecuteReader*5 Close, ExecuteReader.", connectionString, ReaderTestType.ReaderClose, ReaderVerificationType.ExecuteReader);
-            TestReaderMarsCase("Case 2: ExecuteReader*5 Dispose, ExecuteReader.", connectionString, ReaderTestType.ReaderDispose, ReaderVerificationType.ExecuteReader);
-            TestReaderMarsCase("Case 3: ExecuteReader*5 GC, ExecuteReader.", connectionString, ReaderTestType.ReaderGC, ReaderVerificationType.ExecuteReader);
-            TestReaderMarsCase("Case 4: ExecuteReader*5 Connection Close, ExecuteReader.", connectionString, ReaderTestType.ConnectionClose, ReaderVerificationType.ExecuteReader);
-            TestReaderMarsCase("Case 5: ExecuteReader*5 GC, Connection Close, ExecuteReader.", connectionString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ExecuteReader);
-
-            TestReaderMarsCase("Case 6: ExecuteReader*5 Close, ChangeDatabase.", connectionString, ReaderTestType.ReaderClose, ReaderVerificationType.ChangeDatabase);
-            TestReaderMarsCase("Case 7: ExecuteReader*5 Dispose, ChangeDatabase.", connectionString, ReaderTestType.ReaderDispose, ReaderVerificationType.ChangeDatabase);
-            TestReaderMarsCase("Case 8: ExecuteReader*5 GC, ChangeDatabase.", connectionString, ReaderTestType.ReaderGC, ReaderVerificationType.ChangeDatabase);
-            TestReaderMarsCase("Case 9: ExecuteReader*5 Connection Close, ChangeDatabase.", connectionString, ReaderTestType.ConnectionClose, ReaderVerificationType.ChangeDatabase);
-            TestReaderMarsCase("Case 10: ExecuteReader*5 GC, Connection Close, ChangeDatabase.", connectionString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ChangeDatabase);
-
-            TestReaderMarsCase("Case 11: ExecuteReader*5 Close, BeginTransaction.", connectionString, ReaderTestType.ReaderClose, ReaderVerificationType.BeginTransaction);
-            TestReaderMarsCase("Case 12: ExecuteReader*5 Dispose, BeginTransaction.", connectionString, ReaderTestType.ReaderDispose, ReaderVerificationType.BeginTransaction);
-
-            TestReaderMarsCase("Case 13: ExecuteReader*5 Connection Close, BeginTransaction.", connectionString, ReaderTestType.ConnectionClose, ReaderVerificationType.BeginTransaction);
-            TestReaderMarsCase("Case 14: ExecuteReader*5 GC, Connection Close, BeginTransaction.", connectionString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.BeginTransaction);
-        }
-
-        [ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
-        public static void TestTransactionSingle()
-        {
-            string connectionString =
-                (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
-                {
-                    MultipleActiveResultSets = true,
-                    MaxPoolSize = 1
-                }).ConnectionString;
-
-            TestTransactionSingleCase("Case 1: BeginTransaction, Rollback.", connectionString, TransactionTestType.TransactionRollback);
-            TestTransactionSingleCase("Case 2: BeginTransaction, Dispose.", connectionString, TransactionTestType.TransactionDispose);
-            TestTransactionSingleCase("Case 3: BeginTransaction, GC.", connectionString, TransactionTestType.TransactionGC);
-            TestTransactionSingleCase("Case 4: BeginTransaction, Connection Close.", connectionString, TransactionTestType.ConnectionClose);
-            TestTransactionSingleCase("Case 5: BeginTransaction, GC, Connection Close.", connectionString, TransactionTestType.TransactionGCConnectionClose);
-        }
-
-        private enum ReaderTestType
-        {
-            ReaderClose,
-            ReaderDispose,
-            ReaderGC,
-            ConnectionClose,
-            ReaderGCConnectionClose,
-        }
-
-        private enum ReaderVerificationType
-        {
-            ExecuteReader,
-            ChangeDatabase,
-            BeginTransaction,
-            EnlistDistributedTransaction,
-        }
-
-        private enum TransactionTestType
-        {
-            TransactionRollback,
-            TransactionDispose,
-            TransactionGC,
-            ConnectionClose,
-            TransactionGCConnectionClose,
-        }
-
-        public static int GCCount = 0;
-
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static void TestReaderMarsCase(string caseName, string connectionString, ReaderTestType testType, ReaderVerificationType verificationType)
-        {
-            WeakReference weak = null;
-            SqlCommand[] cmd = new SqlCommand[CONCURRENT_COMMANDS];
-            SqlDataReader[] gch = new SqlDataReader[CONCURRENT_COMMANDS];
-
-            using (SqlConnection con = new SqlConnection(connectionString))
-            {
-                con.Open();
-
-                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
-                {
-                    cmd[i] = con.CreateCommand();
-                    cmd[i].CommandText = COMMAND_TEXT_1;
-                    if ((testType != ReaderTestType.ReaderGC) && (testType != ReaderTestType.ReaderGCConnectionClose))
-                        gch[i] = cmd[i].ExecuteReader();
-                    else
-                        gch[i] = null;
-                }
-
-                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
-                {
-                    switch (testType)
-                    {
-                        case ReaderTestType.ReaderClose:
-                            gch[i].Dispose();
-                            break;
-
-                        case ReaderTestType.ReaderDispose:
-                            gch[i].Dispose();
-                            break;
-
-                        case ReaderTestType.ReaderGC:
-                            weak = OpenNullifyReader(cmd[i]);
-                            GC.Collect();
-                            GC.WaitForPendingFinalizers();
-                            Assert.False(weak.IsAlive, "Transaction is still alive on TestReaderMars: ReaderGC");
-                            break;
-
-                        case ReaderTestType.ConnectionClose:
-                            GC.SuppressFinalize(gch[i]);
-                            con.Close();
-                            con.Open();
-                            break;
-
-                        case ReaderTestType.ReaderGCConnectionClose:
-                            weak = OpenNullifyReader(cmd[i]);
-                            GC.Collect();
-                            GC.WaitForPendingFinalizers();
-                            Assert.False(weak.IsAlive, "Transaction is still alive on TestReaderMars: ReaderGCConnectionClose");
-                            con.Close();
-                            con.Open();
-                            break;
-                    }
-
-                    cmd[i].Dispose();
-                }
-
-                SqlCommand verificationCmd = con.CreateCommand();
-
-                switch (verificationType)
-                {
-                    case ReaderVerificationType.ExecuteReader:
-                        verificationCmd.CommandText = COMMAND_TEXT_2;
-                        using (SqlDataReader rdr = verificationCmd.ExecuteReader())
-                        {
-                            rdr.Read();
-                            DataTestUtility.AssertEqualsWithDescription(1, rdr.FieldCount, "Execute Reader should return expected Field count");
-                            DataTestUtility.AssertEqualsWithDescription(COLUMN_NAME_2, rdr.GetName(0), "Execute Reader should return expected Field name");
-                        }
-                        break;
-
-                    case ReaderVerificationType.ChangeDatabase:
-                        con.ChangeDatabase(DATABASE_NAME);
-                        DataTestUtility.AssertEqualsWithDescription(DATABASE_NAME, con.Database, "Change Database should return expected Database Name");
-                        break;
-
-                    case ReaderVerificationType.BeginTransaction:
-                        verificationCmd.Transaction = con.BeginTransaction();
-                        verificationCmd.CommandText = "select @@trancount";
-                        int tranCount = (int)verificationCmd.ExecuteScalar();
-                        DataTestUtility.AssertEqualsWithDescription(1, tranCount, "Begin Transaction should return expected Transaction count");
-                        break;
-                }
-
-                verificationCmd.Dispose();
-            }
-        }
-
-        private static WeakReference OpenNullifyReader(SqlCommand command)
-        {
-            SqlDataReader reader = command.ExecuteReader();
-            WeakReference weak = new WeakReference(reader);
-            reader = null;
-            return weak;
-        }
-
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static void TestTransactionSingleCase(string caseName, string connectionString, TransactionTestType testType)
-        {
-            WeakReference weak = null;
-
-            using (SqlConnection con = new SqlConnection(connectionString))
-            {
-                con.Open();
-
-                SqlTransaction gch = null;
-                if ((testType != TransactionTestType.TransactionGC) && (testType != TransactionTestType.TransactionGCConnectionClose))
-                    gch = con.BeginTransaction();
-
-                switch (testType)
-                {
-                    case TransactionTestType.TransactionRollback:
-                        gch.Rollback();
-                        break;
-
-                    case TransactionTestType.TransactionDispose:
-                        gch.Dispose();
-                        break;
-
-                    case TransactionTestType.TransactionGC:
-                        weak = OpenNullifyTransaction(con);
-                        GC.Collect();
-                        GC.WaitForPendingFinalizers();
-                        Assert.False(weak.IsAlive, "Transaction is still alive on TestTransactionSingle: TransactionGC");
-                        break;
-
-                    case TransactionTestType.ConnectionClose:
-                        GC.SuppressFinalize(gch);
-                        con.Close();
-                        con.Open();
-                        break;
-
-                    case TransactionTestType.TransactionGCConnectionClose:
-                        weak = OpenNullifyTransaction(con);
-                        GC.Collect();
-                        GC.WaitForPendingFinalizers();
-                        Assert.False(weak.IsAlive, "Transaction is still alive on TestTransactionSingle: TransactionGCConnectionClose");
-                        con.Close();
-                        con.Open();
-                        break;
-                }
-
-                using (SqlCommand cmd = con.CreateCommand())
-                {
-                    cmd.CommandText = "select @@trancount";
-                    int tranCount = (int)cmd.ExecuteScalar();
-                    DataTestUtility.AssertEqualsWithDescription(0, tranCount, "TransactionSingle Case " + caseName + " should return expected trans count");
-                }
-            }
-        }
-
-        private static WeakReference OpenNullifyTransaction(SqlConnection connection)
-        {
-            SqlTransaction transaction = connection.BeginTransaction();
-            WeakReference weak = new WeakReference(transaction);
-            transaction = null;
-            return weak;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj b/src/libraries/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj
deleted file mode 100644 (file)
index 340b0a5..0000000
+++ /dev/null
@@ -1,159 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <Configurations>$(NetCoreAppCurrent)-Debug;$(NetCoreAppCurrent)-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="$(CommonTestPath)System\Collections\DictionaryExtensions.cs">
-      <Link>Common\System\Collections\DictionaryExtensions.cs</Link>
-    </Compile>
-    <Compile Include="ProviderAgnostic\ReaderTest\ConcurrentLoadContext.cs" />
-    <Compile Include="SQL\AdapterTest\AdapterTest.cs" />
-    <Compile Include="SQL\AsyncTest\BeginExecAsyncTest.cs" />
-    <Compile Include="SQL\AsyncTest\BeginExecReaderAsyncTest.cs" />
-    <Compile Include="SQL\AsyncTest\XmlReaderAsyncTest.cs" />
-    <Compile Include="SQL\Common\AsyncDebugScope.cs" />
-    <Compile Include="SQL\Common\ConnectionPoolWrapper.cs" />
-    <Compile Include="SQL\Common\InternalConnectionWrapper.cs" />
-    <Compile Include="SQL\Common\SystemDataExtensions.cs" />
-    <Compile Include="SQL\Common\SystemDataInternals\CommandHelper.cs" />
-    <Compile Include="SQL\Common\SystemDataInternals\ConnectionHelper.cs" />
-    <Compile Include="SQL\Common\SystemDataInternals\ConnectionPoolHelper.cs" />
-    <Compile Include="SQL\Common\SystemDataInternals\DataReaderHelper.cs" />
-    <Compile Include="SQL\Common\SystemDataInternals\TdsParserHelper.cs" />
-    <Compile Include="SQL\Common\SystemDataInternals\TdsParserStateObjectHelper.cs" />
-    <Compile Include="DataCommon\AssemblyResourceManager.cs" />
-    <Compile Include="DataCommon\DataSourceBuilder.cs" />
-    <Compile Include="DataCommon\DataTestUtility.cs" />
-    <Compile Include="DataCommon\ProxyServer.cs" />
-    <Compile Include="DataCommon\SystemDataResourceManager.cs" />
-    <Compile Include="SQL\ConnectivityTests\AADAccessTokenTest.cs" />
-    <Compile Include="SQL\ParameterTest\DateTimeVariantTest.cs" />
-    <Compile Include="SQL\ParameterTest\OutputParameter.cs" />
-    <Compile Include="SQL\ParameterTest\ParametersTest.cs" />
-    <Compile Include="SQL\ParameterTest\SqlAdapterUpdateBatch.cs" />
-    <Compile Include="SQL\ParameterTest\SqlVariantParam.cs" />
-    <Compile Include="SQL\ParameterTest\SteAttribute.cs" />
-    <Compile Include="SQL\ParameterTest\SteParam.cs" />
-    <Compile Include="SQL\ParameterTest\StePermutationSet.cs" />
-    <Compile Include="SQL\ParameterTest\SteTypeBoundaries.cs" />
-    <Compile Include="SQL\ParameterTest\StreamInputParam.cs" />
-    <Compile Include="SQL\ParameterTest\TvpTest.cs" />
-    <Compile Include="DDBasics\DDAsyncTest\DDAsyncTest.cs" />
-    <Compile Include="DDBasics\DDDataTypesTest\DDDataTypesTest.cs" />
-    <Compile Include="DDBasics\DDMARSTest\DDMARSTest.cs" />
-    <Compile Include="ProviderAgnostic\MultipleResultsTest\MultipleResultsTest.cs" />
-    <Compile Include="ProviderAgnostic\ReaderTest\ReaderTest.cs" />
-    <Compile Include="SQL\AsyncTest\AsyncTest.cs" />
-    <Compile Include="SQL\CommandCancelTest\CommandCancelTest.cs" />
-    <Compile Include="SQL\ConnectionPoolTest\ConnectionPoolTest.cs" />
-    <Compile Include="SQL\ConnectionPoolTest\PoolBlockPeriodTest.netcoreapp.cs" />
-    <Compile Include="SQL\ConnectivityTests\ConnectivityTest.cs" />
-    <Compile Include="SQL\DataBaseSchemaTest\ConnectionSchemaTest.cs" />
-    <Compile Include="SQL\DataReaderTest\DataReaderTest.cs" />
-    <Compile Include="SQL\ExceptionTest\ExceptionTest.cs" />
-    <Compile Include="SQL\DataStreamTest\DataStreamTest.cs" />
-    <Compile Include="SQL\DateTimeTest\DateTimeTest.cs" />
-    <Compile Include="SQL\InstanceNameTest\InstanceNameTest.cs" />
-    <Compile Include="SQL\IntegratedAuthenticationTest\IntegratedAuthenticationTest.cs" />
-    <Compile Include="SQL\LocalDBTest\LocalDBTest.cs" />
-    <Compile Include="SQL\MARSSessionPoolingTest\MARSSessionPoolingTest.cs" />
-    <Compile Include="SQL\MARSTest\MARSTest.cs" />
-    <Compile Include="SQL\MirroringTest\ConnectionOnMirroringTest.cs" />
-    <Compile Include="SQL\ParallelTransactionsTest\ParallelTransactionsTest.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyWidenNullInexactNumerics.cs" />
-    <Compile Include="SQL\SqlCredentialTest\SqlCredentialTest.cs" />
-    <Compile Include="SQL\SqlSchemaInfoTest\SqlSchemaInfoTest.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\AdjustPrecScaleForBulkCopy.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\AzureDistributedTransaction.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\ErrorOnRowsMarkedAsDeleted.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Bug84548.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Bug85007.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Bug903514.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Bug98182.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CheckConstraints.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\ColumnCollation.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyAllFromReader.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyAllFromReader1.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyAllFromReaderAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyAllFromReaderCancelAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyAllFromReaderConnectionCloseAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyAllFromReaderConnectionCloseOnEventAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyMultipleReaders.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopySomeFromDatatable.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopySomeFromDatatableAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopySomeFromReader.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopySomeFromRowArray.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopySomeFromRowArrayAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyVariants.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyWithEvent.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyWithEvent1.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\InvalidAccessFromEvent.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\CopyWithEventAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\FireTrigger.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Helpers.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\MissingTargetColumn.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\MissingTargetTable.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\SqlBulkCopyTest.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Transaction.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Transaction1.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Transaction2.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Transaction3.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\Transaction4.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\TransactionTestAsync.cs" />
-    <Compile Include="SQL\SqlBulkCopyTest\SpecialCharacterNames.cs" />
-    <Compile Include="SQL\SqlNamedPipesTest\SqlNamedPipesTest.cs" />
-    <Compile Include="SQL\RandomStressTest\Randomizer.cs" />
-    <Compile Include="SQL\RandomStressTest\RandomizerPool.cs" />
-    <Compile Include="SQL\RandomStressTest\SqlRandomColumnOptions.cs" />
-    <Compile Include="SQL\RandomStressTest\SqlRandomizer.cs" />
-    <Compile Include="SQL\RandomStressTest\SqlRandomTable.cs" />
-    <Compile Include="SQL\RandomStressTest\SqlRandomTableColumn.cs" />
-    <Compile Include="SQL\RandomStressTest\SqlRandomTypeInfo.cs" />
-    <Compile Include="SQL\RandomStressTest\SqlRandomTypeInfoCollection.cs" />
-    <Compile Include="SQL\RandomStressTest\SqlRandomTypesForSqlServer.cs" />
-    <Compile Include="SQL\RandomStressTest\RandomStressTest.cs" />
-    <Compile Include="SQL\SplitPacketTest\SplitPacketTest.cs" />
-    <Compile Include="SQL\SqlFileStreamTest\SqlFileStreamTest.cs" />
-    <Compile Include="SQL\SqlNotificationTest\SqlNotificationTest.cs" />
-    <Compile Include="SQL\TransactionTest\TransactionTest.cs" />
-    <Compile Include="SQL\TransactionTest\TransactionEnlistmentTest.cs" />
-    <Compile Include="SQL\UdtTest\SqlServerTypesTest.cs" />
-    <Compile Include="SQL\UdtTest\UdtBulkCopyTest.cs" />
-    <Compile Include="SQL\UdtTest\UdtTest.cs" />
-    <Compile Include="SQL\UdtTest\UdtTest2.cs" />
-    <Compile Include="SQL\UdtTest\UdtTestHelpers.cs" />
-    <Compile Include="SQL\Utf8SupportTest\Utf8SupportTest.cs" />
-    <Compile Include="SQL\WeakRefTest\WeakRefTest.cs" />
-    <Compile Include="SQL\WeakRefTestYukonSpecific\WeakRefTestYukonSpecific.cs" />
-    <Compile Include="XUnitAssemblyAttributes.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <Content Include="DDBasics\DDDataTypesTest\data.xml">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-      <Link>data.xml</Link>
-    </Content>
-    <Content Include="ProviderAgnostic\MultipleResultsTest\MultipleResultsTest.bsl">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-      <Link>MultipleResultsTest.bsl</Link>
-    </Content>
-    <Content Include="SQL\ParameterTest\SqlParameterTest_DebugMode.bsl">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-      <Link>SqlParameterTest_DebugMode.bsl</Link>
-    </Content>
-    <Content Include="SQL\ParameterTest\SqlParameterTest_ReleaseMode.bsl">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-      <Link>SqlParameterTest_ReleaseMode.bsl</Link>
-    </Content>
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="ProviderAgnostic\MultipleResultsTest\MultipleResultsTest.bsl" />
-    <None Include="SQL\ParameterTest\SqlParameterTest_DebugMode.bsl" />
-    <None Include="SQL\ParameterTest\SqlParameterTest_ReleaseMode.bsl" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="SQL\UdtTest\UDTs\Address\Address.csproj" />
-    <ProjectReference Include="SQL\UdtTest\UDTs\Circle\Circle.csproj" />
-    <ProjectReference Include="SQL\UdtTest\UDTs\Shapes\Shapes.csproj" />
-    <ProjectReference Include="SQL\UdtTest\UDTs\Utf8String\Utf8String.csproj" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/XUnitAssemblyAttributes.cs b/src/libraries/System.Data.SqlClient/tests/ManualTests/XUnitAssemblyAttributes.cs
deleted file mode 100644 (file)
index 101ea6d..0000000
+++ /dev/null
@@ -1,9 +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;
-
-// Connection pools are created per process, per connection string. So having a bunch of tests
-// run in parallel with identical connection strings causes Clear Pool tests to report incorrect results.
-[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)]
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/ManualTests/createUdtTestDb_corefx.sql b/src/libraries/System.Data.SqlClient/tests/ManualTests/createUdtTestDb_corefx.sql
deleted file mode 100644 (file)
index d81b49a..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
---
--- Setup UdtTestDb and associated UDTS, tables and procedures.
---
-PRINT N'============================================================================='
-GO
-PRINT N'Starting UdtTestDb Setup Script'
-GO
-PRINT N'============================================================================='
-GO
-SET NOCOUNT ON
-print 'Creating UdtTestDb database.'
-
-if  exists (select name from [master].[dbo].[sysdatabases] where name = N'UdtTestDb')
-    drop database [UdtTestDb]
-go
-create database [UdtTestDb]
-go
-alter database [UdtTestDb] set trustworthy on 
-go 
-
-print 'Configuring UdtTestDb database...'
-
-use UdtTestDb
-go
-
-EXEC sp_configure 'clr enabled', 1
-    go
-    RECONFIGURE
-    go
-EXEC sp_configure 'clr enabled'
-    go
-       
-create assembly address
-from
-0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103000D35305A0000000000000000E00022200B0130000010000000060000000000008A2E000000200000004000000000001000200000000200000400000000000000060000000000000000800000000200003E5E0000030040850000100000100000000010000010000000000000100000000000000000000000382E00004F00000000400000A002000000000000000000000000000000000000006000000C000000B02D00001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000900E0000002000000010000000020000000000000000000000000000200000602E72737263000000A0020000004000000004000000120000000000000000000000000000400000402E72656C6F6300000C00000000600000000200000016000000000000000000000000000040000042000000000000000000000000000000006C2E0000000000004800000002000500082400002809000009000000000000000000000000000000302D0000800000000000000000000000000000000000000000000000000000000000000000000000133001000C00000001000011001773020000060A2B00062A9A02280600000A000002167D06000004027E0700000A7D04000004027E0700000A7D050000042A7A02280600000A000002037D0400000402047D0500000402177D060000042A0000133002000F0000000200001100027B0600000416FE010A2B00062ADE0002036F0800000A730900000A7D0400000402036F0800000A730900000A7D050000040203176F0A00000A16280B00000A7D060000042AFE0003027C04000004FE160B0000016F0C00000A6F0D00000A0003027C05000004FE160B0000016F0C00000A6F0D00000A0003027B060000046F0E00000A002A00133004008E0000000300001100036F0F00000A130411042C200002167D06000004027E0700000A7D04000004027E0700000A7D050000042B60731000000A0A06036F1100000A6F1200000A0B188D120000010C178D1300000125161F7C9D0D07096F1300000A0C0208169A281400000A7D0400000402088E691730077E0700000A2B0808179A281400000A7D0500000402177D060000042B002A000013300400C500000004000011000228050000060D092C1F00036F0F00000A130411042C0538A700000000036F1500000A00389A000000027B050000048C0B0000012C0D027C05000004281600000A2B0117130511052C09027B040000040A2B3900027B040000048C0B0000017201000070281700000A281400000A0A068C0B000001027B050000048C0B000001281700000A281400000A0A001200281800000A0B160C2B1403086A0708916F1900000A00081306110617580C08078E69FE04130711072DE003086A6F1A00000A002B002A000000133001002C00000005000011000228050000060A062C0872050000700B2B1702280E0000060C1202FE160B0000016F0C00000A0B2B00072A133004008100000006000011000F00281600000A0D092C09280100000613042B690F00FE160B0000016F0C00000A0A188D120000010B188D1300000125161F7C9D25171F7C9D0C06086F1300000A0B078E6918FE01130511052C1907169A281400000A07179A281400000A730300000613042B1607169A281400000A7E0700000A730300000613042B0011042A000000133001000C0000000700001100027B040000040A2B00062A133001000C0000000700001100027B050000040A2B00062A133002004F0000000800001100027B060000040A062C3C00027C05000004281600000A0B072C09027B040000040C2B29027B040000048C0B000001027B050000048C0B000001281700000A281400000A0C2B06731B00000A7A082A0042534A4201000100000000000C00000076322E302E35303732370000000005006C00000060030000237E0000CC0300003803000023537472696E67730000000004070000100000002355530014070000100000002347554944000000240700000402000023426C6F620000000000000002000001571FA2010900000000FA013300160000010000001400000002000000060000000E00000008000000020000001B0000000300000005000000080000000100000003000000030000000100000002000000000096010100000000000600DB007C020600FB007C020600920069020F009C0200000600A600E9010A000A0348020A00BF00480206001103D8010A004800AB020A00350148020A006101AB0206001602160006002E0216000A00E402AB02060046012A0306003B02D80106004D012A0306007701D80106001102D8010A00FB01AB02000000000D00000000000100010001201000FB02000021000100010056802901560156807E01590156803A00590101007A00200001006D0020000100C40159015020000000009608A2015C01010068200000000081186302390001008F200000000086186302610102006820000000008618630206000400B02000000000E609B10149000400CB2000000000E601350069010400032100000000E6018C006F0105004421000000008600ED0275010600E021000000008600DA0275010700B42200000000C6006B0128000800EC2200000000960086007B0108007C230000000086006000820109009423000000008600520082010900AC2300000000860819018201090000000100AB010000010001000000020007000000010067020000010036030000010023010000010023010000010001030200250002002900090063020100110063020600190063020A002900630210003900630215004100630206005900CA0120006100560128005900630210006100C0022C008100DF01320041006B01280069008C00100069008C0039007100B1014900790063020600710023024D00890074015200910024035800590018035F007100BC0106005900B10149009100030372005900CA024D007100CF01780071008C017E00A10063020600080004004D0102000800520102000C0054012E000B0095012E0013009E012E001B00BD012E002300C60143002B00D6011B0024003E00650083008A0096009B00020001000000CA0187010000B5018C0100001D01900102000100030002000500050002000E00070004800000010002000000000001000000AB00FB020000020000000000000000000000A2002C0000000000020000000000000000000000A2002000000000000000006C696E6531006C696E6532003C4D6F64756C653E0053797374656D2E494F0053797374656D2E44617461006D73636F726C69620052656164004973427974654F72646572656400494E756C6C61626C65004765745365636F6E644C696E650047657446697273744C696E65006D5F7365636F6E646C696E65006D5F66697273746C696E650050617273650057726974650044656275676761626C6541747472696275746500417373656D626C794B657946696C654174747269627574650053716C55736572446566696E65645479706541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C697479417474726962757465006765745F56616C75650076616C7565004D61784279746553697A65004942696E61727953657269616C697A6500556E69636F6465456E636F64696E670052656164537472696E670053716C537472696E6700546F537472696E6700476574537472696E6700497346697865644C656E677468005365744C656E67746800416464726573732E646C6C006765745F4E756C6C00664E756C6C006765745F49734E756C6C005365744E756C6C006D5F664E6F744E756C6C007365745F4974656D0053797374656D00546F426F6F6C65616E0053797374656D2E5265666C656374696F6E0053716C4E756C6C56616C7565457863657074696F6E00436861720042696E617279526561646572006765745F4275666665720042696E61727957726974657200426974436F6E766572746572004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E446174612E53716C54797065730052656164427974657300476574556E69636F646542797465730046696C6C42797465730053716C42797465730046696C6C46726F6D4279746573004164647265737300436F6E63617400466F726D6174004F626A656374006F705F496D706C696369740053706C69740053797374656D2E5465787400770000037C0000094E0075006C006C0000009FC633470D50F04A8F3934182F3EF32200042001010803200001052001011111042001010E05200101111904070112080306112D030701020320000E0520011D0508060002021D050804200101020A0705123D0E1D0E1D0302032000020420001D050520010E1D050620011D0E1D03050001112D0E0C0708112D1D050802020208020500020E1C1C052002010A05042001010A060703020E112D0B07060E1D0E1D0302120802040701112D0607030202112D08B77A5C561934E08980A000240000048000009400000006020000002400005253413100040000010001009DA2FDED6EA758BFCD48D3E4E6743A3FD9562B89081850D119EF68A2623A529077A8506CA7ED5B788E43A0594ACD2F06CE4C90115F4D3C3547CA5194A6F0357A412C58836E2812A38EC9DD6625CA64FE18AC597BE0B74A20EB08B71A51C2D72AD0859307CC08AC91137EE538953B5F8CB19AB76BE40AAB9CB41B75D740A15EDE04F401000001000101020608020602040000120807200201112D112D0520010112310520010112350520010112390600011208112D042000112D040800120803280002042800112D0801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000701000000000F01000A7368617065732E736E6B00002B010002000000020054020D4973427974654F7264657265640054080B4D61784279746553697A65F40100000000F726B774D6CEE4E19B41D9F0021A91A9EEAA687980F455E95C9D2D62E128C1A0E458990178770F78A2D8755B08BC5F34E974F2FFBA24803EE592FB170DB7E8EAADC23228F40790455BA6E39A6D8A06D78A97F436073709473682AD05D1612D62415897EFDB377E05C7FE3E957CC52B64A42F45A4F25E47ADEA7EFCDCD0B6AE86000000000D35305A00000000020000006C000000CC2D0000CC0F00005253445364578FCD28DFF14B90A3FA07CF04A88601000000443A5C4E65744658446576335C496E7465726D6564696174655C73756974657372635C616464726573732E637370726F6A5F313935373430373334335C6F626A635C616D6436345C416464726573732E70646200602E000000000000000000007A2E00000020000000000000000000000000000000000000000000006C2E0000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF2500200010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000440200000000000000000000440234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100020001000000000002000100000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004A4010000010053007400720069006E006700460069006C00650049006E0066006F0000008001000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000031002E0032002E0030002E003000000038000C00010049006E007400650072006E0061006C004E0061006D006500000041006400640072006500730073002E0064006C006C0000002800020001004C006500670061006C0043006F00700079007200690067006800740000002000000040000C0001004F0072006900670069006E0061006C00460069006C0065006E0061006D006500000041006400640072006500730073002E0064006C006C000000340008000100500072006F006400750063007400560065007200730069006F006E00000031002E0032002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0032002E0030002E00300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C0000008C3E00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-with permission_set = safe
-go
-create assembly circle from
-0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103000E35305A0000000000000000E00022200B01300000160000000600000000000052340000002000000040000000000010002000000002000004000000000000000600000000000000008000000002000059390000030040850000100000100000000010000010000000000000100000000000000000000000FE3300004F00000000400000A002000000000000000000000000000000000000006000000C000000783300001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E7465787400000058140000002000000016000000020000000000000000000000000000200000602E72737263000000A0020000004000000004000000180000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001C0000000000000000000000000000400000420000000000000000000000000000000032340000000000004800000002000500E0260000180C000009000000000000000000000000000000F8320000800000000000000000000000000000000000000000000000000000000000000000000000133001000C00000001000011001773050000060A2B00062AE6000273100000067D01000004027B01000004036F0E0000060002036F0600000A7D020000040203176F0700000A16280800000A7D030000042AA600027B01000004036F0F0000060003027B020000046F0900000A0003027B030000046F0A00000A002A1330020043000000000000000273100000067D0100000402167D0300000402280B00000A0000027B01000004166F1A00000600027B01000004166F1C0000060002167D0200000402167D030000042A8A0273100000067D0100000402167D0300000402280B00000A000002177D030000042A0000133001000C0000000200001100027B030000040A2B00062A13300300680000000300001100036F0C00000A0B072C0A0002177D030000042B52036F0D00000A1F0C6AFE0116FE010C082C06730E00000A7A036F0F00000A0A027B010000040616281000000A6F1A00000600027B01000004061A281000000A6F1C0000060002061E281000000A7D020000042A13300400A60000000400001100027B030000040D092C1C00036F0C00000A130411042C05388800000000036F1100000A002B7E1F0C8D120000010A027B010000046F19000006281200000A0B0706166F1300000A00027B010000046F1B000006281200000A0B07061A6F1300000A00027B02000004281200000A0B07061E6F1300000A00160C2B1403086A0608916F1400000A00081305110517580C08068E69FE04130611062DE003086A6F1500000A002A0000133005006E00000005000011000F00281600000A178D1400000125161F2C9D6F1700000A0A068E6919FE0116FE010C082C06730E00000A7A73040000060B077B0100000406169A281800000A6F1A00000600077B0100000406179A281800000A6F1C000006000706189A281800000A7D02000004070D2B00092A000013300200420000000600001100731900000A0A06027B010000046F1A00000A6F1B00000A260672010000706F1B00000A2606027C02000004281C00000A6F1B00000A26066F1A00000A0B2B00072A0000133001000C0000000700001100027B010000040A2B00062A133001000C0000000800001100027B020000040A2B00062A133001000C00000007000011001773110000060A2B00062AB60002036F0600000A7D0700000402036F0600000A7D080000040203176F0700000A16280800000A7D090000042AA60003027B070000046F0900000A0003027B080000046F0900000A0003027B090000046F0A00000A002A9602167D0900000402280B00000A000002167D0700000402167D0800000402167D090000042A5E02167D0900000402280B00000A000002177D090000042A9602167D0900000402280B00000A000002037D0700000402047D0800000402167D090000042A133001000C0000000200001100027B090000040A2B00062A13300300300000000200001100038E691F09FE0116FE010A062C06730E00000A7A020316281000000A7D0700000402031A281000000A7D080000042A133002002E0000000900001100036F0C00000A0B072C0A0002177D090000042B18036F0F00000A0A020628140000060002167D090000042B002A000013300400860000000400001100027B090000040D092C1900036F0C00000A130411042C022B6B00036F1100000A002B611F098D120000010A027B07000004281200000A0B0706166F1300000A00027B08000004281200000A0B07061A6F1300000A00160C2B1403086A0608916F1400000A00081305110517580C08068E69FE04130611062DE003086A6F1500000A002B002A0000133005004C0000000A000011000F00281600000A178D1400000125161F2C9D6F1700000A0A068E6918FE0116FE010D092C06730E00000A7A06169A281800000A0B06179A281800000A0C0708731200000613042B0011042A13300200380000000600001100731900000A0A06027B070000046F1D00000A260672010000706F1B00000A2606027B080000046F1D00000A26066F1A00000A0B2B00072A133001000C0000000800001100027B070000040A2B00062A260002037D070000042A0000133001000C0000000800001100027B080000040A2B00062A260002037D080000042A0000133003000E0000000B00001100021616281F0000060A2B00062A000013300300180000000B0000110002037B07000004037B08000004281F0000060A2B00062A133003003A0000000B0000110003027B07000004596C230000000000000040281E00000A04027B08000004596C230000000000000040281E00000A58281F00000A0A2B00062A000042534A4201000100000000000C00000076322E302E35303732370000000005006C00000070050000237E0000DC0500009403000023537472696E67730000000070090000080000002355530078090000100000002347554944000000880900009002000023426C6F620000000000000002000001571FA2010900000000FA0133001600000100000017000000030000000D0000001F00000014000000040000001F00000007000000060000000B00000002000000080000000A00000001000000020000000000CD010100000000000600FB00DA0206001B01DA020600B200C7020F00FA0200000600C6002F020A005D03A6020A00DF00A602060064030B020A00950009030A006B01A60206005F02230006007A0223000A00320309030A007C01090306006C027603060099020B02060041020B02060039010B02060089030B0206005A020B02060088010B02060014000B0206008F010B02000000001A000000000001000100012010009F0000002100010001000120100001000000210007000D00010092028B01010073008F010100F201920156805F018F0156809F019201568077009201010087038F01010090038F010100F201920156805F018F0156809F019201568077009201568048018F015020000000009608D80195010100682000000000E6016E009A010100A22000000000E601AC00A0010200CC20000000008618C102060003001B21000000008618C10231000300402100000000E609E7014100040058210000000086003B03A6010400CC210000000086002803A60105008022000000009600A600AC010600FC2200000000C6008601830007004C230000000086088702B301070064230000000086085203200007007C23000000009608D801B8010700942300000000E6016E009A010700C22300000000E601AC00A0010800EC23000000008618C102060009001224000000008618C102310009002A24000000008618C102BD010A00502400000000E609E70141000C006824000000008600B701C3010C00A4240000000086003B03A6010D00E0240000000086002803A6010E007425000000009600A600C9010F00CC2500000000C60086018300100010260000000086082D0020001000282600000000860833000100100034260000000086084800200011004C260000000086084E000100110058260000000086008C00D001120074260000000086001202D401120098260000000086003900DA01130000000100C50200000100840300000100E10100000100600000000100600000000100600000000100C50200000100840300000100E101000001008603000002008F03000001006000000001005901000001005901000001006000000001005901000001005901000001001F02000001008603000002008F03020025000200290003002500030029000900C10201001100C10206001900C1020A002900C10210003900C102150059000800200059001E032400810025022A006100AC0001006100AC0031004100C10206006900E70141006900940145008900C102060069003E014900810012004E006900FA010600810049036100990053026700690002026E006900AD01740071003E018300A9006B038700B100A6008E007900C1020600410086018300790085009900B1008601830079008500B800B9008203C200B9007103C800080010007801020014007D01020018007F0108002800810102002C007D01020030007F010800340086012E000B00F7012E00130000022E001B001F022E002300280243002B00380263002B0064021B0036003A005500790093009F00A400A800AE00BE0002000100030005000000FD01E0010000F301E50100008B02E90100005603EE010000FD01F2010000F301E50100003700EE0100005200EE0102000100030002000600050002000B00070002000C00090002000D000B00020013000D00020019000F0001001A000F0002001B00110001001C00110004800000010002000000000001000000D6009F000000020000000000000000000000CD00650000000000020000000000000000000000CD00540000000000000000506F696E74310052656164496E74333200546F496E743332003C4D6F64756C653E0053797374656D2E494F006765745F58007365745F580044697374616E636546726F6D5859006765745F59007365745F590053797374656D2E446174610064617461006D73636F726C6962005265616400726164004973427974654F72646572656400417070656E640044697374616E636500494E756C6C61626C6500436972636C650050617273650057726974650044656275676761626C6541747472696275746500417373656D626C794B657946696C654174747269627574650053716C55736572446566696E65645479706541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650042797465006765745F56616C7565004D61784279746553697A6556616C75650076616C7565004D61784279746553697A65004942696E61727953657269616C697A650053716C537472696E6700546F537472696E67004D617468006765745F4C656E67746800497346697865644C656E677468005365744C656E6774680046696C6C46726F6D4279746573496E7465726E616C00436972636C652E646C6C006765745F4E756C6C00664E756C6C006765745F49734E756C6C006649734E756C6C005365744E756C6C007365745F4974656D0053797374656D0044697374616E636546726F6D007046726F6D00546F426F6F6C65616E0053797374656D2E5265666C656374696F6E00417267756D656E74457863657074696F6E00436F7079546F00436861720042696E61727952656164657200537472696E674275696C6465720042696E617279577269746572006765745F43656E7465720063656E74657200426974436F6E766572746572004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E446174612E53716C5479706573005265616442797465730046696C6C42797465730053716C42797465730046696C6C46726F6D4279746573004765744279746573006765745F52616469757300466F726D6174004F626A6563740053706C697400537172740053797374656D2E5465787400506F7700697800417272617900697900000000032C0000000000CAE1227FDAD2FC4B80B468D7D286461700042001010803200001052001011111042001010E0520010111190407011208032000080520011D0508060002021D05080420010102030701020607031D050202032000020320000A0420001D05060002081D05080B07071D051D0508020208020500011D050806200201124D08052002010A05042001010A0907041D0E12080212080320000E0620011D0E1D03040001080E050702123D0E052001123D0E040701120C030701080507021D05020907051D0E080802120C052001123D080307010D0500020D0D0D0400010D0D08B77A5C561934E08980A000240000048000009400000006020000002400005253413100040000010001009DA2FDED6EA758BFCD48D3E4E6743A3FD9562B89081850D119EF68A2623A529077A8506CA7ED5B788E43A0594ACD2F06CE4C90115F4D3C3547CA5194A6F0357A412C58836E2812A38EC9DD6625CA64FE18AC597BE0B74A20EB08B71A51C2D72AD0859307CC08AC91137EE538953B5F8CB19AB76BE40AAB9CB41B75D740A15EDE041E000000010101000409000000040C0000000306120C020608020602040000120805200101122D05200101123105200101123506000112081139042000120C040000120C052002010808052001011D05060001120C11390320000D0520010D120C0520020D0808040800120803280002042800120C03280008040800120C0801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000701000000000F01000A7368617065732E736E6B00002B010002000000020054020D4973427974654F7264657265640054080B4D61784279746553697A651E0000002B010002000000020054020D4973427974654F7264657265640154080B4D61784279746553697A6509000000237AF3998B232A1511CF80B1A066F9735F62378908023FD50D7954FD297AF0C4AE6F1D285DEC0D38F27F5E6742D170FBDA5F48C126FF064C2022F76669A2AE6E33C11758930BE5CB1872B57A5626D2233B624FC113CC8472A72A6456DE13895FD6BFED882F238DF3BE893AF020057306FC831809A4E28DFE096CE032F3FCAD26000000000E35305A00000000020000006A00000094330000941500005253445393B182DA5E99404D85D9EEF7D3D2585201000000443A5C4E65744658446576335C496E7465726D6564696174655C73756974657372635C636972636C652E637370726F6A5F5F3231393539383632365C6F626A635C616D6436345C436972636C652E706462002634000000000000000000004034000000200000000000000000000000000000000000000000000032340000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C00000000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000440200000000000000000000440234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100020001000000000002000100000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004A4010000010053007400720069006E006700460069006C00650049006E0066006F0000008001000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000031002E0032002E0030002E003000000036000B00010049006E007400650072006E0061006C004E0061006D006500000043006900720063006C0065002E0064006C006C00000000002800020001004C006500670061006C0043006F0070007900720069006700680074000000200000003E000B0001004F0072006900670069006E0061006C00460069006C0065006E0061006D006500000043006900720063006C0065002E0064006C006C0000000000340008000100500072006F006400750063007400560065007200730069006F006E00000031002E0032002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0032002E0030002E00300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C000000543400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-with permission_set = safe
-go
-create assembly shapes from
-0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103000E35305A0000000000000000E00022200B013000001600000006000000000000BA35000000200000004000000000001000200000000200000400000000000000060000000000000000800000000200005F330000030040850000100000100000000010000010000000000000100000000000000000000000673500004F00000000400000A002000000000000000000000000000000000000006000000C000000E03400001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000C0150000002000000016000000020000000000000000000000000000200000602E72737263000000A0020000004000000004000000180000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001C000000000000000000000000000040000042000000000000000000000000000000009B35000000000000480000000200050018280000480C00000900000000000000000000000000000060340000800000000000000000000000000000000000000000000000000000000000000000000000133001000C00000001000011001773030000060A2B00062A1330060060000000020000110273120000067D010000040273120000067D0200000402167D0300000402280600000A0000027B01000004027B01000004027B02000004027B0200000416250C6F1E0000060008250B6F1C0000060007250A6F1E00000600066F1C000006002AB60273120000067D010000040273120000067D0200000402167D0300000402280600000A000002177D030000042A0000133002006E000000000000000273120000067D010000040273120000067D0200000402167D0300000402280600000A0000027B01000004036F1B0000066F1C00000600027B01000004036F1D0000066F1E00000600027B02000004046F1B0000066F1C00000600027B02000004046F1D0000066F1E000006002A0000133001000C0000000300001100027B030000040A2B00062A133003004500000000000000000273120000067D01000004027B01000004036F10000006000273120000067D02000004027B02000004036F10000006000203176F0700000A16280800000A7D030000042AA600027B01000004036F1100000600027B02000004036F110000060003027B030000046F0900000A002A0013300300820000000400001100036F0A00000A0B072C0A0002177D030000042B6C036F0B00000A1F106AFE0116FE010C082C06730C00000A7A036F0D00000A0A027B010000040616280E00000A6F1C00000600027B01000004061A280E00000A6F1E00000600027B02000004061E280E00000A6F1C00000600027B02000004061F0C280E00000A6F1E000006002A000013300400C90000000500001100027B030000040D092C1F00036F0A00000A130411042C0538AB00000000036F0F00000A00389E0000001F108D120000010A027B010000046F1B000006281000000A0B0706166F1100000A00027B010000046F1D000006281000000A0B07061A6F1100000A00027B020000046F1B000006281000000A0B07061E6F1100000A00027B020000046F1D000006281000000A0B07061F0C6F1100000A00160C2B1403086A0608916F1200000A00081305110517580C08068E69FE04130611062DE003086A6F1300000A002A000000133005008800000006000011000F00281400000A178D1400000125161F2C9D6F1500000A0A068E691AFE0116FE010C082C06730C00000A7A73020000060B077B0100000406169A281600000A6F1C00000600077B0100000406179A281600000A6F1E00000600077B0200000406189A281600000A6F1C00000600077B0200000406199A281600000A6F1E00000600070D2B00092A13300200420000000700001100731700000A0A06027B010000046F1800000A6F1900000A260672010000706F1900000A2606027B020000046F1800000A6F1900000A26066F1800000A0B2B00072A000013300200170000000800001100027B02000004027B010000046F200000060A2B00062A00133001000C0000000900001100027B010000040A2B00062A133001000C0000000900001100027B020000040A2B00062A133001000C00000009000011001773130000060A2B00062AB60002036F1A00000A7D0700000402036F1A00000A7D080000040203176F0700000A16280800000A7D090000042AA60003027B070000046F1B00000A0003027B080000046F1B00000A0003027B090000046F0900000A002A9602167D0900000402280600000A000002167D0700000402167D0800000402167D090000042A5E02167D0900000402280600000A000002177D090000042A9602167D0900000402280600000A000002037D0700000402047D0800000402167D090000042A133001000C0000000300001100027B090000040A2B00062A13300300300000000300001100038E691F09FE0116FE010A062C06730C00000A7A020316280E00000A7D0700000402031A280E00000A7D080000042A133002002E0000000A00001100036F0A00000A0B072C0A0002177D090000042B18036F0D00000A0A020628160000060002167D090000042B002A000013300400860000000500001100027B090000040D092C1900036F0A00000A130411042C022B6B00036F0F00000A002B611F098D120000010A027B07000004281000000A0B0706166F1100000A00027B08000004281000000A0B07061A6F1100000A00160C2B1403086A0608916F1200000A00081305110517580C08068E69FE04130611062DE003086A6F1300000A002B002A0000133005004C0000000B000011000F00281400000A178D1400000125161F2C9D6F1500000A0A068E6918FE0116FE010D092C06730C00000A7A06169A281600000A0B06179A281600000A0C0708731400000613042B0011042A13300200380000000700001100731700000A0A06027B070000046F1C00000A260672010000706F1900000A2606027B080000046F1C00000A26066F1800000A0B2B00072A133001000C0000000C00001100027B070000040A2B00062A260002037D070000042A0000133001000C0000000C00001100027B080000040A2B00062A260002037D080000042A0000133003000E000000080000110002161628210000060A2B00062A00001330030018000000080000110002037B07000004037B0800000428210000060A2B00062A133003003A000000080000110003027B07000004596C230000000000000040281D00000A04027B08000004596C230000000000000040281D00000A58281E00000A0A2B00062A000042534A4201000100000000000C00000076322E302E35303732370000000005006C00000094050000237E0000000600009003000023537472696E67730000000090090000080000002355530098090000100000002347554944000000A8090000A002000023426C6F620000000000000002000001571FA2010900000000FA0133001600000100000017000000030000000D0000002100000016000000040000001E00000007000000060000000C00000002000000080000000A00000001000000020000000000C8010100000000000600F600C30206001601C3020600AD00B0020F00E30200000600C1002A020A0042038F020A00DA008F020600490306020A009200F9020A0066018F0206005A021C00060075021C000A002203F9020A007701F90206006702710306008202060206003C02060206003401060206008403060206005502060206008301060206000D00060206008A0106020000000013000000000001000100012010009C0000002100010001000120100056030000210007000F000100660391010100850091010100ED01950156805A01980156809A01950156806C00950101008203980101008B0398010100ED01950156805A01980156809A01950156806C0095015680430198015020000000009608D3019B0101006820000000008618AA0206000100D420000000008618AA02370001000421000000008618AA02A0010200802100000000E609E20143000400982100000000E6016700A8010400E92100000000E601A700AE01050014220000000086002B03B4010600A4220000000086001803B40107007C23000000009600A100BA010800102400000000C6008101850009006024000000008600AB01C101090084240000000086085C03C50109009C240000000086087A00C5010900B424000000009608D301CA010900CC2400000000E6016700A8010900FA2400000000E601A700AE010A002425000000008618AA0206000B004A25000000008618AA0237000B006225000000008618AA02CF010C00882500000000E609E20143000E00A025000000008600B201D5010E00DC250000000086002B03B4010F0018260000000086001803B4011000AC26000000009600A100DB011100042700000000C60081018500120048270000000086082600AA00120060270000000086082C00010012006C270000000086084100AA001300842700000000860847000100130090270000000086008900C1011400AC270000000086000D02E2011400D0270000000086003200E801150000000100DC01000001008103000002008A0300000100AE02000001007F0300000100590000000100590000000100590000000100AE02000001007F0300000100DC01000001008103000002008A03000001005900000001005401000001005401000001005900000001005401000001005401000001001A02000001008103000002008A03020025000200290003002500030029000900AA0201001100AA0206001900AA020A002900AA0210003900AA0215004100AA02060059000E032A008100200230006100A70037006900E201430069008F0147008900AA020600690039014B0081000B0050006900F501060081003903630099004E0269006900FD0170006900A8017600710039018500A90050038900B100A10090007900AA020600410081018500790082009B0059000100AA006100A700010079008200BE00B9007D03C800B9006C03CE00080010007E0102001400830102001800850108002800870102002C008301020030008501080034008C012E000B0005022E0013000E022E001B002D022E002300360243002B00460263002B0072021B00200026003C0057007B009500A100A500AE00B400C40002000100030005000000F801EE010000EE01F30100006003F70100007E00F7010000F801FC010000EE01F30100003000010200004B00010202000100030002000500050002000D00070002000E00090002000F000B00020015000D0002001B000F0001001C000F0002001D00110001001E00110004800000010002000000000001000000DC00F2020000020000000000000000000000D3005E0000000000020000000000000000000000D3004D000000000000000052656164496E74333200546F496E743332003C4D6F64756C653E0053797374656D2E494F006765745F58007365745F580044697374616E636546726F6D5859006765745F59007365745F590053797374656D2E446174610064617461006D73636F726C69620052656164004973427974654F726465726564006765745F456E6400417070656E640044697374616E636500494E756C6C61626C65004C696E650050617273650057726974650044656275676761626C6541747472696275746500417373656D626C794B657946696C654174747269627574650053716C55736572446566696E65645479706541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650042797465006765745F56616C7565004D61784279746553697A6556616C75650076616C7565004D61784279746553697A65004942696E61727953657269616C697A650053716C537472696E6700546F537472696E67004D617468006765745F4C656E67746800497346697865644C656E677468005365744C656E6774680046696C6C46726F6D4279746573496E7465726E616C005368617065732E646C6C006765745F4E756C6C00664E756C6C006765745F49734E756C6C006649734E756C6C005365744E756C6C007365745F4974656D0053797374656D0044697374616E636546726F6D007046726F6D00546F426F6F6C65616E0053797374656D2E5265666C656374696F6E00417267756D656E74457863657074696F6E00436F7079546F00436861720042696E61727952656164657200537472696E674275696C6465720042696E61727957726974657200426974436F6E766572746572004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F646573005368617065730053797374656D2E446174612E53716C5479706573005265616442797465730046696C6C42797465730053716C42797465730046696C6C46726F6D427974657300476574427974657300466F726D6174004F626A6563740053706C697400506F696E74006765745F537461727400737461727400537172740053797374656D2E5465787400506F770069780041727261790069790000000000032C000000000059E29A85691EF343952D58713C52466D00042001010803200001052001011111042001010E0520010111190407011208050703080808030701020520011D0508060002021D050804200101020607031D050202032000020320000A0420001D05060002081D05080B07071D051D0508020208020500011D050806200201124D08052002010A05042001010A0907041D0E12080212080320000E0620011D0E1D03040001080E050702123D0E052001123D0E0307010D040701120C032000080507021D05020907051D0E080802120C052001123D08030701080500020D0D0D0400010D0D08B77A5C561934E08980A000240000048000009400000006020000002400005253413100040000010001009DA2FDED6EA758BFCD48D3E4E6743A3FD9562B89081850D119EF68A2623A529077A8506CA7ED5B788E43A0594ACD2F06CE4C90115F4D3C3547CA5194A6F0357A412C58836E2812A38EC9DD6625CA64FE18AC597BE0B74A20EB08B71A51C2D72AD0859307CC08AC91137EE538953B5F8CB19AB76BE40AAB9CB41B75D740A15EDE0414000000010101000409000000040C0000000306120C020602020608040000120807200201120C120C05200101122D052001011231052001011235060001120811390320000D042000120C040000120C052002010808052001011D05060001120C11390520010D120C0520020D0808040800120803280002042800120C040800120C032800080801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000701000000000F01000A7368617065732E736E6B00002B010002000000020054020D4973427974654F7264657265640054080B4D61784279746553697A65140000002B010002000000020054020D4973427974654F7264657265640154080B4D61784279746553697A65090000000000C7543C2B7EA843E1D1B10AFDA58B14890C124DC295A3C149591FDB001F74E98A982DC4010F3880C429D8E72E061A3878D0EC188268C944C9DD614493768E89663C6600E3EDF1610E028A20A69740F930549314FA18764BE1DC81F8535DE0EBE8EDF0AE4C0A5854EAD93EDC742D09F6521319070DD8621C6B2ABA8D53310DEBC8000000000E35305A00000000020000006B000000FC340000FC1600005253445375AD7217CC13B749927F88E4CCE1E75B01000000443A5C4E65744658446576335C496E7465726D6564696174655C73756974657372635C7368617065732E637370726F6A5F5F313739323734333635315C6F626A635C616D6436345C5368617065732E706462008F3500000000000000000000A93500000020000000000000000000000000000000000000000000009B350000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C000000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000440200000000000000000000440234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100020001000000000002000100000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004A4010000010053007400720069006E006700460069006C00650049006E0066006F0000008001000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000031002E0032002E0030002E003000000036000B00010049006E007400650072006E0061006C004E0061006D00650000005300680061007000650073002E0064006C006C00000000002800020001004C006500670061006C0043006F0070007900720069006700680074000000200000003E000B0001004F0072006900670069006E0061006C00460069006C0065006E0061006D00650000005300680061007000650073002E0064006C006C0000000000340008000100500072006F006400750063007400560065007200730069006F006E00000031002E0032002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0032002E0030002E00300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C000000BC3500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-with permission_set = safe
-go
-create assembly weakpoint from
-0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103001035305A0000000000000000E00022200B013000000C000000060000000000000A2B0000002000000040000000000010002000000002000004000000000000000600000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000B82A00004F00000000400000A802000000000000000000000000000000000000006000000C0000002C2A00001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000100B000000200000000C000000020000000000000000000000000000200000602E72737263000000A80200000040000000040000000E0000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001200000000000000000000000000004000004200000000000000000000000000000000EC2A0000000000004800000002000500A8220000840700000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000133001000C00000001000011001773060000060A2B00062A133001000C0000000200001100027B030000040A2B00062AB60002036F0500000A7D0100000402036F0500000A7D020000040203176F0600000A16280700000A7D030000042AA60003027B010000046F0800000A0003027B020000046F0800000A0003027B030000046F0900000A002A9602167D0300000402280A00000A000002167D0100000402167D0200000402167D030000042A5E02167D0300000402280A00000A000002177D030000042A9602167D0300000402280A00000A000002037D0100000402047D0200000402167D030000042A133005004C00000003000011000F00280B00000A178D0F00000125161F2C9D6F0C00000A0A068E6918FE0116FE010D092C06730D00000A7A06169A280E00000A0B06179A280E00000A0C0708730700000613042B0011042A13300200380000000400001100730F00000A0A06027B010000046F1000000A260672010000706F1100000A2606027B020000046F1000000A26066F1200000A0B2B00072A133001000C0000000500001100027B010000040A2B00062A260002037D010000042A0000133001000C0000000500001100027B020000040A2B00062A260002037D020000042A0000133003000E000000060000110002161628100000060A2B00062A00001330030018000000060000110002037B01000004037B0200000428100000060A2B00062A133003003A000000060000110003027B01000004596C230000000000000040281300000A04027B02000004596C230000000000000040281300000A58281400000A0A2B00062A000042534A4201000100000000000C00000076322E302E35303732370000000005006C00000044030000237E0000B00300008C02000023537472696E6773000000003C060000080000002355530044060000100000002347554944000000540600003001000023426C6F6200000000000000020000015717A2010900000000FA01330016000001000000130000000200000003000000100000000B000000020000001400000004000000060000000100000004000000060000000100000002000000000031010100000000000600BA0005020600DA00050206008A00F2010F00250200000A005302D1010A009E00D10106005A0261010A00740034020A000801D10106009C0114000600B70114000A00190134020600A90176020600C401610106009701610106002501610106008501610106000500610106002C016101000000000B00000000000100010001201000670200001D0001000100010087027D0001008A027D0001005901800050200000000096083F0183000100682000000000E6094E0188000100802000000000E6015F008C000100AE2000000000E601840092000200D820000000008618EC0106000300FE20000000008618EC01300003001621000000008618EC01980004003C210000000096007E009E000600942100000000C60023013F000700D8210000000086081E001F000700F021000000008608240001000700FC2100000000860839001F00080014220000000086083F000100080020220000000086006B00A50009003C220000000086006801A900090060220000000086002A00AF000A0000000100F00100000100840200000100480100000100860200000200890200000100510000000100020100000100020100000100750100000100860200000200890202002100020025000900EC0101001100EC0106001900EC010A003100EC011000510001001F0051004902230071007B0129005900840001005900840030003900EC0106006100F8003F008100610243008900EC01060091007E004A006900EC010600690064005500690064005B00390023013F00990082026900990071026F002E000B00C2002E001300CB002E001B00EA0043002300F30016001B0035004F00610065000200010000005C01B50000005A01BA0000002800BE0000004300BE0002000100030002000200050002000A00070001000B00070002000C00090001000D000900048000000000000000000000000000000000670200000200000000000000000000007400560000000000020000000000000000000000740045000000000000000052656164496E743332003C4D6F64756C653E0053797374656D2E494F006765745F58007365745F580044697374616E636546726F6D5859006765745F59007365745F590053797374656D2E446174610064617461006D73636F726C6962005265616400417070656E640044697374616E636500494E756C6C61626C650050617273650057726974650044656275676761626C654174747269627574650053716C55736572446566696E65645479706541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C697479417474726962757465006765745F56616C75650076616C7565004942696E61727953657269616C697A650053716C537472696E6700546F537472696E67004D617468005765616B506F696E742E646C6C006765745F4E756C6C00664E756C6C006765745F49734E756C6C006649734E756C6C0053797374656D0044697374616E636546726F6D007046726F6D00546F426F6F6C65616E00417267756D656E74457863657074696F6E00436861720042696E61727952656164657200537472696E674275696C6465720042696E61727957726974657200426974436F6E766572746572004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E446174612E53716C54797065730052656164427974657300466F726D6174004F626A6563740053706C6974005765616B506F696E7400537172740053797374656D2E5465787400506F770069780069790000032C00000000001C6A2D297F0ED54E9AA9C5ED1B2E659800042001010803200001052001011111052001011115040701120803070102032000080520011D0508060002021D050804200101020907051D0E08080212080320000E0620011D0E1D03040001080E05070212350E05200112350805200112350E030701080307010D0500020D0D0D0400010D0D08B77A5C561934E08902060802060204000012080320000205200101122905200101122D052002010808060001120811310320000D0520010D12080520020D0808040800120803280002032800080801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000701000000003C010002000000030054020D4973427974654F7264657265640054080B4D61784279746553697A650900000054020D497346697865644C656E67746801000000001035305A000000000200000070000000482A0000480C0000525344534DC50A309930A04DB58620223DCA5E2901000000443A5C4E65744658446576335C496E7465726D6564696174655C73756974657372635C7765616B706F696E742E637370726F6A5F313436393531383132305C6F626A635C616D6436345C5765616B506F696E742E70646200E02A00000000000000000000FA2A0000002000000000000000000000000000000000000000000000EC2A0000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF2500200010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001000000018000080000000000000000000000000000001000100000030000080000000000000000000000000000001000000000048000000584000004C02000000000000000000004C0234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100000000000000000000000000000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004AC010000010053007400720069006E006700460069006C00650049006E0066006F0000008801000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000030002E0030002E0030002E00300000003C000E00010049006E007400650072006E0061006C004E0061006D00650000005700650061006B0050006F0069006E0074002E0064006C006C0000002800020001004C006500670061006C0043006F00700079007200690067006800740000002000000044000E0001004F0072006900670069006E0061006C00460069006C0065006E0061006D00650000005700650061006B0050006F0069006E0074002E0064006C006C000000340008000100500072006F006400750063007400560065007200730069006F006E00000030002E0030002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000030002E0030002E0030002E0030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C0000000C3B00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-with permission_set = safe
-go
-create assembly weakline from
-0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103001135305A0000000000000000E00022200B013000000E00000006000000000000CE2D00000020000000400000000000100020000000020000040000000000000006000000000000000080000000020000000000000300408500001000001000000000100000100000000000001000000000000000000000007B2D00004F00000000400000A802000000000000000000000000000000000000006000000C000000F02C00001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000D40D000000200000000E000000020000000000000000000000000000200000602E72737263000000A8020000004000000004000000100000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001400000000000000000000000000004000004200000000000000000000000000000000AF2D0000000000004800000002000500B42400003C0800000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000133001000C00000001000011001773040000060A2B00062A133001000C0000000200001100027B030000040A2B00062A13300600600000000300001102730500000A7D0100000402730500000A7D0200000402167D0300000402280600000A0000027B01000004027B01000004027B02000004027B0200000416250C6F0700000A0008250B6F0800000A0007250A6F0700000A00066F0800000A002AB602730500000A7D0100000402730500000A7D0200000402167D0300000402280600000A000002177D030000042A0000133002006E0000000000000002730500000A7D0100000402730500000A7D0200000402167D0300000402280600000A0000027B01000004036F0900000A6F0800000A00027B01000004036F0A00000A6F0700000A00027B02000004046F0900000A6F0800000A00027B02000004046F0A00000A6F0700000A002A00001330030045000000000000000002730500000A7D01000004027B01000004036F0B00000A0002730500000A7D02000004027B02000004036F0B00000A000203176F0C00000A16280D00000A7D030000042AA600027B01000004036F0E00000A00027B02000004036F0E00000A0003027B030000046F0F00000A002A0013300300820000000400001100036F1000000A0B072C0A0002177D030000042B6C036F1100000A1F146AFE0116FE010C082C06731200000A7A036F1300000A0A027B010000040616281400000A6F0800000A00027B01000004061A281400000A6F0700000A00027B02000004061E281400000A6F0800000A00027B02000004061F0C281400000A6F0700000A002A000013300400C90000000500001100027B030000040D092C1F00036F1000000A130411042C0538AB00000000036F1500000A00389E0000001F108D120000010A027B010000046F0900000A281600000A0B0706166F1700000A00027B010000046F0A00000A281600000A0B07061A6F1700000A00027B020000046F0900000A281600000A0B07061E6F1700000A00027B020000046F0A00000A281600000A0B07061F0C6F1700000A00160C2B1403086A0608916F1800000A00081305110517580C08068E69FE04130611062DE003086A6F1900000A002A000000133005008800000006000011000F00281A00000A178D1400000125161F2C9D6F1B00000A0A068E691AFE0116FE010C082C06731200000A7A73030000060B077B0100000406169A281C00000A6F0800000A00077B0100000406179A281C00000A6F0700000A00077B0200000406189A281C00000A6F0800000A00077B0200000406199A281C00000A6F0700000A00070D2B00092A13300200420000000700001100731D00000A0A06027B010000046F1E00000A6F1F00000A260672010000706F1F00000A2606027B020000046F1E00000A6F1F00000A26066F1E00000A0B2B00072A000013300200170000000800001100027B02000004027B010000046F2000000A0A2B00062A00133001000C0000000900001100027B010000040A2B00062A133001000C0000000900001100027B020000040A2B00062A42534A4201000100000000000C00000076322E302E35303732370000000005006C00000080030000237E0000EC030000DC02000023537472696E677300000000C80600000800000023555300D0060000100000002347554944000000E00600005C01000023426C6F6200000000000000020000015717A2010900000000FA013300160000010000001600000002000000030000000E00000008000000020000002000000004000000090000000100000004000000040000000100000003000000000037010100000000000600B1001C020600D1001C020600810009020F003C0200000A009402E8010A009500E80106009B0277010A0062004B020A00FE00E8010E00A80200000600B30112000600CE0112000A0074024B020A000F014B020600C001C2020600DB0177010600950177010600EF0077010600D30277010600AE01770106001B0177010600030077010000000009000000000001000100012010006C0000001D00010001000100BC02C40001005E00C40001005E01C80050200000000096084401CB000100682000000000E60953014E0001008020000000008618030206000100EC200000000086180302420001001C210000000086180302D0000200982100000000E6014E0029000400E92100000000E6017B003C00050014220000000086007D02D8000600A4220000000086006A02D80007007C230000000096007500DE000800102400000000C60019019000090060240000000086003001E50009008424000000008608B202E90009009C240000000086085300E9000900000001004D0100000100D00200000200D90200000100070200000100CE020000010040000000010040000000010040000200210002002500090003020100110003020600190003020A0031000302100051000302060039000302060051002E00010051002200010051001C00250051002800250051004E002900590060022F0081008B01350051007B003C0061007B004200690053014E006900220152008900030206006900F4005600810001005B0069006601060081008B026E009900A701740069006E017B0069002D0181007100F4009000A900A2029400B10075009B0079000302060039001901900079005B00A60051007E01B0002E000B00FC002E00130005012E001B002401430023002D0116001B001F00470062008600A000AC00B6000200010000006901EE0000005F01F3000000B602F70000005700F70002000100030002000200050002000D00070002000E0009000480000000000000000000000000000000006C000000020000000000000000000000BB00450000000000020000000000000000000000BB003400000000000000000000000000000000000000A802000000000000000000546F496E743332003C4D6F64756C653E0053797374656D2E494F006765745F58007365745F58006765745F59007365745F590053797374656D2E446174610064617461006D73636F726C69620052656164006765745F456E6400417070656E6400494E756C6C61626C65005765616B4C696E650050617273650057726974650044656275676761626C654174747269627574650053716C55736572446566696E65645479706541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650042797465006765745F56616C7565004942696E61727953657269616C697A650053716C537472696E6700546F537472696E67006765745F4C656E677468005365744C656E677468005765616B4C696E652E646C6C006765745F4E756C6C00664E756C6C006765745F49734E756C6C006649734E756C6C005365744E756C6C007365745F4974656D0053797374656D0044697374616E636546726F6D00546F426F6F6C65616E00417267756D656E74457863657074696F6E00436F7079546F00436861720042696E61727952656164657200537472696E674275696C6465720042696E61727957726974657200426974436F6E766572746572004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E446174612E53716C5479706573005265616442797465730046696C6C42797465730053716C42797465730046696C6C46726F6D427974657300476574427974657300466F726D6174004F626A6563740053706C6974005765616B506F696E74006765745F53746172740073746172740053797374656D2E5465787400770069780041727261790069790000032C00000000002B62F9B32B2F1E4EADCDFA868546C061000420010108032000010520010111110520010111150407011208030701020507030808080320000805200101122D0520011D0508060002021D050805200101123104200101020607031D050202032000020320000A0420001D05060002081D05080B07071D051D0508020208020500011D050806200201124D08052002010A05042001010A0907041D0E12080212080320000E0620011D0E1D03040001080E050702123D0E052001123D0E0307010D0520010D1229040701122908B77A5C561934E0890306122902060204000012080720020112291229052001011235060001120811390320000D042000122904080012080328000204280012290801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000701000000002B010002000000020054020D4973427974654F7264657265640054080B4D61784279746553697A6514000000000000000000001135305A00000000020000006F0000000C2D00000C0F0000525344537EE559BCA5981A45AA5875C930563E2F01000000443A5C4E65744658446576335C496E7465726D6564696174655C73756974657372635C7765616B6C696E652E637370726F6A5F5F313739383234393030375C6F626A635C616D6436345C5765616B4C696E652E70646200A32D00000000000000000000BD2D0000002000000000000000000000000000000000000000000000AF2D0000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C000000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001000000018000080000000000000000000000000000001000100000030000080000000000000000000000000000001000000000048000000584000004C02000000000000000000004C0234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100000000000000000000000000000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004AC010000010053007400720069006E006700460069006C00650049006E0066006F0000008801000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000030002E0030002E0030002E00300000003A000D00010049006E007400650072006E0061006C004E0061006D00650000005700650061006B004C0069006E0065002E0064006C006C00000000002800020001004C006500670061006C0043006F00700079007200690067006800740000002000000042000D0001004F0072006900670069006E0061006C00460069006C0065006E0061006D00650000005700650061006B004C0069006E0065002E0064006C006C0000000000340008000100500072006F006400750063007400560065007200730069006F006E00000030002E0030002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000030002E0030002E0030002E0030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C000000D03D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-with permission_set = safe
-go
-create assembly weakcircle from
-0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103001235305A0000000000000000E00022200B013000000E000000060000000000006A2C0000002000000040000000000010002000000002000004000000000000000600000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000152C00004F00000000400000B002000000000000000000000000000000000000006000000C000000882B00001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000700C000000200000000E000000020000000000000000000000000000200000602E72737263000000B0020000004000000004000000100000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001400000000000000000000000000004000004200000000000000000000000000000000492C000000000000480000000200050068230000200800000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000133001000C00000001000011001773040000060A2B00062A133001000C0000000200001100027B030000040A2B00062AF202730500000A7D0100000402167D0300000402280600000A0000027B01000004166F0700000A00027B01000004166F0800000A0002167D020000042A8A02730500000A7D0100000402167D0300000402280600000A000002177D030000042AE60002730500000A7D01000004027B01000004036F0900000A0002036F0A00000A7D020000040203176F0B00000A16280C00000A7D030000042AA600027B01000004036F0D00000A0003027B020000046F0E00000A0003027B030000046F0F00000A002A13300300680000000300001100036F1000000A0B072C0A0002177D030000042B52036F1100000A1F0C6AFE0116FE010C082C06731200000A7A036F1300000A0A027B010000040616281400000A6F0700000A00027B01000004061A281400000A6F0800000A0002061E281400000A7D020000042A13300400A60000000400001100027B030000040D092C1C00036F1000000A130411042C05388800000000036F1500000A002B7E1F0C8D120000010A027B010000046F1600000A281700000A0B0706166F1800000A00027B010000046F1900000A281700000A0B07061A6F1800000A00027B02000004281700000A0B07061E6F1800000A00160C2B1403086A0608916F1A00000A00081305110517580C08068E69FE04130611062DE003086A6F1B00000A002A0000133005006E00000005000011000F00281C00000A178D1400000125161F2C9D6F1D00000A0A068E6919FE0116FE010C082C06731200000A7A73030000060B077B0100000406169A281E00000A6F0700000A00077B0100000406179A281E00000A6F0800000A000706189A281E00000A7D02000004070D2B00092A000013300200420000000600001100731F00000A0A06027B010000046F2000000A6F2100000A260672010000706F2100000A2606027C02000004282200000A6F2100000A26066F2000000A0B2B00072A0000133001000C0000000700001100027B010000040A2B00062A133001000C0000000800001100027B020000040A2B00062A42534A4201000100000000000C00000076322E302E35303732370000000005006C00000060030000237E0000CC030000E002000023537472696E677300000000AC0600000800000023555300B4060000100000002347554944000000C40600005C01000023426C6F6200000000000000020000015717A2010900000000FA013300160000010000001600000002000000030000000C0000000600000002000000220000000400000008000000010000000400000004000000010000000300000000003F010100000000000600B9002B020600D9002B020600890018020F004B0200000A00AE02F7010A009D00F7010600B50281010A0068005A020A000601F7010E00C20200000600B0011C000600CB011C000A0083025A020A0017015A020600BD01CC020600EA0181010600920181010600F70081010600DA0281010600AB01810106002301810106000D008101000000001300000000000100010001201000720000001D00010001000100E301B80001005D00BC0001006801BF0050200000000096084E01C2000100682000000000E6095D01480001008020000000008618120206000100BD2000000000861812023C000100E02000000000E60158001F0002001A2100000000E60183003600030044210000000086008C02C7000400B8210000000086007902C70005006C220000000096007D00CD000600E82200000000C60021018A0007003823000000008608D801D40007005023000000008608A3022500070000000100570100000100160200000100D802000001004A00000001004A00000001004A000200210002002500090012020100110012020600190012020A0031001202100051001202060039001202060051002C000100510038000100510058001F0059000100250059006F022900810088012F00510083003600610083000100610083003C0069005D01480069002A014C008900120206006900FC00500081000B00550069007001060051002600250081009A0268009900A4016E00510032002500690078017500690035017B007100FC008A00A900BC028E00B1007D009500790012020600390021018A0079006100A000B10021018A002E000B00EB002E001300F4002E001B001301430023001C0116001B0041005C0080009A00A600AB000200010000007301D90000006901DE000000DC01E2000000A702E70002000100030002000200050002000B00070002000C00090004800000000000000000000000000000000072000000020000000000000000000000AF004F0000000000020000000000000000000000AF003E00000000000000000000000000000000000000C2020000000000000052656164496E74333200546F496E743332003C4D6F64756C653E0053797374656D2E494F006765745F58007365745F58006765745F59007365745F590053797374656D2E446174610064617461006D73636F726C696200526561640072616400417070656E6400494E756C6C61626C65005765616B436972636C650050617273650057726974650044656275676761626C654174747269627574650053716C55736572446566696E65645479706541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650042797465006765745F56616C7565004942696E61727953657269616C697A650053716C537472696E6700546F537472696E67006765745F4C656E677468005365744C656E677468005765616B436972636C652E646C6C006765745F4E756C6C00664E756C6C006765745F49734E756C6C006649734E756C6C005365744E756C6C007365745F4974656D0053797374656D00546F426F6F6C65616E00417267756D656E74457863657074696F6E00436F7079546F00436861720042696E61727952656164657200537472696E674275696C6465720042696E617279577269746572006765745F43656E7465720063656E74657200426974436F6E766572746572004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E446174612E53716C5479706573005265616442797465730046696C6C42797465730053716C42797465730046696C6C46726F6D4279746573004765744279746573006765745F52616469757300466F726D6174004F626A6563740053706C6974005765616B506F696E740053797374656D2E5465787400770041727261790000032C000000000032731D069C04DC4C944D50557785DC8F0004200101080320000105200101111105200101111504070112080307010205200101122D032000080520011D0508060002021D050805200101123104200101020607031D050202032000020320000A0420001D05060002081D05080B07071D051D0508020208020500011D050806200201124D08052002010A05042001010A0907041D0E12080212080320000E0620011D0E1D03040001080E050702123D0E052001123D0E04070112290307010808B77A5C561934E0890306122902060802060204000012080520010112350600011208113904200012290408001208032800020428001229032800080801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000701000000003C010002000000030054020D4973427974654F7264657265640054080B4D61784279746553697A650E00000054020D497346697865644C656E67746801000000000000001235305A000000000200000071000000A42B0000A40D000052534453F99C212E38B4B14980C9189A0F4C0A6901000000443A5C4E65744658446576335C496E7465726D6564696174655C73756974657372635C7765616B636972636C652E637370726F6A5F5F36393733363431375C6F626A635C616D6436345C5765616B436972636C652E706462003D2C00000000000000000000572C0000002000000000000000000000000000000000000000000000492C0000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000540200000000000000000000540234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100000000000000000000000000000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004B4010000010053007400720069006E006700460069006C00650049006E0066006F0000009001000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000030002E0030002E0030002E00300000003E000F00010049006E007400650072006E0061006C004E0061006D00650000005700650061006B0043006900720063006C0065002E0064006C006C00000000002800020001004C006500670061006C0043006F00700079007200690067006800740000002000000046000F0001004F0072006900670069006E0061006C00460069006C0065006E0061006D00650000005700650061006B0043006900720063006C0065002E0064006C006C0000000000340008000100500072006F006400750063007400560065007200730069006F006E00000030002E0030002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000030002E0030002E0030002E003000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C0000006C3C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-with permission_set = safe
-go
-
-create type Point external name shapes.[Point]
-create type Line external name shapes.[Line]
-create type Circle external name circle.[Circle]
-create type Address external name address.[Address]
-create type WeakPoint external name weakpoint.[WeakPoint]
-create type WeakLine external name weakline.[WeakLine]
-go
-
-create type CustomerAddress as table( name nvarchar(30) NOT NULL, addr Address NULL )
-go
-
-create table cities (name sysname,location Point)
-create table lines(ids int null, pos Line null)
-create table customers(name nvarchar(30), address Address)
-create table circles(num int, def Circle)
-create table lines_weak(ids int, pos WeakLine)
-go
-
-insert into cities values('redmond',convert(Point,'3,4'))
-insert into cities values('bellevue',convert(Point,'6,8'))
-insert into cities values('seattle',convert(Point,'10,11'))
-insert into cities values('portland',convert(Point,'20,15'))
-insert into cities values('LA',convert(Point,'3,4'))
-insert into cities values('SFO',convert(Point,'6,8'))
-insert into cities values('beaverton',convert(Point,'10,11'))
-insert into cities values('new york',convert(Point,'20,15'))
-insert into cities values('yukon',convert(Point,'20,25'))
-
-insert into lines values (1, CONVERT(Line,'1,2,3,4'))
-insert into lines values (2, CONVERT(Line,'3,4,5,6'))
-insert into lines values (3, CONVERT(Line,'11,23,15,32'))
-insert into lines values (4, CONVERT(Line,'444,555,245,634'))
-insert into lines values (5, CONVERT(Line,'1,2,3,4'))
-insert into lines values (6, CONVERT(Line,'3,4,5,6'))
-insert into lines values (7, CONVERT(Line,'11,23,15,32'))
-insert into lines values (8, CONVERT(Line,'444,555,245,634'))
-
-insert into customers values('first', convert(Address, 'Address 1 | Address 2'))
-insert into customers values('second', convert(Address, '123 Park Lane | New York'))
-insert into customers values('third', convert(Address, '21 Forest grove | Portland'))
-insert into customers values('fourth', convert(Address, '34 Lake Blvd | Seattle'))
-insert into customers values('fifth', convert(Address, 'A2 Meadows | Bellevue'))
-
-insert into circles values (1, CONVERT(Circle,'1,2,3'))
-insert into circles values (2, CONVERT(Circle,'3,4,5'))
-insert into circles values (3, CONVERT(Circle,'11,23,32'))
-insert into circles values (4, CONVERT(Circle,'444,555,634'))
-insert into circles values (5, CONVERT(Circle,'1,2,3'))
-insert into circles values (6, CONVERT(Circle,'3,4,5'))
-insert into circles values (7, CONVERT(Circle,'11,23,32'))
-insert into circles values (8, CONVERT(Circle,'444,245,634'))
-
-insert into lines_weak values (1, CONVERT(WeakLine,'1,2,3,4'))
-insert into lines_weak values (2, CONVERT(WeakLine,'3,4,5,6'))
-insert into lines_weak values (3, CONVERT(WeakLine,'11,23,15,32'))
-insert into lines_weak values (4, CONVERT(WeakLine,'444,555,245,634'))
-insert into lines_weak values (5, CONVERT(WeakLine,'1,2,3,4'))
-insert into lines_weak values (6, CONVERT(WeakLine,'3,4,5,6'))
-insert into lines_weak values (7, CONVERT(WeakLine,'11,23,15,32'))
-insert into lines_weak values (8, CONVERT(WeakLine,'444,555,245,634'))
-go
-
-create proc vicinity @boundary Point output
-as
-select name, location from cities where location.Distance() < @boundary.Distance()
-go
-
-create proc sp_insert_customer(@name nvarchar(30), @addr Address output)
-as
-insert into customers values (@name, @addr)
-go
-
-create proc sp_insert_customers ( @customers CustomerAddress READONLY )
-as
-insert into customers(name,address) select name,addr from @customers
-go
-
-create assembly Utf8String from 
-0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103000F35305A0000000000000000E00022200B0130000016000000060000000000006A350000002000000040000000000010002000000002000004000000000000000600000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000173500004F00000000400000B002000000000000000000000000000000000000006000000C000000883400001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E7465787400000070150000002000000016000000020000000000000000000000000000200000602E72737263000000B0020000004000000004000000180000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001C000000000000000000000000000040000042000000000000000000000000000000004B350000000000004800000002000500C0250000C80E00000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000133001002500000001000011000F00280600000A0A062C0828160000060B2B0F0F00280700000A73130000060B2B00072A000000133003006D00000002000011000228150000060A062C087E0800000A0B2B58027B0200000414FE030C082C0E027B02000004280900000A0B2B3D027B0100000414FE030D092C250002280A00000A027B010000046F0B00000A7D02000004027B02000004730C00000A0B2B0B7201000070730D00000A7A072A000000133002003500000003000011000F01280E00000A0A062C120002147D0200000402147D01000004002B1600020F01280F00000A7D0200000402147D01000004002A000000133003005F00000004000011000228150000060A062C04140B2B4E027B0100000414FE030C082C09027B010000040B2B38027B0200000414FE030D092C200002280A00000A027B020000046F1000000A7D01000004027B010000040B2B0B724F000070730D00000A7A072A00133001002300000005000011000228150000060A062C087E1100000A0B2B0E026F1200000A731300000A0B2B00072A00133003004D00000006000011000228150000060B072C087E1100000A0C2B38160A040D092C040617600A05130411042C040618600A0E04130511052C05061F10600A026F1200000A036F1400000A06731500000A0C2B00082A000000133006003F000000070000110003281600000A0A0614FE010B072C1F281700000A72B5000070178D07000001251603A2281800000A731900000A7A020604050E0428060000060C2B00082A001330050014000000080000110002281A00000A03040528060000060A2B00062A133002001000000003000011000203281200000616FE010A2B00062A133002000D000000030000110002036F1B00000A0A2B00062A000000133002001000000003000011000203280A00000616FE010A2B00062A1330020010000000030000110002036F1200000616FE040A2B00062A1330020010000000030000110002036F1200000616FE020A2B00062A133006006200000009000011000314280A0000060A062C04170B2B500228150000060C082C12036F150000060D092C04160B2B38150B2B34036F15000006130411042C04170B2B240204050E040E052806000006130512050304050E040E056F06000006281C00000A0B2B00072A000013300600410000000A0000110004281600000A0A0614FE010B072C1F281700000A72B5000070178D07000001251604A2281800000A731900000A7A020306050E040E05280E0000060C2B00082A00000013300600160000000B000011000203281A00000A04050E04280E0000060A2B00062A0000133001001F0000000C000011000228150000060A062C04160B2B0E026F1200000A6F1D00000A0B2B00072A0013300200710000000D000011000314FE010B072C04170C2B620375020000020A0614280A0000060D092C0B72ED000070731900000A7A022815000006130411042C1500066F15000006130511052C04160C2B28150C2B24066F15000006130611062C04170C2B14026F1200000A066F1200000A6F1E00000A0C2B00082A4202281F00000A000002037D010000042A4202281F00000A000002037D020000042A00133002001A0000000300001100027B010000042D0B027B0200000414FE012B01160A2B00062A0000133001000E0000000E000011001473130000060A060B2B00072A2602281F00000A00002A13300200430000000F000011000228150000062D03162B0117D20A03066F2000000A000617FE010C082C022B210228020000060D1203280F00000A0B03078E696F2100000A0003076F2200000A002A0013300300310000001000001100036F2300000A0A06175F16FE020C082C0A0002147D020000042B14036F2400000A0B0203076F2500000A7D020000042A00000042534A4201000100000000000C00000076322E302E35303732370000000005006C0000000C050000237E0000780500008804000023537472696E677300000000000A00004801000023555300480B0000100000002347554944000000580B00007003000023426C6F6200000000000000020000015717A2010900000000FA01330016000001000000180000000200000002000000190000002900000003000000250000000700000010000000010000000300000004000000010000000200000000007E0201000000000006006F01960306008F01960306003F0183030F00B60300000A00300446030A005301460306003704A1020A007A00C50306008400A1020A00C60146030A000102C5030A006304C5030A002C0146030A00500046030A004A00460306000A03C3020A001E04C5030600390326000600160326000600D7014A040600D802A10206002102A10206002303A1020600EE02A102000000001400000000000100010001201000E00161031D00010001000100F60108010100F6030B01502000000000960020010F0101008420000000008608DA03160102000021000000008608E8031B010200442100000000C600150220000300B021000000008600FF0121010300E0210000000081005F02260103003C22000000008600CE00300107008822000000008600580439010B00A82200000000C6001704A5000E00C4220000000096086D0441010F00E022000000009608790441011100FC22000000009608B702410113001823000000009608A802410115003423000000008100430249011700A423000000008600BA0054011C00F4230000000086009C005E012100182400000000C6006E0078002500442400000000E601000367012500C1240000000086187D0348002600D2240000000086187D0342002700E42400000000E60996021C0028000C250000000096088D026C01280026250000000086187D0306002800302500000000E601260171012800802500000000E601450077012900000001000B0200000100C001000001000D01000002001501000003005F00000004003302000001009000000002001501000003005F00000004003302000001001501000002005F00000003003302000001003F0200000100EB0100000200330300000100EB0100000200330300000100EB0100000200330300000100EB01000002003303000001003303000002000D01000003001501000004005F00000005003302000001003303000002009000000003001501000004005F00000005003302000001003303000002001501000003005F00000004003302000001003F0200000100C00100000100110400000100560400000100810302002100020025000200290009007D03010011007D03060019007D030A0031007D03100069007D030600590096021C005900B601200061009C022C0061003E043000A1000B003700A10008043C0061007D034200A9007D034800610096021C006100B6015100A1001E025D0059009C02690039001502200059007D03480081001D00780059007D037C008100A4008C008100E5009200B10030049700C1007D0348008100FA00920039001704A50059000003B40039006E007800B1000003D50039007D03060091002601EA009100260101009100260142009900AD01F5009900010078009900FE03F9002E000B008B012E00130094012E001B00B30143002300410380002B00BC01E0002B00040300012B002903160024004D00560063006D008400A000AA00BA00C100C500CA00DA00E100EF00020001000000EC037D0100009A02820100009C02860102000200030001000300030002001500050002001600070004800000030002000100010000000000000028020000020000000000000000000000FF003C0000000000020000000000000000000000FF0030000000000000000052656164496E743332006765745F55544638003C4D6F64756C653E006765745F4C4349440053797374656D2E494F0053797374656D2E44617461006D73636F726C696200526561640053797374656D446174614163636573734B696E640069676E6F72654E6F6E53706163650047657448617368436F646500494E756C6C61626C650049436F6D70617261626C650063756C747572654E616D6500436F6D7061726500437265617465537065636966696343756C7475726500436F6D706172655573696E6743756C7475726500476574536F72744B65795573696E6743756C74757265006765745F496E76617269616E7443756C74757265006765745F43757272656E7443756C747572650063756C747572650069676E6F7265436173650050617273650057726974650053716C4D6574686F644174747269627574650044656275676761626C654174747269627574650053716C55736572446566696E65645479706541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C697479417474726962757465005265616442797465006765745F56616C75650076616C7565004942696E61727953657269616C697A6500456E636F64696E670055746638537472696E670075746638537472696E67006D5F537472696E6700546F53716C537472696E670073716C537472696E6700546F537472696E6700476574537472696E670075746638737472696E670069676E6F72655769647468006F626A00436F6D706172655573696E6743756C74757265496E7465726E616C00476574536F72744B65795573696E6743756C74757265496E7465726E616C0075746638737472696E672E646C6C006765745F4E756C6C006765745F49734E756C6C0053797374656D006F705F477265617465725468616E006F705F4C6573735468616E0053797374656D2E476C6F62616C697A6174696F6E004E6F74537570706F72746564457863657074696F6E00417267756D656E74457863657074696F6E00436F6D70617265546F0043756C74757265496E666F0042696E6172795265616465720049466F726D617450726F7669646572006F746865720042696E617279577269746572004D6963726F736F66742E53716C5365727665722E536572766572004D6963726F736F66742E53616D706C65732E53716C536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E446174612E53716C5479706573006765745F557466384279746573007365745F557466384279746573006D5F42797465730052656164427974657300476574427974657300627974657300457175616C730053716C436F6D706172654F7074696F6E7300466F726D6174004F626A656374006F705F496D706C696369740053797374656D2E54657874007700476574536F72744B65790053716C42696E617279006F705F457175616C697479006F705F496E657175616C6974790000004D630061006E006E006F0074002000720065007400750072006E00200062007900740065007300200066006F007200200065006D00700074007900200069006E007300740061006E0063006500006564006F006E00740020006B006E006F007700200068006F007700200074006F002000720065007400750072006E00200073007400720069006E0067002000660072006F006D00200065006D00700074007900200069006E007300740061006E00630065000037430075006C00740075007200650020007B0030007D0020006E006F00740020007200650063006F0067006E0069007A00650064002E000057740068006500200061007200670075006D0065006E007400200074006F00200063006F006D00700061007200650020006900730020006E006F007400200061002000550074006600380053007400720069006E006700000000000EC59433DD025D47A6AE3D09E458D39500042001010803200001052001011111052001011115050702021208032000020320000E07070402113102020306113106000111311D0504000012510520011D050E052001011D05042001010E030701020420001D05060704020E02020520010E1D0505070202112D0306112D0A0706114502112D02020203200008072003010E081145070703124102112D05000112410E04000012410800030E125D0E1D1C040701112D042001021C0907060208020202112D05200108112D060703124102080307010804070202080A07071208020802020202042001080E06070212081208080704051D050211310420010105050703050802032000050520011D050808B77A5C561934E08902060E03061D050600011208112D0420001131052001011131042000112D092004112D1241020202082004112D0E020202072003112D02020207000202120812080A200508120812410202020920050812080E020202082004081208020202042001081C040000120805200101124905200101124D04280011310328000204080012080801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F77730108010007010000000081460100040054020F497344657465726D696E697374696301540209497350726563697365015455794D6963726F736F66742E53716C5365727665722E5365727665722E446174614163636573734B696E642C2053797374656D2E446174612C2056657273696F6E3D322E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038390A446174614163636573730000000054557F4D6963726F736F66742E53716C5365727665722E5365727665722E53797374656D446174614163636573734B696E642C2053797374656D2E446174612C2056657273696F6E3D322E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038391053797374656D4461746141636365737300000000240100020054020F497344657465726D696E69737469630154020949735072656369736501170100010054020F497344657465726D696E6973746963002B010002000000020054020D4973427974654F7264657265640154080B4D61784279746553697A65401F0000000000000000000F35305A000000000200000073000000A4340000A416000052534453F3CBC33915671D4B9EE0AEAF82371B5101000000443A5C4E65744658446576335C496E7465726D6564696174655C73756974657372635C75746638737472696E672E637370726F6A5F5F313733303533303137335C6F626A635C616D6436345C75746638737472696E672E706462003F3500000000000000000000593500000020000000000000000000000000000000000000000000004B350000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C000000000000FF250020001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000540200000000000000000000540234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100020003000100010002000300010001003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004B4010000010053007400720069006E006700460069006C00650049006E0066006F0000009001000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000033002E0032002E0031002E00310000003E000F00010049006E007400650072006E0061006C004E0061006D0065000000750074006600380073007400720069006E0067002E0064006C006C00000000002800020001004C006500670061006C0043006F00700079007200690067006800740000002000000046000F0001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000750074006600380073007400720069006E0067002E0064006C006C0000000000340008000100500072006F006400750063007400560065007200730069006F006E00000033002E0032002E0031002E003100000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000033002E0032002E0031002E003100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C0000006C3500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
-with permission_set = safe
-go
-
-create type Utf8String external name Utf8String.[Microsoft.Samples.SqlServer.Utf8String]
-go
-
-create table Testtable (udtstring Utf8String Primary Key)
-go
-
-insert into Testtable (udtstring) values (Convert(Utf8String, 'this'))
-insert into Testtable (udtstring) values (Convert(Utf8String, 'is'))
-insert into Testtable (udtstring) values (Convert(Utf8String, 'a'))
-insert into Testtable (udtstring) values (Convert(Utf8String, 'test'))
-go
-
-create procedure UDTTest @value Utf8String OUTPUT AS select @value = Convert(Utf8String, 'this is an outparam test');
-go
-
-create table TesttableNull (udtstring Utf8String null)
-go
-
-insert into TesttableNull (udtstring) values (Convert(Utf8String, 'this'))
-insert into TesttableNull (udtstring) values (Convert(Utf8String, 'is'))
-insert into TesttableNull (udtstring) values (Convert(Utf8String, 'a'))
-insert into TesttableNull (udtstring) values (Convert(Utf8String, 'test'))
-go
-
-PRINT N'Creation of UdtTestDb database complete.'
-go
-
-
-PRINT N'============================================================================='
-GO
-PRINT N'Finished executing Script'
-GO
-PRINT N'============================================================================='
-GO
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/Configurations.props b/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/Configurations.props
deleted file mode 100644 (file)
index 69f0b7d..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0-Unix;
-      netstandard2.0-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/IMonitorLoader.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/IMonitorLoader.cs
deleted file mode 100644 (file)
index 5a9dc16..0000000
+++ /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.Collections.Generic;
-using Monitoring;
-
-namespace Monitoring
-{
-    public interface IMonitorLoader
-    {
-        string HostMachine { get; set; }
-        string AssemblyPath { get; set; }
-        string TestName { get; set; }
-        bool Enabled { get; set; }
-
-        void Action(MonitorLoaderUtils.MonitorAction monitoraction);
-        void AddPerfData(MonitorMetrics data);
-        Dictionary<string, MonitorMetrics> GetPerfData();
-    }
-
-    public class MonitorLoaderUtils
-    {
-        public enum MonitorAction
-        {
-            Initialize,
-            Start,
-            Stop,
-            DoNothing
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/IMonitorLoader.csproj b/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/IMonitorLoader.csproj
deleted file mode 100644 (file)
index 7ca0bad..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <RootNamespace>Monitoring</RootNamespace>
-    <AssemblyName>Monitoring</AssemblyName>
-    <Configurations>netstandard2.0-Unix-Debug;netstandard2.0-Unix-Release;netstandard2.0-Windows_NT-Debug;netstandard2.0-Windows_NT-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="IMonitorLoader.cs" />
-    <Compile Include="MonitorMetrics.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/MonitorMetrics.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/IMonitorLoader/MonitorMetrics.cs
deleted file mode 100644 (file)
index ed37544..0000000
+++ /dev/null
@@ -1,96 +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;
-
-namespace Monitoring
-{
-    public class MonitorMetrics
-    {
-        private string _name;
-        private string _strValue;
-        private string _unit;
-        private bool _isPrimary;
-        private bool _isHigherBetter;
-        private double _dblValue;
-        private long _lngValue;
-        private char _valueType; // D=double, L=long, S=String
-
-        public MonitorMetrics(string name, string value, string unit, bool HigherIsBetter, bool Primary)
-        {
-            _name = name;
-            _strValue = value;
-            _unit = unit;
-            _valueType = 'S';
-            _isHigherBetter = HigherIsBetter;
-            _isPrimary = Primary;
-        }
-
-        public MonitorMetrics(string name, double value, string unit, bool HigherIsBetter, bool Primary)
-        {
-            _name = name;
-            _dblValue = value;
-            _unit = unit;
-            _valueType = 'D';
-            _isHigherBetter = HigherIsBetter;
-            _isPrimary = Primary;
-        }
-
-        public MonitorMetrics(string name, long value, string unit, bool HigherIsBetter, bool Primary)
-        {
-            _name = name;
-            _lngValue = value;
-            _unit = unit;
-            _valueType = 'L';
-            _isHigherBetter = HigherIsBetter;
-            _isPrimary = Primary;
-        }
-
-        public string GetName()
-        {
-            return _name;
-        }
-
-        public string GetUnit()
-        {
-            return _unit;
-        }
-
-        public bool GetPrimary()
-        {
-            return _isPrimary;
-        }
-
-        public bool GetHigherIsBetter()
-        {
-            return _isHigherBetter;
-        }
-
-        public char GetValueType()
-        {
-            return _valueType;
-        }
-
-        public string GetStringValue()
-        {
-            if (_valueType == 'S')
-                return _strValue;
-            throw new Exception("Value is not a string");
-        }
-
-        public double GetDoubleValue()
-        {
-            if (_valueType == 'D')
-                return _dblValue;
-            throw new Exception("Value is not a double");
-        }
-
-        public long GetLongValue()
-        {
-            if (_valueType == 'L')
-                return _lngValue;
-            throw new Exception("Value is not a long");
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/Configurations.props b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/Configurations.props
deleted file mode 100644 (file)
index f350311..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      $(NetCoreAppCurrent)-Unix;
-      $(NetCoreAppCurrent)-Windows_NT;
-      $(NetFrameworkCurrent)-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/FilteredDefaultTraceListener.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/FilteredDefaultTraceListener.cs
deleted file mode 100644 (file)
index 3311abe..0000000
+++ /dev/null
@@ -1,211 +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.Reflection;
-using System.Text.RegularExpressions;
-using System.Threading;
-
-namespace Stress.Data.SqlClient
-{
-    /// <summary>
-    /// A DefaultTraceListener that can filter out given asserts
-    /// </summary>
-    internal class FilteredDefaultTraceListener : DefaultTraceListener
-    {
-        private static readonly Assembly s_systemDataAssembly = typeof(System.Data.SqlClient.SqlConnection).GetTypeInfo().Assembly;
-        private const RegexOptions AssertMessageRegexOptions = RegexOptions.Singleline | RegexOptions.CultureInvariant;
-
-        private enum MatchType : byte
-        {
-            Exact,
-            Regex,
-        }
-
-        private enum HandlingOption : byte
-        {
-            CovertToException,
-            WriteToConsole,
-        }
-
-        /// <summary>
-        /// Represents a single assert to filter out
-        /// </summary>
-        private struct FilteredAssert
-        {
-            public FilteredAssert(string messageOrRegex, int bugNumber, MatchType matchType, HandlingOption assertHandlingOption, params string[] stackFrames)
-            {
-                if (matchType == MatchType.Exact)
-                {
-                    Message = messageOrRegex;
-                    MessageRegex = null;
-                }
-                else
-                {
-                    Message = null;
-                    MessageRegex = new Regex(messageOrRegex, AssertMessageRegexOptions);
-                }
-
-
-                StackFrames = stackFrames;
-                BugNumber = bugNumber;
-                Handler = assertHandlingOption;
-            }
-
-            /// <summary>
-            /// The assert's message (NOTE: MessageRegex must be null if this is specified)
-            /// </summary>
-            public string Message;
-            /// <summary>
-            /// A regex that matches the assert's message (NOTE: Message must be null if this is specified)
-            /// </summary>
-            public Regex MessageRegex;
-            /// <summary>
-            /// The most recent frames on the stack when the assert was hit (i.e. 0 is most recent, 1 is next, etc.). Null if stack should not be checked.
-            /// </summary>
-            public string[] StackFrames;
-            /// <summary>
-            /// Product bug to fix the assert
-            /// </summary>
-            public int BugNumber;
-            /// <summary>
-            /// How the assert will be handled once it is matched
-            /// </summary>
-            /// <remarks>
-            /// In most cases this can be set to WriteToConsole - typically the assert is either invalid or there will be an exception thrown by the product code anyway.
-            /// However, in the case where this is state corruption AND the product code has no exception in place, this will need to be set to CovertToException to prevent further corruption\asserts
-            /// </remarks>
-            public HandlingOption Handler;
-        }
-
-        private static readonly FilteredAssert[] s_assertsToFilter = new FilteredAssert[] {
-            new FilteredAssert("TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!", 433324, MatchType.Exact, HandlingOption.WriteToConsole,
-                "System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning",
-                "System.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning",
-                "System.Data.SqlClient.TdsParserStateObject.ReadAsyncCallbackCaptureException"),
-        };
-
-        public FilteredDefaultTraceListener(DefaultTraceListener listenerToClone) : base()
-        {
-            base.Filter = listenerToClone.Filter;
-            base.IndentLevel = listenerToClone.IndentLevel;
-            base.IndentSize = listenerToClone.IndentSize;
-            base.TraceOutputOptions = listenerToClone.TraceOutputOptions;
-        }
-
-        public override void Fail(string message)
-        {
-            Fail(message, null);
-        }
-
-        public override void Fail(string message, string detailMessage)
-        {
-            FilteredAssert? foundAssert = FindAssertInList(message);
-            if (!foundAssert.HasValue)
-            {
-                // Don't filter this assert - pass it down to the underlying DefaultTraceListener which will show the UI, break into the debugger, etc.
-                base.Fail(message, detailMessage);
-            }
-            else
-            {
-                // Assert is to be filtered, either convert to an exception or a message
-                var assert = foundAssert.Value;
-                if (assert.Handler == HandlingOption.CovertToException)
-                {
-                    throw new FailedAssertException(message, assert.BugNumber);
-                }
-                else if (assert.Handler == HandlingOption.WriteToConsole)
-                {
-                    Console.WriteLine("Hit known assert, Bug {0}: {1}", assert.BugNumber, message);
-                }
-            }
-        }
-
-        private FilteredAssert? FindAssertInList(string message)
-        {
-            StackTrace actualCallstack = null;
-            foreach (var assert in s_assertsToFilter)
-            {
-                if (((assert.Message != null) && (assert.Message == message)) || ((assert.MessageRegex != null) && (assert.MessageRegex.IsMatch(message))))
-                {
-                    if (assert.StackFrames != null)
-                    {
-                        // Skipping four frames:
-                        // Stress.Data.SqlClient.FilteredDefaultTraceListener.FindAssertInList
-                        // Stress.Data.SqlClient.FilteredDefaultTraceListener.Fail (This may be in the stack twice due to the overloads calling each other)
-                        // System.Diagnostics.TraceInternal.Fail
-                        // System.Diagnostics.Debug.Assert
-                        if (actualCallstack == null)
-                        {
-                            actualCallstack = new StackTrace(e: new InvalidOperationException(), fNeedFileInfo: false);
-                        }
-
-                        StackFrame[] frames = actualCallstack.GetFrames();
-                        if (frames.Length >= assert.StackFrames.Length)
-                        {
-                            int actualStackFrameCounter = 0;
-                            bool foundMatch = true;
-                            foreach (var expectedStack in assert.StackFrames)
-                            {
-                                // Get the method information for the next stack which came from System.Data.dll
-                                MethodBase actualStackMethod;
-                                do
-                                {
-                                    actualStackMethod = frames[actualStackFrameCounter].GetMethod();
-                                    actualStackFrameCounter++;
-                                } while (((actualStackMethod.DeclaringType == null) || (actualStackMethod.DeclaringType.GetTypeInfo().Assembly != s_systemDataAssembly)) && (actualStackFrameCounter < frames.Length));
-
-                                if ((actualStackFrameCounter > frames.Length) || (string.Format("{0}.{1}", actualStackMethod.DeclaringType.FullName, actualStackMethod.Name) != expectedStack))
-                                {
-                                    // Ran out of actual frames while there were still expected frames or the current frames didn't match
-                                    foundMatch = false;
-                                    break;
-                                }
-                            }
-
-                            // Message and all frames matched
-                            if (foundMatch)
-                            {
-                                return assert;
-                            }
-                        }
-                    }
-                    else
-                    {
-                        // Messages match, and there are no frames to verify
-                        return assert;
-                    }
-                }
-            }
-
-            // Fall through - didn't find the assert
-            return null;
-        }
-    }
-
-    internal class FailedAssertException : Exception
-    {
-        /// <summary>
-        /// Number of the bug that caused the assert to fire
-        /// </summary>
-        public int BugNumber { get; private set; }
-
-        /// <summary>
-        /// Creates an exception to represent hitting a known assert
-        /// </summary>
-        /// <param name="message">Message of the assert</param>
-        /// <param name="bugNumber">Number of the bug that caused the assert</param>
-        public FailedAssertException(string message, int bugNumber)
-            : base(message)
-        {
-            BugNumber = bugNumber;
-        }
-
-        public override string ToString()
-        {
-            return string.Format("{1}\r\nAssert caused by Bug {0}", BugNumber, base.ToString());
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/HostsFileManager.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/HostsFileManager.cs
deleted file mode 100644 (file)
index 17c6101..0000000
+++ /dev/null
@@ -1,483 +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;
-using System.Runtime.CompilerServices;
-using System.IO;
-using System.Net;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-
-namespace Microsoft.Test.Data.SqlClient
-{
-    /// <summary>
-    /// allows user to manipulate %windir%\system32\drivers\etc\hosts
-    /// the hosts file must be reverted if changed even if test application crashes, thus inherit from CriticalFinalizerObject. Make sure the instance is disposed after its use.
-    /// The last dispose call on the active instance reverts the hosts file.
-    ///
-    /// Usage:
-    /// using (var hostsFile = new HostsFileManager())
-    /// {
-    ///     // use the hostsFile methods to add/remove entries
-    ///     // simultaneous usage of HostsFileManager in two app domains or processes on the same machine is not allowed
-    /// }
-    /// </summary>
-    public sealed class HostsFileManager : IDisposable
-    {
-        // define global (machine-wide) lock instance
-        private static EventWaitHandle s_globalLock = new EventWaitHandle(true /* create as signalled */, EventResetMode.AutoReset, @"Global\HostsFileManagerLock");
-        private static bool s_globalLockTaken; // set when global (machine-wide) lock is in use
-
-        private static int s_localUsageRefCount;
-        private static object s_localLock = new object();
-
-        private static string s_hostsFilePath;
-        private static string s_backupPath;
-        private static bool s_hasBackup;
-        private static TextReader s_activeReader;
-        private static TextWriter s_activeWriter;
-        private static List<HostEntry> s_entriesCache;
-
-        private const string HostsFilePathUnderSystem32 = @"C:\Windows\System32\drivers\etc\hosts";
-        private const string HostsFilePathUnderLinux = "/etc/hosts";
-        private const string HostsFilePathUnderMacOS = "/private/etc/hosts";
-
-
-        private static void InitializeGlobal(ref bool mustRelease)
-        {
-            if (mustRelease)
-            {
-                // already initialized
-                return;
-            }
-
-            lock (s_localLock)
-            {
-                if (mustRelease)
-                {
-                    // check again under lock
-                    return;
-                }
-
-                if (s_localUsageRefCount > 0)
-                {
-                    // initialized by another thread
-                    ++s_localUsageRefCount;
-                    return;
-                }
-
-                // first call to initialize in this app domain
-                // note: simultanious use of HostsFileManager is currently supported only within single AppDomain scope
-
-                // non-critical initialization goes first
-                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
-                {
-                    s_hostsFilePath = HostsFilePathUnderSystem32;
-                }
-                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
-                {
-                    s_hostsFilePath = HostsFilePathUnderLinux;
-                }
-                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
-                {
-                    s_hostsFilePath = HostsFilePathUnderMacOS;
-                }
-
-                s_backupPath = Path.Combine(Path.GetTempPath(), string.Format("Hosts_{0}.bak", Guid.NewGuid().ToString("N")));
-
-                // try to get global lock
-                // note that once global lock is aquired, it must be released
-                try { }
-                finally
-                {
-                    if (s_globalLock.WaitOne(0))
-                    {
-                        s_globalLockTaken = true;
-                        mustRelease = true;
-                        ++s_localUsageRefCount; // increment ref count for the first thread using the manager
-                    }
-                }
-
-                if (!s_globalLockTaken)
-                {
-                    throw new InvalidOperationException("HostsFileManager cannot initialize because hosts file is in use by another instance of the manager in the same or a different process (concurrent access is not allowed)");
-                }
-
-                // locked now, take snapshot of hosts file and save it as a backup
-                File.Copy(s_hostsFilePath, s_backupPath);
-                s_hasBackup = true;
-
-                // load the current entries
-                InternalRefresh();
-            }
-        }
-
-        private static void TerminateGlobal(ref bool originalMustRelease)
-        {
-            if (!originalMustRelease)
-            {
-                // already disposed
-                return;
-            }
-
-            lock (s_localLock)
-            {
-                if (!originalMustRelease)
-                {
-                    // check again under lock
-                    return;
-                }
-
-                // not yet disposed, do it now
-                if (s_localUsageRefCount > 1)
-                {
-                    // still in use by another thread(s)
-                    --s_localUsageRefCount;
-                    return;
-                }
-
-                if (s_activeReader != null)
-                {
-                    s_activeReader.Dispose();
-                    s_activeReader = null;
-                }
-                if (s_activeWriter != null)
-                {
-                    s_activeWriter.Dispose();
-                    s_activeWriter = null;
-                }
-                bool deleteBackup = false;
-                if (s_hasBackup)
-                {
-                    // revert the hosts file
-                    File.Copy(s_backupPath, s_hostsFilePath, overwrite: true);
-                    s_hasBackup = false;
-                    deleteBackup = true;
-                }
-
-                // Note: if critical finalizer fails to revert the hosts file, the global lock might remain reset until the machine is rebooted.
-                // if this happens, Hosts file in unpredictable state so there is no point in running tests anyway
-                if (s_globalLockTaken)
-                {
-                    try { }
-                    finally
-                    {
-                        s_globalLock.Set();
-                        s_globalLockTaken = false;
-                        --s_localUsageRefCount; // decrement local ref count
-                        originalMustRelease = false;
-                    }
-                }
-
-                // now we can destroy the backup
-                if (deleteBackup)
-                {
-                    File.Delete(s_backupPath);
-                }
-            }
-        }
-
-        private bool _mustRelease;
-        private bool _disposed;
-
-        public HostsFileManager()
-        {
-            // lazy initialization
-            _mustRelease = false;
-            _disposed = false;
-        }
-
-        ~HostsFileManager()
-        {
-            Dispose(false);
-        }
-
-        public void Dispose()
-        {
-            Dispose(true);
-            GC.SuppressFinalize(this);
-        }
-
-        private void Dispose(bool disposing)
-        {
-            if (!_disposed)
-            {
-                _disposed = true;
-                TerminateGlobal(ref _mustRelease);
-            }
-        }
-
-        public class HostEntry
-        {
-            public HostEntry(string name, IPAddress address)
-            {
-                ValidateName(name);
-                ValidateAddress(address);
-
-                this.Name = name;
-                this.Address = address;
-            }
-
-            public readonly string Name;
-            public readonly IPAddress Address;
-        }
-
-        // helper methods
-
-        // must be called under lock(_localLock) from each public API that uses static fields
-        private void InitializeLocal()
-        {
-            if (_disposed)
-            {
-                throw new ObjectDisposedException(this.GetType().Name);
-            }
-
-            InitializeGlobal(ref _mustRelease);
-        }
-
-        private static readonly char[] s_whiteSpaceChars = new char[] { ' ', '\t' };
-
-        private static void ValidateName(string name)
-        {
-            if (string.IsNullOrEmpty(name) || name.IndexOfAny(s_whiteSpaceChars) >= 0)
-            {
-                throw new ArgumentException("name cannot be null or empty or have whitespace characters in it");
-            }
-        }
-
-        private static void ValidateAddress(IPAddress address)
-        {
-            ValidateNonNull(address, "address");
-
-            if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork &&
-                address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
-            {
-                throw new ArgumentException("only IPv4 or IPv6 addresses are allowed");
-            }
-        }
-
-        private static void ValidateNonNull<T>(T value, string argName) where T : class
-        {
-            if (value == null)
-            {
-                throw new ArgumentNullException(argName);
-            }
-        }
-
-        private static HostEntry TryParseLine(string line)
-        {
-            line = line.Trim();
-            if (line.StartsWith("#"))
-            {
-                // comment, ignore
-                return null;
-            }
-
-            string[] items = line.Split(s_whiteSpaceChars, StringSplitOptions.RemoveEmptyEntries);
-            if (items.Length == 0)
-            {
-                // empty or white-space only line - ignore
-                return null;
-            }
-
-            if (items.Length != 2)
-            {
-                Trace.WriteLine("Wrong entry in the hosts file (exactly two columns expected): \"" + line + "\"");
-                return null;
-            }
-
-            string name = items[1];
-            IPAddress address;
-            if (!IPAddress.TryParse(items[0], out address))
-            {
-                Trace.WriteLine("Wrong entry in the hosts file (cannot parse the IP address): \"" + line + "\"");
-                return null;
-            }
-
-            try
-            {
-                return new HostEntry(name, address);
-            }
-            catch (ArgumentException e)
-            {
-                Console.WriteLine("Wrong entry in the hosts file, cannot create host entry: " + e.Message);
-                return null;
-            }
-        }
-
-        private bool NameMatch(HostEntry entry, string name)
-        {
-            ValidateNonNull(entry, "entry");
-            ValidateName(name);
-
-            return string.Equals(entry.Name, name, StringComparison.OrdinalIgnoreCase);
-        }
-
-        // hosts file manipulation methods
-
-        // reloads the hosts file, must be called under lock(_localLock)
-        private static void InternalRefresh()
-        {
-            List<HostEntry> entries = new List<HostEntry>();
-
-            try
-            {
-                s_activeReader = new StreamReader(new FileStream(s_hostsFilePath, FileMode.Open));
-
-                string line;
-                while ((line = s_activeReader.ReadLine()) != null)
-                {
-                    HostEntry nextEntry = TryParseLine(line);
-                    if (nextEntry != null)
-                    {
-                        entries.Add(nextEntry);
-                    }
-                }
-            }
-            finally
-            {
-                if (s_activeReader != null)
-                {
-                    s_activeReader.Dispose();
-                    s_activeReader = null;
-                }
-            }
-
-            s_entriesCache = entries;
-        }
-
-        // reloads the hosts file, must be called while still under lock(_localLock)
-        private void InternalSave()
-        {
-            try
-            {
-                s_activeWriter = new StreamWriter(new FileStream(s_hostsFilePath, FileMode.Create));
-
-                foreach (HostEntry entry in s_entriesCache)
-                {
-                    s_activeWriter.WriteLine("  {0}  {1}", entry.Address, entry.Name);
-                }
-
-                s_activeWriter.Flush();
-            }
-            finally
-            {
-                if (s_activeWriter != null)
-                {
-                    s_activeWriter.Dispose();
-                    s_activeWriter = null;
-                }
-            }
-        }
-
-        public int RemoveAll(string name)
-        {
-            lock (s_localLock)
-            {
-                InitializeLocal();
-                ValidateName(name);
-
-                int removed = s_entriesCache.RemoveAll(entry => NameMatch(entry, name));
-
-                if (removed > 0)
-                {
-                    InternalSave();
-                }
-
-                return removed;
-            }
-        }
-
-        public IEnumerable<IPAddress> EnumerateAddresses(string name)
-        {
-            lock (s_localLock)
-            {
-                InitializeLocal();
-                ValidateName(name);
-
-                return from entry in s_entriesCache where NameMatch(entry, name) select entry.Address;
-            }
-        }
-
-        public void Add(string name, IPAddress address)
-        {
-            lock (s_localLock)
-            {
-                InitializeLocal();
-
-                HostEntry entry = new HostEntry(name, address); // c-tor validates the arguments
-                s_entriesCache.Add(entry);
-
-                InternalSave();
-            }
-        }
-
-        public void Add(HostEntry entry)
-        {
-            lock (s_localLock)
-            {
-                InitializeLocal();
-                ValidateNonNull(entry, "entry");
-
-                s_entriesCache.Add(entry);
-
-                InternalSave();
-            }
-        }
-
-        public void AddRange(string name, IEnumerable<IPAddress> addresses)
-        {
-            lock (s_localLock)
-            {
-                InitializeLocal();
-                ValidateName(name);
-                ValidateNonNull(addresses, "addresses");
-
-                foreach (IPAddress address in addresses)
-                {
-                    HostEntry entry = new HostEntry(name, address);
-
-                    s_entriesCache.Add(entry);
-                }
-
-                InternalSave();
-            }
-        }
-
-        public void AddRange(IEnumerable<HostEntry> entries)
-        {
-            lock (s_localLock)
-            {
-                InitializeLocal();
-                ValidateNonNull(entries, "entries");
-
-                foreach (HostEntry entry in entries)
-                {
-                    ValidateNonNull(entry, "entries element");
-
-                    s_entriesCache.Add(entry);
-                }
-
-                InternalSave();
-            }
-        }
-
-        public void Clear()
-        {
-            lock (s_localLock)
-            {
-                InitializeLocal();
-
-                s_entriesCache.Clear();
-
-                InternalSave();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/MultiSubnetFailoverSetup.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/MultiSubnetFailoverSetup.cs
deleted file mode 100644 (file)
index 3192962..0000000
+++ /dev/null
@@ -1,136 +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.Test.Data.SqlClient;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Stress.Data.SqlClient
-{
-    internal class MultiSubnetFailoverSetup
-    {
-        private HostsFileManager _hostsFile;
-
-        internal MultiSubnetFailoverSetup(SqlServerDataSource source)
-        {
-            this.Source = source;
-        }
-
-        internal string MultiSubnetFailoverHostNameForIntegratedSecurity { get; private set; }
-
-        private List<string> _multiSubnetFailoverHostNames;
-
-        internal string GetMultiSubnetFailoverHostName(Random rnd)
-        {
-            return _multiSubnetFailoverHostNames[rnd.Next(_multiSubnetFailoverHostNames.Count)];
-        }
-
-        public SqlServerDataSource Source { get; private set; }
-
-        internal void InitializeFakeHostsForMultiSubnetFailover()
-        {
-            // initialize fake hosts for MultiSubnetFailover
-            string originalHost, protocol, instance;
-            int? port;
-            NetUtils.ParseDataSource(this.Source.DataSource, out protocol, out originalHost, out instance, out port);
-
-            // get the IPv4 addresses
-            IPAddress[] ipV4 = NetUtils.EnumerateIPv4Addresses(originalHost).ToArray();
-            if (ipV4 == null || ipV4.Length == 0)
-            {
-                // consider supporting IPv6 when it becomes relevant (not a goal right now)
-                throw new ArgumentException("The target server " + originalHost + " has no IPv4 addresses associated with it in DNS");
-            }
-
-            // construct different host names for MSF with valid server IP located in a different place each time
-            List<HostsFileManager.HostEntry> allEntries = new List<HostsFileManager.HostEntry>();
-
-            int nextValidIp = 0;
-            int nextInvalidIp = 0;
-            _multiSubnetFailoverHostNames = new List<string>();
-
-            // construct some interesting cases for MultiSubnetFailover stress
-
-            // for integrated security to work properly, the server name in connection string must match the target server host name.
-            // thus, create one entry in the hosts with the true server name: either FQDN or the short name
-            Task<IPHostEntry> task = Dns.GetHostEntryAsync(ipV4[0]);
-            string nameToUse = task.Result.HostName;
-            if (originalHost.Contains('.'))
-            {
-                // if the original hosts is FQDN, put short name in the hosts instead
-                // otherwise, put FQDN in hosts
-                int shortNameEnd = nameToUse.IndexOf('.');
-                if (shortNameEnd > 0)
-                    nameToUse = nameToUse.Substring(0, shortNameEnd);
-            }
-            // since true server name is being re-mapped, keep the valid IP first in the list
-            AddEntryHelper(allEntries, _multiSubnetFailoverHostNames, nameToUse,
-                ipV4[(nextValidIp++) % ipV4.Length],
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount));
-            this.MultiSubnetFailoverHostNameForIntegratedSecurity = nameToUse;
-
-            // single valid IP
-            AddEntryHelper(allEntries, _multiSubnetFailoverHostNames, "MSF_MP_Stress_V",
-                ipV4[(nextValidIp++) % ipV4.Length]);
-
-            // valid + invalid
-            AddEntryHelper(
-                allEntries, _multiSubnetFailoverHostNames, "MSF_MP_Stress_VI",
-                ipV4[(nextValidIp++) % ipV4.Length],
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount));
-
-            // invalid + valid + invalid
-            AddEntryHelper(
-                allEntries, _multiSubnetFailoverHostNames, "MSF_MP_Stress_IVI",
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount),
-                ipV4[(nextValidIp++) % ipV4.Length],
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount));
-
-            // Using more than one active IP associated with the virtual name (VNN) is not a supported scenario with MultiSubnetFailover.
-            // But, this can definitly happen in reality - add special cases here to cover two valid IPs.
-            AddEntryHelper(
-                allEntries, _multiSubnetFailoverHostNames, "MSF_MP_Stress_IVI",
-                ipV4[(nextValidIp++) % ipV4.Length],
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount),
-                ipV4[(nextValidIp++) % ipV4.Length]);
-
-            // big boom with 7 IPs - for stress purposes only
-            AddEntryHelper(
-                allEntries, _multiSubnetFailoverHostNames, "MSF_MP_Stress_BIGBOOM",
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount),
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount),
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount),
-                ipV4[(nextValidIp++) % ipV4.Length],
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount),
-                ipV4[(nextValidIp++) % ipV4.Length],
-                NetUtils.GetNonExistingIPv4((nextInvalidIp++) % NetUtils.NonExistingIPv4AddressCount)
-                );
-
-            // list of fake hosts is ready, initialize hosts file manager and update the file
-            _hostsFile = new HostsFileManager();
-            _hostsFile.AddRange(allEntries);
-        }
-
-
-        private static void AddEntryHelper(List<HostsFileManager.HostEntry> entries, List<string> names, string msfHostName, params IPAddress[] addresses)
-        {
-            for (int i = 0; i < addresses.Length; i++)
-                entries.Add(new HostsFileManager.HostEntry(msfHostName, addresses[i]));
-            names.Add(msfHostName);
-        }
-
-        internal void Terminate()
-        {
-            // revert hosts file
-            if (_hostsFile != null)
-            {
-                _hostsFile.Dispose();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/NetUtils.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/NetUtils.cs
deleted file mode 100644 (file)
index 55212da..0000000
+++ /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.Net;
-using System.Diagnostics;
-using System.Data.SqlClient;
-using System.Collections.Generic;
-using Microsoft.Win32;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.Test.Data.SqlClient
-{
-    public static class NetUtils
-    {
-        // according to RFC 5737 (http://tools.ietf.org/html/rfc5737): The blocks 192.0.2.0/24 (TEST-NET-1), 198.51.100.0/24 (TEST-NET-2),
-        // and 203.0.113.0/24 (TEST-NET-3) are provided for use in documentation and should not be in use by any public network
-        private static readonly IPAddress[] s_testNets = new IPAddress[]
-        {
-            IPAddress.Parse("192.0.2.0"),
-            IPAddress.Parse("198.51.100.0"),
-            IPAddress.Parse("203.0.113.0")
-        };
-
-        private const int TestNetAddressRangeLength = 256;
-
-        public static readonly int NonExistingIPv4AddressCount = TestNetAddressRangeLength * s_testNets.Length;
-
-        public static IPAddress GetNonExistingIPv4(int index)
-        {
-            if (index < 0 || index > NonExistingIPv4AddressCount)
-            {
-                throw new ArgumentOutOfRangeException("index");
-            }
-
-            byte[] address = s_testNets[index / TestNetAddressRangeLength].GetAddressBytes();
-
-            Debug.Assert(address[3] == 0, "address ranges above must end with .0");
-            address[3] = checked((byte)(index % TestNetAddressRangeLength));
-
-            return new IPAddress(address);
-        }
-
-        public static IEnumerable<IPAddress> EnumerateIPv4Addresses(string hostName)
-        {
-            hostName = hostName.Trim();
-
-            if ((hostName == ".") ||
-                 (string.Compare("(local)", hostName, StringComparison.OrdinalIgnoreCase) == 0))
-            {
-                hostName = Dns.GetHostName();
-            }
-
-            Task<IPAddress[]> task = Dns.GetHostAddressesAsync(hostName);
-            IPAddress[] allAddresses = task.Result;
-
-            foreach (var addr in allAddresses)
-            {
-                if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
-                {
-                    yield return addr;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Splits data source into protocol, host name, instance name and port.
-        ///
-        /// Note that this algorithm does not cover all valid combinations of data source; only those we actually use in tests are supported now.
-        /// Please update as needed.
-        /// </summary>
-        public static void ParseDataSource(string dataSource, out string protocol, out string hostName, out string instanceName, out int? port)
-        {
-            // check for protocol prefix
-            int i = dataSource.IndexOf(':');
-            if (i >= 0)
-            {
-                protocol = dataSource.Substring(0, i);
-
-                // remove the protocol
-                dataSource = dataSource.Substring(i + 1);
-            }
-            else
-            {
-                protocol = null;
-            }
-
-            // check for server port
-            i = dataSource.IndexOf(',');
-            if (i >= 0)
-            {
-                // there is a port value in connection string
-                port = int.Parse(dataSource.Substring(i + 1));
-                dataSource = dataSource.Substring(0, i);
-            }
-            else
-            {
-                port = null;
-            }
-
-            // check for the instance name
-            i = dataSource.IndexOf('\\');
-            if (i >= 0)
-            {
-                instanceName = dataSource.Substring(i + 1);
-                dataSource = dataSource.Substring(0, i);
-            }
-            else
-            {
-                instanceName = null;
-            }
-
-            // trim redundant whitespace
-            dataSource = dataSource.Trim();
-            hostName = dataSource;
-        }
-
-        private static Dictionary<string, int> s_dataSourceToPortCache = new Dictionary<string, int>();
-
-        /// <summary>
-        /// the method converts the regular connection string to one supported by MultiSubnetFailover (connect to the port, bypassing the browser)
-        /// it does the following:
-        /// * removes Failover Partner, if presents
-        /// * removes the network library and protocol prefix (only TCP is supported)
-        /// * if instance name is specified without port value, data source is replaced with "server, port" format instead of "server\name"
-        ///
-        /// Note that this method can create a connection to the server in case TCP port is needed. The port value is cached per data source, to avoid round trip to the server on next use.
-        /// </summary>
-        /// <param name="connectionString">original connection string, must be valid</param>
-        /// <param name="replaceServerName">optionally, replace the (network) server name with a different one</param>
-        /// <param name="originalServerName">holds the original server name on return</param>
-        /// <returns>MultiSubnetFailover-enabled connection string builder</returns>
-        public static SqlConnectionStringBuilder GetMultiSubnetFailoverConnectionString(string connectionString, string replaceServerName, out string originalServerName)
-        {
-            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(connectionString);
-
-            sb["Network Library"] = null; // MSF supports TCP only, no need to specify the protocol explicitly
-            sb["Failover Partner"] = null; // not supported, remove it if present
-
-            string protocol, instance;
-            int? serverPort;
-
-            ParseDataSource(sb.DataSource, out protocol, out originalServerName, out instance, out serverPort);
-
-            // Note: protocol value is ignored, connection to the server will fail if TCP is not enabled on the server
-
-            if (!serverPort.HasValue)
-            {
-                // to get server listener's TCP port, connect to it using the original string, with TCP protocol enforced
-                // to improve stress performance, cache the port value to avoid round trip every time new connection string is needed
-                lock (s_dataSourceToPortCache)
-                {
-                    int cachedPort;
-                    string cacheKey = sb.DataSource;
-                    if (s_dataSourceToPortCache.TryGetValue(cacheKey, out cachedPort))
-                    {
-                        serverPort = cachedPort;
-                    }
-                    else
-                    {
-                        string originalServerNameWithInstance = sb.DataSource;
-                        int protocolEndIndex = originalServerNameWithInstance.IndexOf(':');
-                        if (protocolEndIndex >= 0)
-                        {
-                            originalServerNameWithInstance = originalServerNameWithInstance.Substring(protocolEndIndex + 1);
-                        }
-
-                        sb.DataSource = "tcp:" + originalServerNameWithInstance;
-                        string tcpConnectionString = sb.ConnectionString;
-                        using (SqlConnection con = new SqlConnection(tcpConnectionString))
-                        {
-                            con.Open();
-
-                            SqlCommand cmd = con.CreateCommand();
-                            cmd.CommandText = "select [local_tcp_port] from sys.dm_exec_connections where [session_id] = @@SPID";
-                            serverPort = Convert.ToInt32(cmd.ExecuteScalar());
-                        }
-
-                        s_dataSourceToPortCache[cacheKey] = serverPort.Value;
-                    }
-                }
-            }
-
-            // override it with user-provided one
-            string retDataSource;
-            if (replaceServerName != null)
-            {
-                retDataSource = replaceServerName;
-            }
-            else
-            {
-                retDataSource = originalServerName;
-            }
-
-            // reconstruct the connection string (with the new server name and port)
-            // also, no protocol is needed since TCP is enforced anyway if MultiSubnetFailover is set to true
-            Debug.Assert(serverPort.HasValue, "Server port must be initialized");
-            retDataSource += ", " + serverPort.Value;
-
-            sb.DataSource = retDataSource;
-            sb.MultiSubnetFailover = true;
-
-            return sb;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/SqlClientStressFactory.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/SqlClientStressFactory.cs
deleted file mode 100644 (file)
index 75586f0..0000000
+++ /dev/null
@@ -1,223 +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.Data.SqlClient;
-using Microsoft.Test.Data.SqlClient;
-
-namespace Stress.Data.SqlClient
-{
-    public class SqlClientStressFactory : DataStressFactory
-    {
-        // scenarios
-        internal enum SqlClientScenario
-        {
-            Sql
-        }
-
-        private SqlServerDataSource _source;
-        private SqlClientScenario _scenario;
-
-        private MultiSubnetFailoverSetup _multiSubnetSetupHelper;
-
-        internal SqlClientStressFactory()
-            : base(SqlClientFactory.Instance)
-        {
-        }
-
-        internal void Initialize(ref string scenario, ref DataSource source)
-        {
-            // Ignore all asserts from known issues
-            var defaultTraceListener = Trace.Listeners["Default"] as DefaultTraceListener;
-            if (defaultTraceListener != null)
-            {
-                var newTraceListener = new FilteredDefaultTraceListener(defaultTraceListener);
-                Trace.Listeners.Remove(defaultTraceListener);
-                Trace.Listeners.Add(newTraceListener);
-            }
-
-            // scenario <=> SqlClientScenario
-            if (string.IsNullOrEmpty(scenario))
-            {
-                _scenario = SqlClientScenario.Sql;
-            }
-            else
-            {
-                _scenario = (SqlClientScenario)Enum.Parse(typeof(SqlClientScenario), scenario, true);
-            }
-            scenario = _scenario.ToString();
-
-            // initialize the source information
-            // SNAC/WDAC is using SqlServer sources; JET is using Access
-            switch (_scenario)
-            {
-                case SqlClientScenario.Sql:
-                    if (source == null)
-                        source = DataStressSettings.Instance.GetDefaultSourceByType(DataSourceType.SqlServer);
-                    else if (source.Type != DataSourceType.SqlServer)
-                        throw new ArgumentException(string.Format("Given source type is wrong: required {0}, received {1}", DataSourceType.SqlServer, source.Type));
-                    break;
-
-                default:
-                    throw new ArgumentException("Wrong scenario \"" + scenario + "\"");
-            }
-
-            _source = (SqlServerDataSource)source;
-
-            // Only try to add Multisubnet Failover host entries when the settings allow it in the source.
-            if (!_source.DisableMultiSubnetFailoverSetup)
-            {
-                _multiSubnetSetupHelper = new MultiSubnetFailoverSetup(_source);
-                _multiSubnetSetupHelper.InitializeFakeHostsForMultiSubnetFailover();
-            }
-        }
-
-
-
-        internal void Terminate()
-        {
-            if (_multiSubnetSetupHelper != null)
-            {
-                _multiSubnetSetupHelper.Terminate();
-            }
-        }
-
-        public sealed override string GetParameterName(string pName)
-        {
-            return "@" + pName;
-        }
-
-        public override bool PrimaryKeyValueIsRequired
-        {
-            get { return false; }
-        }
-
-
-        public override string CreateBaseConnectionString(Random rnd, ConnectionStringOptions options)
-        {
-            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
-
-            switch (_scenario)
-            {
-                case SqlClientScenario.Sql:
-                    builder.DataSource = _source.DataSource;
-                    builder.InitialCatalog = _source.Database;
-                    break;
-
-                default:
-                    throw new InvalidOperationException("missing case for " + _scenario);
-            }
-
-            // Randomize between Windows Authentication and SQL Authentication
-            // Note that having 2 options here doubles the number of connection pools
-            bool integratedSecurity = false;
-            if (_source.SupportsWindowsAuthentication)
-            {
-                if (string.IsNullOrEmpty(_source.User)) // if sql login is not provided
-                    integratedSecurity = true;
-                else
-                    integratedSecurity = (rnd != null) ? (rnd.Next(2) == 0) : true;
-            }
-
-            if (integratedSecurity)
-            {
-                builder.IntegratedSecurity = true;
-            }
-            else
-            {
-                builder.UserID = _source.User;
-                builder.Password = _source.Password;
-            }
-
-            if (CurrentPoolingStressMode == PoolingStressMode.RandomizeConnectionStrings && rnd != null)
-            {
-                // Randomize connection string
-
-                // Randomize packetsize
-                // Note that having 2 options here doubles the number of connection pools
-                if (rnd.NextBool())
-                {
-                    builder.PacketSize = 8192;
-                }
-                else
-                {
-                    builder.PacketSize = 512;
-                }
-
-                // If test case allows randomization and doesn't disallow MultiSubnetFailover, then enable MultiSubnetFailover 20% of the time
-                // Note that having 2 options here doubles the number of connection pools
-
-                if (!_source.DisableMultiSubnetFailoverSetup &&
-                    !options.HasFlag(ConnectionStringOptions.DisableMultiSubnetFailover) &&
-                    rnd != null &&
-                    rnd.Next(5) == 0)
-                {
-                    string msfHostName;
-                    if (integratedSecurity)
-                    {
-                        msfHostName = _multiSubnetSetupHelper.MultiSubnetFailoverHostNameForIntegratedSecurity;
-                    }
-                    else
-                    {
-                        msfHostName = _multiSubnetSetupHelper.GetMultiSubnetFailoverHostName(rnd);
-                    }
-                    string serverName;
-
-                    // replace with build which has host name with multiple IP addresses
-                    builder = NetUtils.GetMultiSubnetFailoverConnectionString(builder.ConnectionString, msfHostName, out serverName);
-                }
-
-                // Randomize between using Named Pipes and TCP providers
-                // Note that having 2 options here doubles the number of connection pools
-                if (rnd != null)
-                {
-                    if (rnd.Next(2) == 0)
-                    {
-                        builder.DataSource = "tcp:" + builder.DataSource;
-                    }
-                    else if (!_source.DisableNamedPipes)
-                    {
-                        // Named Pipes
-                        if (builder.DataSource.Equals("(local)"))
-                            builder.DataSource = "np:" + builder.DataSource;
-                        else
-                            builder.DataSource = @"np:\\" + builder.DataSource.Split(',')[0] + @"\pipe\sql\query";
-                    }
-                }
-
-                // Set MARS if it is requested by the test case
-                if (options.HasFlag(ConnectionStringOptions.EnableMars))
-                {
-                    builder.MultipleActiveResultSets = true;
-                }
-
-                // Disable connection resiliency, which is on by default, 20% of the time.
-                if (rnd != null && rnd.NextBool(.2))
-                {
-                    builder.ConnectRetryCount = 0;
-                }
-            }
-            else
-            {
-                // Minimal randomization of connection string
-
-                // Enable MARS for all scenarios
-                builder.MultipleActiveResultSets = true;
-            }
-
-            builder.MaxPoolSize = 1000;
-
-            return builder.ToString();
-        }
-
-        protected override int GetNumDifferentApplicationNames()
-        {
-            // Return only 1 because the randomization in the base connection string above will give us more pools, so we don't need
-            // to also have many different application names. Getting connections from many different pools is not interesting to test
-            // because it reduces the amount of multithreadedness within each pool.
-            return 1;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/SqlClientTestGroup.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/SqlClientTestGroup.cs
deleted file mode 100644 (file)
index 4f7c11d..0000000
+++ /dev/null
@@ -1,612 +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.Threading;
-using System.Threading.Tasks;
-using System.Diagnostics;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Xml;
-using Stress.Data;
-
-using DPStressHarness;
-using System.IO;
-
-namespace Stress.Data.SqlClient
-{
-    public class SqlClientTestGroup : DataTestGroup
-    {
-        /// <summary>
-        /// SqlNotificationRequest options string
-        /// </summary>
-        private static string s_notificationOptions;
-
-        /// <summary>
-        /// Connection string for SqlDependency.Start()/Stop()
-        ///
-        /// The connection string used for SqlDependency.Start() must always be exactly the same every time
-        /// if you are connecting to the same database with the same user and same application domain, so
-        /// don't randomise the connection string for calling SqlDependency.Start()
-        /// </summary>
-        private static string s_sqlDependencyConnString;
-
-        /// <summary>
-        /// A thread which randomly calls SqlConnection.ClearAllPools.
-        /// This significantly increases the probability of hitting some bugs, such as:
-        ///     vstfdevdiv 674236 (SqlConnection.Open() throws InvalidOperationException for absolutely valid connection request)
-        ///     sqlbuvsts 328845 (InvalidOperationException: The requested operation cannot be completed because the connection has been broken.) (this is LSE QFE)
-        /// However, calling ClearAllPools all the time might also significantly decrease the probability of hitting some other bug,
-        /// so this thread will alternate between hammering on ClearAllPools for several minutes, and then doing nothing for several minutes.
-        /// </summary>
-        private static Thread s_clearAllPoolsThread;
-
-        /// <summary>
-        /// Call .Set() on this to cleanly stop the ClearAllPoolsThread.
-        /// </summary>
-        private static ManualResetEvent s_clearAllPoolsThreadStop = new ManualResetEvent(false);
-
-        private static void ClearAllPoolsThreadFunc()
-        {
-            Random rnd = new TrackedRandom((int)Environment.TickCount);
-
-            // Swap between calling ClearAllPools and doing nothing every 5 minutes.
-            TimeSpan halfCycleTime = TimeSpan.FromMinutes(5);
-
-            int minWait = 10; // milliseconds
-            int maxWait = 1000; // milliseconds
-
-            bool active = true; // Start active so we can hit vstfdevdiv 674236 asap
-            Stopwatch stopwatch = Stopwatch.StartNew();
-            while (!s_clearAllPoolsThreadStop.WaitOne(rnd.Next(minWait, maxWait)))
-            {
-                if (stopwatch.Elapsed > halfCycleTime)
-                {
-                    active = !active;
-                    stopwatch.Reset();
-                    stopwatch.Start();
-                }
-
-                if (active)
-                {
-                    SqlConnection.ClearAllPools();
-                }
-            }
-        }
-
-        public override void GlobalTestSetup()
-        {
-            base.GlobalTestSetup();
-
-            s_clearAllPoolsThread = new Thread(ClearAllPoolsThreadFunc);
-            s_clearAllPoolsThread.Start();
-
-            // set the notification options for SqlNotificationRequest tests
-            s_notificationOptions = "service=StressNotifications;local database=" + ((SqlServerDataSource)Source).Database;
-
-            s_sqlDependencyConnString = Factory.CreateBaseConnectionString(null, DataStressFactory.ConnectionStringOptions.DisableMultiSubnetFailover);
-        }
-
-        public override void GlobalTestCleanup()
-        {
-            s_clearAllPoolsThreadStop.Set();
-            s_clearAllPoolsThread.Join();
-
-            SqlClientStressFactory factory = Factory as SqlClientStressFactory;
-            if (factory != null)
-            {
-                factory.Terminate();
-            }
-
-            base.GlobalTestCleanup();
-        }
-
-        public override void GlobalExceptionHandler(Exception e)
-        {
-            base.GlobalExceptionHandler(e);
-        }
-
-        protected override DataStressFactory CreateFactory(ref string scenario, ref DataSource source)
-        {
-            SqlClientStressFactory factory = new SqlClientStressFactory();
-            factory.Initialize(ref scenario, ref source);
-            return factory;
-        }
-
-        protected override bool IsCommandCancelledException(Exception e)
-        {
-            return
-                base.IsCommandCancelledException(e) ||
-                ((e is SqlException || e is InvalidOperationException) && e.Message.ToLower().Contains("operation cancelled")) ||
-                (e is SqlException && e.Message.StartsWith("A severe error occurred on the current command.")) ||
-                (e is AggregateException && e.InnerException != null && IsCommandCancelledException(e.InnerException)) ||
-                (e is System.Reflection.TargetInvocationException && e.InnerException != null && IsCommandCancelledException(e.InnerException));
-        }
-
-        protected override bool IsReaderClosedException(Exception e)
-        {
-            return
-                e is TaskCanceledException
-                ||
-                (
-                    e is InvalidOperationException
-                    &&
-                    (
-                        (e.Message.StartsWith("Invalid attempt to call") && e.Message.EndsWith("when reader is closed."))
-                        ||
-                        e.Message.Equals("Invalid attempt to read when no data is present.")
-                        ||
-                        e.Message.Equals("Invalid operation. The connection is closed.")
-                    )
-                )
-                ||
-                (
-                    e is ObjectDisposedException
-                    &&
-                    (
-                        e.Message.Equals("Cannot access a disposed object.\r\nObject name: 'SqlSequentialStream'.")
-                        ||
-                        e.Message.Equals("Cannot access a disposed object.\r\nObject name: 'SqlSequentialTextReader'.")
-                    )
-                );
-        }
-
-        protected override bool AllowReaderCloseDuringReadAsync()
-        {
-            return true;
-        }
-
-        /// <summary>
-        /// Utility function used by async tests
-        /// </summary>
-        /// <param name="com">SqlCommand to be executed.</param>
-        /// <param name="query">Indicates if data is being queried</param>
-        /// <param name="xml">Indicates if the query should be executed as an Xml</param>
-        /// <param name="useBeginAPI"></param>
-        /// <param name="cts">The Cancellation Token Source</param>
-        /// <returns>The result of beginning of Async execution.</returns>
-        private IAsyncResult SqlCommandBeginExecute(SqlCommand com, bool query, bool xml, bool useBeginAPI, CancellationTokenSource cts = null)
-        {
-            DataStressErrors.Assert(!(useBeginAPI && cts != null), "Cannot use begin api with CancellationTokenSource");
-
-            CancellationToken token = (cts != null) ? cts.Token : CancellationToken.None;
-
-            if (xml)
-            {
-                com.CommandText = com.CommandText + " FOR XML AUTO";
-                return useBeginAPI ? null : com.ExecuteXmlReaderAsync(token);
-            }
-            else if (query)
-            {
-                return useBeginAPI ? null : com.ExecuteReaderAsync(token);
-            }
-            else
-            {
-                return useBeginAPI ? null : com.ExecuteNonQueryAsync(token);
-            }
-        }
-
-        /// <summary>
-        /// Utility function used by async tests
-        /// </summary>
-        /// <param name="rnd"> Used to randomize reader.Read() call, whether it should continue or break, and is passed down to ConsumeReaderAsync</param>
-        /// <param name="result"> The Async result from Begin operation.</param>
-        /// <param name="com"> The Sql Command to Execute</param>
-        /// <param name="query">Indicates if data is being queried and where ExecuteQuery or Non-query to be used with the reader</param>
-        /// <param name="xml">Indicates if the query should be executed as an Xml</param>
-        /// <param name="cancelled">Indicates if command was cancelled and is used to throw exception if a Command cancellation related exception is encountered</param>
-        /// <param name="cts">The Cancellation Token Source</param>
-        private void SqlCommandEndExecute(Random rnd, IAsyncResult result, SqlCommand com, bool query, bool xml, bool cancelled, CancellationTokenSource cts = null)
-        {
-            try
-            {
-                bool closeReader = ShouldCloseDataReader();
-                if (xml)
-                {
-                    XmlReader reader = null;
-                    if (result != null && result is Task<XmlReader>)
-                    {
-                        reader = AsyncUtils.GetResult<XmlReader>(result);
-                    }
-                    else
-                    {
-                        reader = AsyncUtils.ExecuteXmlReader(com);
-                    }
-
-                    while (reader.Read())
-                    {
-                        if (rnd.Next(10) == 0) break;
-                        if (rnd.Next(2) == 0) continue;
-                        reader.ReadElementContentAsString();
-                    }
-                    if (closeReader) reader.Dispose();
-                }
-                else if (query)
-                {
-                    DataStressReader reader = null;
-                    if (result != null && result is Task<SqlDataReader>)
-                    {
-                        reader = new DataStressReader(AsyncUtils.GetResult<SqlDataReader>(result));
-                    }
-                    else
-                    {
-                        reader = new DataStressReader(AsyncUtils.ExecuteReader(com));
-                    }
-
-                    CancellationToken token = (cts != null) ? cts.Token : CancellationToken.None;
-
-                    AsyncUtils.WaitAndUnwrapException(ConsumeReaderAsync(reader, false, token, rnd));
-
-                    if (closeReader) reader.Close();
-                }
-                else
-                {
-                    if (result != null && result is Task<int>)
-                    {
-                        int temp = AsyncUtils.GetResult<int>(result);
-                    }
-                    else
-                    {
-                        AsyncUtils.ExecuteNonQuery(com);
-                    }
-                }
-            }
-            catch (Exception e)
-            {
-                if (cancelled && IsCommandCancelledException(e))
-                {
-                    // expected exception, ignore
-                }
-                else
-                {
-                    throw;
-                }
-            }
-        }
-
-
-        /// <summary>
-        /// Utility function for tests
-        /// </summary>
-        /// <param name="rnd"></param>
-        /// <param name="read"></param>
-        /// <param name="poll"></param>
-        /// <param name="handle"></param>
-        /// <param name="xml"></param>
-        private void TestSqlAsync(Random rnd, bool read, bool poll, bool handle, bool xml)
-        {
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                SqlCommand com = (SqlCommand)Factory.GetCommand(rnd, table, conn, read, xml);
-                bool useBeginAPI = rnd.NextBool();
-
-                IAsyncResult result = SqlCommandBeginExecute(com, read, xml, useBeginAPI);
-                // Cancel 1/10 commands
-                bool cancel = (rnd.Next(10) == 0);
-                if (cancel)
-                {
-                    if (com.Connection.State != ConnectionState.Closed) com.Cancel();
-                }
-
-                if (result != null)
-                    WaitForAsyncOpToComplete(rnd, result, poll, handle);
-                // At random end query or forget it
-                if (rnd.Next(2) == 0)
-                    SqlCommandEndExecute(rnd, result, com, read, xml, cancel);
-
-                // Randomly wait for the command to complete after closing the connection to verify devdiv bug 200550.
-                // This was fixed for .NET 4.5 Task-based API, but not for the older Begin/End IAsyncResult API.
-                conn.Close();
-                if (!useBeginAPI && rnd.NextBool())
-                    result.AsyncWaitHandle.WaitOne();
-            }
-        }
-
-        private void WaitForAsyncOpToComplete(Random rnd, IAsyncResult result, bool poll, bool handle)
-        {
-            if (poll)
-            {
-                long ret = 0;
-                bool wait = !result.IsCompleted;
-                while (wait)
-                {
-                    wait = !result.IsCompleted;
-                    Thread.Sleep(100);
-                    if (ret++ > 300) //30 second max wait time  then exit
-                        wait = false;
-                }
-            }
-            else if (handle)
-            {
-                WaitHandle wait = result.AsyncWaitHandle;
-                wait.WaitOne(rnd.Next(1000));
-            }
-        }
-
-        /// <summary>
-        /// SqlClient Async Non-blocking Read Test
-        /// </summary>
-        [StressTest("TestSqlAsyncNonBlockingRead", Weight = 10)]
-        public void TestSqlAsyncNonBlockingRead()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: true, poll: false, handle: false, xml: false);
-        }
-
-        /// <summary>
-        /// SqlClient Async Non-blocking Write Test
-        /// </summary>
-        [StressTest("TestSqlAsyncNonBlockingWrite", Weight = 10)]
-        public void TestSqlAsyncNonBlockingWrite()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: false, poll: false, handle: false, xml: false);
-        }
-
-        /// <summary>
-        /// SqlClient Async Polling Read Test
-        /// </summary>
-        [StressTest("TestSqlAsyncPollingRead", Weight = 10)]
-        public void TestSqlAsyncPollingRead()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: true, poll: true, handle: false, xml: false);
-        }
-
-        /// <summary>
-        /// SqlClient Async Polling Write Test
-        /// </summary>
-        [StressTest("TestSqlAsyncPollingWrite", Weight = 10)]
-        public void TestSqlAsyncPollingWrite()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: false, poll: true, handle: false, xml: false);
-        }
-
-        /// <summary>
-        /// SqlClient Async Event Read Test
-        /// </summary>
-        [StressTest("TestSqlAsyncEventRead", Weight = 10)]
-        public void TestSqlAsyncEventRead()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: true, poll: false, handle: true, xml: false);
-        }
-
-        /// <summary>
-        /// SqlClient Async Event Write Test
-        /// </summary>
-        [StressTest("TestSqlAsyncEventWrite", Weight = 10)]
-        public void TestSqlAsyncEventWrite()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: false, poll: false, handle: true, xml: false);
-        }
-
-
-        /// <summary>
-        /// SqlClient Async Xml Non-blocking Read Test
-        /// </summary>
-        [StressTest("TestSqlXmlAsyncNonBlockingRead", Weight = 10)]
-        public void TestSqlXmlAsyncNonBlockingRead()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: true, poll: false, handle: false, xml: true);
-        }
-
-        /// <summary>
-        /// SqlClient Async Xml Polling Read Test
-        /// </summary>
-        [StressTest("TestSqlXmlAsyncPollingRead", Weight = 10)]
-        public void TestSqlXmlAsyncPollingRead()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: true, poll: true, handle: false, xml: true);
-        }
-
-        /// <summary>
-        /// SqlClient Async Xml Event Read Test
-        /// </summary>
-        [StressTest("TestSqlXmlAsyncEventRead", Weight = 10)]
-        public void TestSqlXmlAsyncEventRead()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsync(rnd, read: true, poll: false, handle: true, xml: true);
-        }
-
-
-        [StressTest("TestSqlXmlCommandReader", Weight = 10)]
-        public void TestSqlXmlCommandReader()
-        {
-            Random rnd = RandomInstance;
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                SqlCommand com = (SqlCommand)Factory.GetCommand(rnd, table, conn, query: true, isXml: true);
-                com.CommandText = com.CommandText + " FOR XML AUTO";
-
-                // Cancel 1/10 commands
-                bool cancel = rnd.Next(10) == 0;
-                if (cancel)
-                {
-                    ThreadPool.QueueUserWorkItem(new WaitCallback(CommandCancel), com);
-                }
-
-                try
-                {
-                    XmlReader reader = com.ExecuteXmlReader();
-
-                    while (reader.Read())
-                    {
-                        if (rnd.Next(10) == 0) break;
-                        if (rnd.Next(2) == 0) continue;
-                        reader.ReadElementContentAsString();
-                    }
-                    if (rnd.Next(10) != 0) reader.Dispose();
-                }
-                catch (Exception ex)
-                {
-                    if (cancel && IsCommandCancelledException(ex))
-                    {
-                        // expected, ignore
-                    }
-                    else
-                    {
-                        throw;
-                    }
-                }
-            }
-        }
-
-
-        /// <summary>
-        /// Utility function used for testing cancellation on Execute*Async APIs.
-        /// </summary>
-        private void TestSqlAsyncCancellation(Random rnd, bool read, bool xml)
-        {
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                SqlCommand com = (SqlCommand)Factory.GetCommand(rnd, table, conn, read, xml);
-
-                CancellationTokenSource cts = new CancellationTokenSource();
-                Task t = (Task)SqlCommandBeginExecute(com, read, xml, false, cts);
-
-                cts.CancelAfter(rnd.Next(2000));
-                SqlCommandEndExecute(rnd, (IAsyncResult)t, com, read, xml, true, cts);
-            }
-        }
-
-        /// <summary>
-        /// SqlClient Async Xml Event Read Test
-        /// </summary>
-        [StressTest("TestExecuteXmlReaderAsyncCancellation", Weight = 10)]
-        public void TestExecuteXmlReaderAsyncCancellation()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsyncCancellation(rnd, true, true);
-        }
-
-        /// <summary>
-        /// SqlClient Async Xml Event Read Test
-        /// </summary>
-        [StressTest("TestExecuteReaderAsyncCancellation", Weight = 10)]
-        public void TestExecuteReaderAsyncCancellation()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsyncCancellation(rnd, true, false);
-        }
-
-        /// <summary>
-        /// SqlClient Async Xml Event Read Test
-        /// </summary>
-        [StressTest("TestExecuteNonQueryAsyncCancellation", Weight = 10)]
-        public void TestExecuteNonQueryAsyncCancellation()
-        {
-            Random rnd = RandomInstance;
-            TestSqlAsyncCancellation(rnd, false, false);
-        }
-
-
-        private class MARSCommand
-        {
-            internal SqlCommand cmd;
-            internal IAsyncResult result;
-            internal bool query;
-            internal bool xml;
-        }
-
-        [StressTest("TestSqlAsyncMARS", Weight = 10)]
-        public void TestSqlAsyncMARS()
-        {
-            const int MaxCmds = 11;
-            Random rnd = RandomInstance;
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd, DataStressFactory.ConnectionStringOptions.EnableMars))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-
-                // MARS session cache is by default 10.
-                // This is documented here: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets
-                // We want to stress test this by allowing 11 concurrent commands. Hence the max in rnd.Next below is 12.
-                MARSCommand[] cmds = new MARSCommand[rnd.Next(5, MaxCmds + 1)];
-
-                for (int i = 0; i < cmds.Length; i++)
-                {
-                    cmds[i] = new MARSCommand();
-
-                    // Make every 3rd query xml reader
-                    if (i % 3 == 0)
-                    {
-                        cmds[i].query = true;
-                        cmds[i].xml = true;
-                    }
-                    else
-                    {
-                        cmds[i].query = rnd.NextBool();
-                        cmds[i].xml = false;
-                    }
-
-                    cmds[i].cmd = (SqlCommand)Factory.GetCommand(rnd, table, conn, cmds[i].query, cmds[i].xml);
-                    cmds[i].result = SqlCommandBeginExecute(cmds[i].cmd, cmds[i].query, cmds[i].xml, rnd.NextBool());
-                    if (cmds[i].result != null)
-                        WaitForAsyncOpToComplete(rnd, cmds[i].result, true, false);
-                }
-
-                // After all commands have been launched, wait for them to complete now.
-                for (int i = 0; i < cmds.Length; i++)
-                {
-                    SqlCommandEndExecute(rnd, cmds[i].result, cmds[i].cmd, cmds[i].query, cmds[i].xml, false);
-                }
-            }
-        }
-
-
-        [StressTest("TestStreamInputParameter", Weight = 10)]
-        public void TestStreamInputParameter()
-        {
-            Random rnd = RandomInstance;
-            int dataSize = 100000;
-            byte[] data = new byte[dataSize];
-            rnd.NextBytes(data);
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                SqlCommand cmd = (SqlCommand)conn.CreateCommand();
-                cmd.CommandText = "SELECT @blob";
-                SqlParameter param = cmd.Parameters.Add("@blob", SqlDbType.VarBinary, dataSize);
-                param.Direction = ParameterDirection.Input;
-                param.Value = new MemoryStream(data);
-                CommandExecute(rnd, cmd, true);
-            }
-        }
-
-        [StressTest("TestTextReaderInputParameter", Weight = 10)]
-        public void TestTextReaderInputParameter()
-        {
-            Random rnd = RandomInstance;
-            int dataSize = 100000;
-            string data = new string('a', dataSize);
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                SqlCommand cmd = (SqlCommand)conn.CreateCommand();
-                cmd.CommandText = "SELECT @blob";
-                SqlParameter param = cmd.Parameters.Add("@blob", SqlDbType.VarChar, dataSize);
-                param.Direction = ParameterDirection.Input;
-                param.Value = new StringReader(data);
-                CommandExecute(rnd, cmd, true);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/System.Data.SqlClient.Stress.Tests.csproj b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.SqlClient.Stress.Tests/System.Data.SqlClient.Stress.Tests.csproj
deleted file mode 100644 (file)
index 5cf78a8..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <RootNamespace>Stress.Data.SqlClient</RootNamespace>
-    <AssemblyName>System.Data.SqlClient.Stress.Tests</AssemblyName>
-    <!-- These should not run in Helix: they produce no outputs and are only run manually -->
-    <Configurations>$(NetCoreAppCurrent)-Unix-Debug;$(NetCoreAppCurrent)-Unix-Release;$(NetCoreAppCurrent)-Windows_NT-Debug;$(NetCoreAppCurrent)-Windows_NT-Release;$(NetFrameworkCurrent)-Windows_NT-Debug;$(NetFrameworkCurrent)-Windows_NT-Release</Configurations>
-    <IgnoreForCI>true</IgnoreForCI>
-  </PropertyGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\System.Data.StressRunner\System.Data.StressRunner.csproj" />
-    <ProjectReference Include="..\System.Data.StressFramework\System.Data.StressFramework.csproj" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="MultiSubnetFailoverSetup.cs" />
-    <Compile Include="SqlClientStressFactory.cs" />
-    <Compile Include="SqlClientTestGroup.cs" />
-    <Compile Include="FilteredDefaultTraceListener.cs" />
-    <Compile Include="HostsFileManager.cs" />
-    <Compile Include="NetUtils.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/AsyncUtils.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/AsyncUtils.cs
deleted file mode 100644 (file)
index 5c66a98..0000000
+++ /dev/null
@@ -1,186 +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.Data.SqlClient;
-using System.Linq;
-using System.Runtime.ExceptionServices;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-using DPStressHarness;
-
-namespace Stress.Data
-{
-    public enum SyncAsyncMode
-    {
-        Sync,           // call sync method, e.g. connection.Open(), and return completed task
-        SyncOverAsync,  // call async method, e.g. connection.OpenAsync().Wait(), and return completed task
-        Async           // call async method, e.g. connection.OpenAsync(), and return running task
-    }
-
-    public static class AsyncUtils
-    {
-        public static Task<TResult> SyncOrAsyncMethod<TResult>(Func<TResult> syncFunc, Func<Task<TResult>> asyncFunc, SyncAsyncMode mode)
-        {
-            switch (mode)
-            {
-                case SyncAsyncMode.Sync:
-                    TResult result = syncFunc();
-                    return Task.FromResult(result);
-
-                case SyncAsyncMode.SyncOverAsync:
-                    Task<TResult> t = asyncFunc();
-                    WaitAndUnwrapException(t);
-                    return t;
-
-                case SyncAsyncMode.Async:
-                    return asyncFunc();
-
-                default:
-                    throw new ArgumentException(mode.ToString());
-            }
-        }
-
-        public static Task SyncOrAsyncMethod(Action syncFunc, Func<Task> asyncFunc, SyncAsyncMode mode)
-        {
-            switch (mode)
-            {
-                case SyncAsyncMode.Sync:
-                    syncFunc();
-                    return Task.CompletedTask;
-
-                case SyncAsyncMode.SyncOverAsync:
-                    Task t = asyncFunc();
-                    WaitAndUnwrapException(t);
-                    return t;
-
-                case SyncAsyncMode.Async:
-                    return asyncFunc();
-
-                default:
-                    throw new ArgumentException(mode.ToString());
-            }
-        }
-
-        public static void WaitAll(params Task[] ts)
-        {
-            DeadlockDetection.DisableThreadAbort();
-            try
-            {
-                Task.WaitAll(ts);
-            }
-            finally
-            {
-                DeadlockDetection.EnableThreadAbort();
-            }
-        }
-
-        public static void WaitAllNullable(params Task[] ts)
-        {
-            DeadlockDetection.DisableThreadAbort();
-            try
-            {
-                Task[] tasks = ts.Where(t => t != null).ToArray();
-                Task.WaitAll(tasks);
-            }
-            finally
-            {
-                DeadlockDetection.EnableThreadAbort();
-            }
-        }
-
-        public static void WaitAndUnwrapException(Task t)
-        {
-            DeadlockDetection.DisableThreadAbort();
-            try
-            {
-                t.Wait();
-            }
-            catch (AggregateException ae)
-            {
-                // The callers of this API may not expect AggregateException, so throw the inner exception
-                // If AggregateException contains more than one InnerExceptions, throw it out as it is,
-                // because that is unexpected
-                if ((ae.InnerExceptions != null) && (ae.InnerExceptions.Count == 1))
-                {
-                    if (ae.InnerException != null)
-                    {
-                        ExceptionDispatchInfo info = ExceptionDispatchInfo.Capture(ae.InnerException);
-                        info.Throw();
-                    }
-                }
-
-                throw;
-            }
-            finally
-            {
-                DeadlockDetection.EnableThreadAbort();
-            }
-        }
-
-        public static T GetResult<T>(IAsyncResult result)
-        {
-            return GetResult<T>((Task<T>)result);
-        }
-
-        public static T GetResult<T>(Task<T> result)
-        {
-            DeadlockDetection.DisableThreadAbort();
-            try
-            {
-                return result.Result;
-            }
-            finally
-            {
-                DeadlockDetection.EnableThreadAbort();
-            }
-        }
-
-        public static SqlDataReader ExecuteReader(SqlCommand command)
-        {
-            DeadlockDetection.DisableThreadAbort();
-            try
-            {
-                return command.ExecuteReader();
-            }
-            finally
-            {
-                DeadlockDetection.EnableThreadAbort();
-            }
-        }
-
-        public static int ExecuteNonQuery(SqlCommand command)
-        {
-            DeadlockDetection.DisableThreadAbort();
-            try
-            {
-                return command.ExecuteNonQuery();
-            }
-            finally
-            {
-                DeadlockDetection.DisableThreadAbort();
-            }
-        }
-
-        public static XmlReader ExecuteXmlReader(SqlCommand command)
-        {
-            DeadlockDetection.DisableThreadAbort();
-            try
-            {
-                return command.ExecuteXmlReader();
-            }
-            finally
-            {
-                DeadlockDetection.EnableThreadAbort();
-            }
-        }
-
-        public static SyncAsyncMode ChooseSyncAsyncMode(Random rnd)
-        {
-            // Any mode is allowed
-            return (SyncAsyncMode)rnd.Next(3);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/Configurations.props b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/Configurations.props
deleted file mode 100644 (file)
index f350311..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      $(NetCoreAppCurrent)-Unix;
-      $(NetCoreAppCurrent)-Windows_NT;
-      $(NetFrameworkCurrent)-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataSource.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataSource.cs
deleted file mode 100644 (file)
index 6a299cb..0000000
+++ /dev/null
@@ -1,160 +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;
-
-namespace Stress.Data
-{
-    /// <summary>
-    /// supported source types - values for 'type' attribute for 'source' node in App.config
-    /// </summary>
-    public enum DataSourceType
-    {
-        SqlServer
-    }
-
-    /// <summary>
-    /// base class for database source information (SQL Server, Oracle Server, Access Database file, etc...).
-    /// Data sources are loaded from the app config file.
-    /// </summary>
-    public abstract class DataSource
-    {
-        /// <summary>
-        /// name of the source - can be used in command line: StressTest ... -override source "sourcename"
-        /// </summary>
-        public readonly string Name;
-
-        /// <summary>
-        /// database type
-        /// </summary>
-        public readonly DataSourceType Type;
-
-        /// <summary>
-        /// whether this source is the default one for the type specified
-        /// </summary>
-        public readonly bool IsDefault;
-
-        /// <summary>
-        /// constructs new data source - called by derived class c-tors only (thus protected)
-        /// </summary>
-        protected DataSource(string name, DataSourceType type, bool isDefault)
-        {
-            this.Name = name;
-            this.Type = type;
-            this.IsDefault = isDefault;
-        }
-
-        /// <summary>
-        /// this method is used to create the data source, based on its type
-        /// </summary>
-        public static DataSource Create(string name, DataSourceType sourceType, bool isDefault, IDictionary<string, string> properties)
-        {
-            switch (sourceType)
-            {
-                case DataSourceType.SqlServer:
-                    return new SqlServerDataSource(name, isDefault, properties);
-                default:
-                    throw new ArgumentException("Wrong source type value: " + sourceType);
-            }
-        }
-
-        /// <summary>
-        ///  used by GetRequiredAttributeValue or derived classes to construct exception on missing required attribute
-        /// </summary>
-        /// <param name="sourceName">name of the source (from XML) to include in exception message (for troubleshooting)</param>
-        protected Exception MissingAttributeValueException(string sourceName, string attributeName)
-        {
-            return new ArgumentException(string.Format("Missing or empty value for {0} attribute in the config file for source: {1}", attributeName, sourceName));
-        }
-
-        /// <summary>
-        /// search for required attribute or fail if not found
-        /// </summary>
-        protected string GetRequiredAttributeValue(string sourceName, IDictionary<string, string> properties, string valueName, bool allowEmpty)
-        {
-            string value;
-            if (!properties.TryGetValue(valueName, out value) || (value == null) || (!allowEmpty && value.Length == 0))
-            {
-                throw MissingAttributeValueException(sourceName, valueName);
-            }
-            return value;
-        }
-
-        /// <summary>
-        /// search for optional attribute or return default vale
-        /// </summary>
-        protected string GetOptionalAttributeValue(IDictionary<string, string> properties, string valueName, string defaultValue)
-        {
-            string value;
-            if (!properties.TryGetValue(valueName, out value) || (value == null))
-            {
-                value = defaultValue;
-            }
-            return value;
-        }
-    }
-
-    /// <summary>
-    /// Represents SQL Server data source. This source is used by SqlClient as well as by ODBC and OLEDB when connecting to SQL with SNAC or MDAC/WDAC
-    /// </summary>
-    /// <example>
-    ///       <source
-    ///        name="mysrv01"
-    ///        type="SqlServer"
-    ///        isDefault="false"
-    ///        dataSource="mysrv01"
-    ///        database="stress"
-    ///        user="stress"
-    ///        password=""
-    ///        supportsWindowsAuthentication="false">
-    ///      </source>
-    /// </example>
-    public class SqlServerDataSource : DataSource
-    {
-        public readonly string DataSource;
-        public readonly string Database;
-        public readonly bool IsLocal;
-
-        // if user and password are set, test can create connection strings with SQL auth settings
-        public readonly string User;
-        public readonly string Password;
-
-        // if true, test can create connnection strings with integrated security (trusted connection) set to true (or SSPI).
-        public readonly bool SupportsWindowsAuthentication;
-
-        public bool DisableMultiSubnetFailoverSetup;
-
-        public bool DisableNamedPipes;
-
-        internal SqlServerDataSource(string name, bool isDefault, IDictionary<string, string> properties)
-            : base(name, DataSourceType.SqlServer, isDefault)
-        {
-            this.DataSource = GetOptionalAttributeValue(properties, "dataSource", "localhost");
-            this.Database = GetOptionalAttributeValue(properties, "database", "stress");
-
-            this.User = GetOptionalAttributeValue(properties, "user", string.Empty);
-            this.Password = GetOptionalAttributeValue(properties, "password", string.Empty);
-
-            this.IsLocal = bool.Parse(GetOptionalAttributeValue(properties, "islocal", bool.FalseString));
-
-            this.DisableMultiSubnetFailoverSetup = bool.Parse(GetOptionalAttributeValue(properties, "DisableMultiSubnetFailoverSetup", bool.TrueString));
-
-            this.DisableNamedPipes = bool.Parse(GetOptionalAttributeValue(properties, "DisableNamedPipes", bool.TrueString));
-
-            string temp = GetOptionalAttributeValue(properties, "supportsWindowsAuthentication", "false");
-            if (!string.IsNullOrEmpty(temp))
-                SupportsWindowsAuthentication = Convert.ToBoolean(temp);
-            else
-                SupportsWindowsAuthentication = false;
-
-            if (string.IsNullOrEmpty(User) && !SupportsWindowsAuthentication)
-                throw new ArgumentException("SQL Server settings should include either a valid User name or SupportsWindowsAuthentication=true");
-        }
-    }
-
-
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressConnection.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressConnection.cs
deleted file mode 100644 (file)
index 73a7a24..0000000
+++ /dev/null
@@ -1,236 +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.Data.Common;
-using System.Data.SqlClient;
-using System.Linq;
-using System.Security.Principal;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Stress.Data
-{
-    public class DataStressConnection : IDisposable
-    {
-        public DbConnection DbConnection { get; private set; }
-        private readonly bool _clearPoolBeforeClose;
-        public DataStressConnection(DbConnection conn, bool clearPoolBeforeClose = false)
-        {
-            if (conn == null)
-                throw new ArgumentException("Cannot pass in null DbConnection to make new DataStressConnection!");
-            this.DbConnection = conn;
-            _clearPoolBeforeClose = clearPoolBeforeClose;
-        }
-
-        private short _spid = 0;
-
-        [ThreadStatic]
-        private static TrackedRandom t_randomInstance;
-        private static TrackedRandom RandomInstance
-        {
-            get
-            {
-                if (t_randomInstance == null)
-                    t_randomInstance = new TrackedRandom();
-                return t_randomInstance;
-            }
-        }
-
-        public void Open()
-        {
-            bool sync = RandomInstance.NextBool();
-
-            if (sync)
-            {
-                OpenSync();
-            }
-            else
-            {
-                Task t = OpenAsync();
-                AsyncUtils.WaitAndUnwrapException(t);
-            }
-        }
-
-        public async Task OpenAsync()
-        {
-            int startMilliseconds = Environment.TickCount;
-            try
-            {
-                await DbConnection.OpenAsync();
-            }
-            catch (ObjectDisposedException e)
-            {
-                HandleObjectDisposedException(e, true);
-                throw;
-            }
-            catch (InvalidOperationException e)
-            {
-                int endMilliseconds = Environment.TickCount;
-
-                // we may be able to handle this exception
-                HandleInvalidOperationException(e, startMilliseconds, endMilliseconds, true);
-                throw;
-            }
-
-            GetSpid();
-        }
-
-        private void OpenSync()
-        {
-            int startMilliseconds = Environment.TickCount;
-            try
-            {
-                DbConnection.Open();
-            }
-            catch (ObjectDisposedException e)
-            {
-                HandleObjectDisposedException(e, false);
-                throw;
-            }
-            catch (InvalidOperationException e)
-            {
-                int endMilliseconds = Environment.TickCount;
-
-                // we may be able to handle this exception
-                HandleInvalidOperationException(e, startMilliseconds, endMilliseconds, false);
-                throw;
-            }
-
-            GetSpid();
-        }
-
-        private void HandleObjectDisposedException(ObjectDisposedException e, bool async)
-        {
-            // Race condition in DbConnectionFactory.TryGetConnection results in an ObjectDisposedException when calling OpenAsync on a non-pooled connection
-            string methodName = async ? "OpenAsync()" : "Open()";
-            throw DataStressErrors.ProductError(
-                "Hit ObjectDisposedException in SqlConnection." + methodName, e);
-        }
-
-        private static int s_fastTimeoutCountOpen;      // number of times hit by SqlConnection.Open
-        private static int s_fastTimeoutCountOpenAsync; // number of times hit by SqlConnection.OpenAsync
-        private static readonly DateTime s_startTime = DateTime.Now;
-
-        private const int MaxFastTimeoutCountPerDay = 200;
-
-        /// <summary>
-        /// Handles InvalidOperationException generated from Open or OpenAsync calls.
-        /// For any other type of Exception, it simply returns
-        /// </summary>
-        private void HandleInvalidOperationException(InvalidOperationException e, int startMilliseconds, int endMilliseconds, bool async)
-        {
-            int elapsedMilliseconds = unchecked(endMilliseconds - startMilliseconds); // unchecked to handle overflow of Environment.TickCount
-
-            // Since InvalidOperationExceptions due to timeout can be caused by issues
-            // (e.g. network hiccup, server unavailable, etc) we need a heuristic to guess whether or not this exception
-            // should have happened or not.
-            bool wasTimeoutFromPool = (e.GetType() == typeof(InvalidOperationException)) &&
-                                      (e.Message.StartsWith("Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool"));
-
-            bool wasTooEarly = (elapsedMilliseconds < ((DbConnection.ConnectionTimeout - 5) * 1000));
-
-            if (wasTimeoutFromPool && wasTooEarly)
-            {
-                if (async)
-                    Interlocked.Increment(ref s_fastTimeoutCountOpenAsync);
-                else
-                    Interlocked.Increment(ref s_fastTimeoutCountOpen);
-            }
-        }
-
-        /// <summary>
-        /// Gets spid value.
-        /// </summary>
-        /// <remarks>
-        /// If we want to kill the connection, we get its spid up front before the test case uses the connection. Otherwise if
-        /// we try to get the spid when KillConnection is called, then the connection could be in a bad state (e.g. enlisted in
-        /// aborted transaction, or has open datareader) and we will fail to get the spid. Also the randomization is put here
-        /// instead of in KillConnection because otherwise this method would execute a command for every single connection which
-        /// most of the time will not be used later.
-        /// </remarks>
-        private void GetSpid()
-        {
-            if (DbConnection is System.Data.SqlClient.SqlConnection && RandomInstance.Next(0, 20) == 0)
-            {
-                using (var cmd = DbConnection.CreateCommand())
-                {
-                    cmd.CommandText = "select @@spid";
-                    _spid = (short)cmd.ExecuteScalar();
-                }
-            }
-            else
-            {
-                _spid = 0;
-            }
-        }
-
-        /// <summary>
-        /// Kills the given connection using "kill [spid]" if the parameter is nonzero
-        /// </summary>
-        private void KillConnection()
-        {
-            DataStressErrors.Assert(_spid != 0, "Called KillConnection with spid != 0");
-
-            using (var killerConn = DataTestGroup.Factory.CreateConnection())
-            {
-                killerConn.Open();
-
-                using (var killerCmd = killerConn.CreateCommand())
-                {
-                    killerCmd.CommandText = "begin try kill " + _spid + " end try begin catch end catch";
-                    killerCmd.ExecuteNonQuery();
-                }
-            }
-        }
-
-        /// <summary>
-        /// Kills the given connection using "kill [spid]" if the parameter is nonzero
-        /// </summary>
-        /// <returns>a Task that is asynchronously killing the connection, or null if the connection is not being killed</returns>
-        public Task KillConnectionAsync()
-        {
-            if (_spid == 0)
-                return null;
-            else
-                return Task.Factory.StartNew(() => KillConnection());
-        }
-
-        public void Close()
-        {
-            if (_spid != 0)
-            {
-                KillConnection();
-
-                // Wait before putting the connection back in the pool, to ensure that
-                // the pool checks the connection the next time it is used.
-                Task.Delay(10).ContinueWith((t) => DbConnection.Close());
-            }
-            else
-            {
-                // If this is a SqlConnection, and it is a connection with a unique connection string that we will never use again,
-                // then call SqlConnection.ClearPool() before closing so that it is fully closed and does not waste client & server resources.
-                if (_clearPoolBeforeClose)
-                {
-                    SqlConnection sqlConn = DbConnection as SqlConnection;
-                    if (sqlConn != null) SqlConnection.ClearPool(sqlConn);
-                }
-
-                DbConnection.Close();
-            }
-        }
-
-        public void Dispose()
-        {
-            Close();
-        }
-
-        public DbCommand CreateCommand()
-        {
-            return DbConnection.CreateCommand();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs
deleted file mode 100644 (file)
index ee1a107..0000000
+++ /dev/null
@@ -1,216 +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.Serialization;
-
-namespace Stress.Data
-{
-    public enum ErrorHandlingAction
-    {
-        // If you add an item here, remember to add it to all of the methods below
-        DebugBreak,
-        ThrowException
-    }
-
-    /// <summary>
-    /// Static class containing methods to report errors.
-    ///
-    /// The StressTest executor will eat exceptions that are thrown and write them out to the console. In theory these should all be
-    /// either harmless exceptions or product bugs, however at present there are a large number of test issues that will cause a flood
-    /// of exceptions. Therefore if something actually bad happens (e.g. a known product bug is hit due to regression, or a major test
-    /// programming error) this error would be easy to miss if it were reported just by throwing an exception. To solve this, we use
-    /// this class for structured & consistent handling of errors.
-    /// </summary>
-    public static class DataStressErrors
-    {
-        private static void DebugBreak(string message, Exception exception)
-        {
-            // Print out the error before breaking to make debugging easier
-            Console.WriteLine(message);
-            if (exception != null)
-            {
-                Console.WriteLine(exception);
-            }
-
-            Debugger.Break();
-        }
-
-        /// <summary>
-        /// Reports that a product bug has been hit. The action that will be taken is configurable in the .config file.
-        /// This can be used to check for regressions of known product bugs.
-        /// </summary>
-        /// <param name="description">A description of the product bug hit (e.g. title, bug number & database, more information)</param>
-        /// <param name="exception">The exception that was thrown that indicates a product bug, or null if the product bug was detected without
-        /// having thrown an exception</param>
-        /// <returns>An exception that the caller should throw.</returns>
-        public static Exception ProductError(string description, Exception exception = null)
-        {
-            switch (DataStressSettings.Instance.ActionOnProductError)
-            {
-                case ErrorHandlingAction.DebugBreak:
-                    DebugBreak("Hit product error: " + description, exception);
-                    return new ProductErrorException(description, exception);
-
-                case ErrorHandlingAction.ThrowException:
-                    return new ProductErrorException(description, exception);
-
-                default:
-                    throw UnhandledCaseError(DataStressSettings.Instance.ActionOnProductError);
-            }
-        }
-
-        /// <summary>
-        /// Reports that a non-fatal test error has been hit. The action that will be taken is configurable in the .config file.
-        /// This should be used for test errors that do not prevent the test from running.
-        /// </summary>
-        /// <param name="description">A description of the error</param>
-        /// <param name="exception">The exception that was thrown that indicates an error, or null if the error was detected without
-        /// <returns>An exception that the caller should throw.</returns>
-        public static Exception TestError(string description, Exception exception = null)
-        {
-            switch (DataStressSettings.Instance.ActionOnTestError)
-            {
-                case ErrorHandlingAction.DebugBreak:
-                    DebugBreak("Hit test error: " + description, exception);
-                    return new TestErrorException(description, exception);
-
-                case ErrorHandlingAction.ThrowException:
-                    return new TestErrorException(description, exception);
-
-                default:
-                    throw UnhandledCaseError(DataStressSettings.Instance.ActionOnTestError);
-            }
-        }
-
-        /// <summary>
-        /// Reports that a programming error in the test code has occurred. The action that will be taken is configurable in the .config file.
-        /// This must strictly be used to report programming errors. It should not be in any way possible to see one of these errors unless
-        /// you make an incorrect change to the code, for example having an unhandled case in a switch statement.
-        /// </summary>
-        /// <param name="description">A description of the error</param>
-        /// <param name="exception">The exception that was thrown that indicates an error, or null if the error was detected without
-        /// having thrown an exception</param>
-        /// <returns>An exception that the caller should throw.</returns>
-        private static Exception ProgrammingError(string description, Exception exception = null)
-        {
-            switch (DataStressSettings.Instance.ActionOnProgrammingError)
-            {
-                case ErrorHandlingAction.DebugBreak:
-                    DebugBreak("Hit programming error: " + description, exception);
-                    return new ProgrammingErrorException(description, exception);
-
-                case ErrorHandlingAction.ThrowException:
-                    return new ProgrammingErrorException(description, exception);
-
-                default:
-                    // If we are here then it's a programming error, but calling UnhandledCaseError here would cause an inifite loop.
-                    goto case ErrorHandlingAction.DebugBreak;
-            }
-        }
-
-        /// <summary>
-        /// Reports that an unhandled case in a switch statement in the test code has occurred. The action that will be taken is configurable
-        /// as a programming error in the .config file. It should not be in any way possible to see one of these errors unless
-        /// you make an incorrect change to the test code, for example having an unhandled case in a switch statement.
-        /// </summary>
-        /// <param name="unhandledValue">The value that was not handled in the switch statement</param>
-        /// <returns>An exception that the caller should throw.</returns>
-        public static Exception UnhandledCaseError<T>(T unhandledValue)
-        {
-            return ProgrammingError("Unhandled case in switch statement: " + unhandledValue);
-        }
-
-        /// <summary>
-        /// Asserts that a condition is true. If the condition is false then throws a ProgrammingError.
-        /// This must strictly be used to report programming errors. It should not be in any way possible to see one of these errors unless
-        /// you make an incorrect change to the code, for example having an unhandled case in a switch statement.
-        /// </summary>
-        /// <param name="condition">A condition to assert</param>
-        /// <param name="description">A description of the error</param>
-        /// <exception cref="ProgrammingErrorException">if the condition is false</exception>
-        public static void Assert(bool condition, string description)
-        {
-            if (!condition)
-            {
-                throw ProgrammingError(description);
-            }
-        }
-
-        /// <summary>
-        /// Reports that a fatal error has happened. This is an error that completely prevents the test from continuing,
-        /// for example a setup failure. Ordinary programming errors should not be handled by this method.
-        /// </summary>
-        /// <param name="description">A description of the error</param>
-        /// <returns>An exception that the caller should throw.</returns>
-        public static Exception FatalError(string description)
-        {
-            Console.WriteLine("Fatal test error: {0}", description);
-            Debugger.Break();       // Give the user a chance to debug
-            Environment.FailFast("Fatal error. Exit.");
-            return new Exception(); // Caller should throw this to indicate to the compiler that any code after the call is unreachable
-        }
-
-        #region Exception types
-
-        // These exception types are provided so that they can be easily found in logs, i.e. just do a text search in the console
-        // output log for "ProductErrorException"
-
-        private class ProductErrorException : Exception
-        {
-            public ProductErrorException()
-                : base()
-            {
-            }
-
-            public ProductErrorException(string message)
-                : base(message)
-            {
-            }
-
-            public ProductErrorException(string message, Exception innerException)
-                : base(message, innerException)
-            {
-            }
-        }
-
-        private class ProgrammingErrorException : Exception
-        {
-            public ProgrammingErrorException()
-                : base()
-            {
-            }
-
-            public ProgrammingErrorException(string message)
-                : base(message)
-            {
-            }
-
-            public ProgrammingErrorException(string message, Exception innerException)
-                : base(message, innerException)
-            {
-            }
-        }
-
-        private class TestErrorException : Exception
-        {
-            public TestErrorException()
-                : base()
-            {
-            }
-
-            public TestErrorException(string message)
-                : base(message)
-            {
-            }
-
-            public TestErrorException(string message, Exception innerException)
-                : base(message, innerException)
-            {
-            }
-        }
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressFactory.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressFactory.cs
deleted file mode 100644 (file)
index b4af0b5..0000000
+++ /dev/null
@@ -1,952 +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;
-using System.Data;
-using System.Data.Common;
-using System.Diagnostics;
-
-namespace Stress.Data
-{
-    /// <summary>
-    /// Base class to generate utility objects required for stress tests to run. For example: connection strings, command texts,
-    /// data tables and views, and other information
-    /// </summary>
-    public abstract class DataStressFactory : IDisposable
-    {
-        // This is the maximum number of rows, stress will operate on
-        public const int Depth = 100;
-
-        // A string value to be used for scalar data retrieval while constructing
-        // a select statement that retrieves multiple result sets.
-        public static readonly string LargeStringParam = new string('p', 2000);
-
-        // A temp table that when create puts the server session into a non-recoverable state until dropped.
-        private static readonly string s_tempTableName = string.Format("#stress_{0}", Guid.NewGuid().ToString("N"));
-
-        // The languages used for "SET LANGUAGE [language]" statements that modify the server session state.  Let's
-        // keep error message readable so we're only using english languages.
-        private static string[] s_languages = new string[]
-        {
-            "English",
-            "British English",
-        };
-
-        public DbProviderFactory DbFactory { get; private set; }
-
-        protected DataStressFactory(DbProviderFactory factory)
-        {
-            DataStressErrors.Assert(factory != null, "Argument to DataStressFactory constructor is null");
-            this.DbFactory = factory;
-        }
-
-
-        public void Dispose()
-        {
-            GC.SuppressFinalize(this);
-        }
-
-        public abstract string GetParameterName(string pName);
-
-
-        public abstract bool PrimaryKeyValueIsRequired
-        {
-            get;
-        }
-
-        [Flags]
-        public enum SelectStatementOptions
-        {
-            UseNOLOCK = 0x1,
-
-            // keep last
-            Default = 0
-        }
-
-        #region PoolingStressMode
-
-        public enum PoolingStressMode
-        {
-            RandomizeConnectionStrings,    // Use many different connection strings with the same identity, which will result in many DbConnectionPoolGroups each containing one DbConnectionPool
-        }
-
-        protected PoolingStressMode CurrentPoolingStressMode
-        {
-            get;
-            private set;
-        }
-
-        #endregion
-
-
-        /// <summary>
-        /// Creates a new connection and initializes it with random connection string generated from the factory's source
-        /// Note: if rnd is null, create a connection with minimal string required to connect to the target database
-        /// </summary>
-        /// <param name="rnd">Randomizes Connection Pool enablement, the application Name to randomize connection pool</param>
-        /// <param name="options"></param>
-        /// <returns></returns>
-        public DataStressConnection CreateConnection(Random rnd = null, ConnectionStringOptions options = ConnectionStringOptions.Default)
-        {
-            // Determine connection options (connection string, identity, etc)
-            string connectionString = CreateBaseConnectionString(rnd, options);
-            bool clearPoolBeforeClose = false;
-
-            if (rnd != null)
-            {
-                // Connection string and/or identity are randomized
-
-                // We implement this using the Application Name field in the connection string since this field
-                // should not affect behaviour other than connection pooling, since all connections in a pool
-                // must have the exact same connection string (including Application Name)
-
-                if (rnd.NextBool(.1))
-                {
-                    // Disable pooling
-                    connectionString = connectionString + ";Pooling=false;";
-                }
-                else if (rnd.NextBool(0.001))
-                {
-                    // Use a unique Application Name to get a new connection from a new pool. We do this in order to
-                    // stress the code that creates/deletes pools.
-                    connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, GetRandomApplicationName());
-
-                    // Tell DataStressConnection to call SqlConnection.ClearPool when closing the connection. This ensures
-                    // we do not keep a large number of connections in the pool that we will never use again.
-                    clearPoolBeforeClose = true;
-                }
-                else
-                {
-                    switch (CurrentPoolingStressMode)
-                    {
-                        case PoolingStressMode.RandomizeConnectionStrings:
-                            // Use one of the pre-generated Application Names in order to get a pooled connection with a randomized connection string
-                            connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, _applicationNames[rnd.Next(_applicationNames.Count)]);
-                            break;
-                        default:
-                            throw DataStressErrors.UnhandledCaseError(CurrentPoolingStressMode);
-                    }
-                }
-            }
-
-            // All options have been determined, now create
-            DbConnection con = DbFactory.CreateConnection();
-            con.ConnectionString = connectionString;
-            return new DataStressConnection(con, clearPoolBeforeClose);
-        }
-
-        [Flags]
-        public enum ConnectionStringOptions
-        {
-            Default = 0,
-
-            // by default, MARS is disabled
-            EnableMars = 0x2,
-
-            // by default, MultiSubnetFailover is enabled
-            DisableMultiSubnetFailover = 0x8
-        }
-
-        /// <summary>
-        /// Creates a new connection string.
-        /// Note: if rnd is null, create minimal connection string required to connect to the target database (used during setup)
-        /// Otherwise, string is randomized to enable multiple pools.
-        /// </summary>
-        public abstract string CreateBaseConnectionString(Random rnd, ConnectionStringOptions options);
-
-        protected virtual int GetNumDifferentApplicationNames()
-        {
-            return DataStressSettings.Instance.NumberOfConnectionPools;
-        }
-
-        private string GetRandomApplicationName()
-        {
-            return Guid.NewGuid().ToString();
-        }
-
-
-        /// <summary>
-        /// Returns index of a random table
-        /// This will be used to narrow down memory leaks
-        /// related to specific tables.
-        /// </summary>
-        public TableMetadata GetRandomTable(Random rnd)
-        {
-            return TableMetadataList[rnd.Next(TableMetadataList.Count)];
-        }
-
-        /// <summary>
-        /// Returns a random command object
-        /// </summary>
-        public DbCommand GetCommand(Random rnd, TableMetadata table, DataStressConnection conn, bool query, bool isXml = false)
-        {
-            if (query)
-            {
-                return GetSelectCommand(rnd, table, conn, isXml);
-            }
-            else
-            {
-                // make sure arguments are correct
-                DataStressErrors.Assert(!isXml, "wrong usage of GetCommand: cannot create command with FOR XML that is not query");
-
-                int select = rnd.Next(4);
-                switch (select)
-                {
-                    case 0:
-                        return GetUpdateCommand(rnd, table, conn);
-                    case 1:
-                        return GetInsertCommand(rnd, table, conn);
-                    case 2:
-                        return GetDeleteCommand(rnd, table, conn);
-                    default:
-                        return GetSelectCommand(rnd, table, conn);
-                }
-            }
-        }
-
-        private DbCommand CreateCommand(Random rnd, DataStressConnection conn)
-        {
-            DbCommand cmd;
-            if (conn == null)
-            {
-                cmd = DbFactory.CreateCommand();
-            }
-            else
-            {
-                cmd = conn.CreateCommand();
-            }
-
-            if (rnd != null)
-            {
-                cmd.CommandTimeout = rnd.NextBool() ? 30 : 600;
-            }
-
-            return cmd;
-        }
-
-        /// <summary>
-        /// Returns a random SELECT command
-        /// </summary>
-        public DbCommand GetSelectCommand(Random rnd, TableMetadata tableMetadata, DataStressConnection conn, bool isXml = false)
-        {
-            DbCommand com = CreateCommand(rnd, conn);
-            StringBuilder cmdText = new StringBuilder();
-            cmdText.Append(GetSelectCommandForMultipleRows(rnd, com, tableMetadata, isXml));
-
-            // 33% of the time, we also want to add another batch to the select command to allow for
-            // multiple result sets.
-            if ((!isXml) && (rnd.Next(0, 3) == 0))
-            {
-                cmdText.Append(";").Append(GetSelectCommandForScalarValue(com));
-            }
-
-            if ((!isXml) && ShouldModifySession(rnd))
-            {
-                cmdText.Append(";").Append(GetRandomSessionModificationStatement(rnd));
-            }
-
-            com.CommandText = cmdText.ToString();
-            return com;
-        }
-
-        /// <summary>
-        /// Returns a SELECT command that retrieves data from a table
-        /// </summary>
-        private string GetSelectCommandForMultipleRows(Random rnd, DbCommand com, TableMetadata inputTable, bool isXml)
-        {
-            int rowcount = rnd.Next(Depth);
-
-            StringBuilder cmdText = new StringBuilder();
-            cmdText.Append("SELECT TOP ");
-            cmdText.Append(rowcount); //Jonfo added this to prevent table scan of 75k row tables
-            cmdText.Append(" PrimaryKey");
-
-            List<TableColumn> columns = inputTable.Columns;
-            int colindex = rnd.Next(0, columns.Count);
-
-            for (int i = 0; i <= colindex; i++)
-            {
-                if (columns[i].ColumnName == "PrimaryKey") continue;
-                cmdText.Append(", ");
-                cmdText.Append(columns[i].ColumnName);
-            }
-
-            cmdText.Append(" FROM \"");
-            cmdText.Append(inputTable.TableName);
-            cmdText.Append("\" WITH(NOLOCK) WHERE PrimaryKey ");
-
-            // We randomly pick an operator from '>' or '=' to allow for randomization
-            // of possible rows returned by this query. This approach *may* help
-            // in reducing the likelihood of multiple threads accessing same rows.
-            // If multiple threads access same rows, there may be locking issues
-            // which may be avoided because of this randomization.
-            string op = rnd.NextBool() ? ">" : "=";
-            cmdText.Append(op).Append(" ");
-
-            string pName = GetParameterName("P0");
-            cmdText.Append(pName);
-
-            DbParameter param = DbFactory.CreateParameter();
-            param.ParameterName = pName;
-            param.Value = GetRandomPK(rnd, inputTable);
-            param.DbType = DbType.Int32;
-            com.Parameters.Add(param);
-
-            return cmdText.ToString();
-        }
-
-        /// <summary>
-        /// Returns a SELECT command that returns a single string parameter value.
-        /// </summary>
-        private string GetSelectCommandForScalarValue(DbCommand com)
-        {
-            string pName = GetParameterName("P1");
-            StringBuilder cmdText = new StringBuilder();
-
-            cmdText.Append("SELECT ").Append(pName);
-
-            DbParameter param = DbFactory.CreateParameter();
-            param.ParameterName = pName;
-            param.Value = LargeStringParam;
-            param.Size = LargeStringParam.Length;
-            param.DbType = DbType.String;
-            com.Parameters.Add(param);
-
-            return cmdText.ToString();
-        }
-
-        /// <summary>
-        /// Returns a random existing Primary Key value
-        /// </summary>
-        private int GetRandomPK(Random rnd, TableMetadata table)
-        {
-            using (DataStressConnection conn = CreateConnection())
-            {
-                conn.Open();
-
-                // This technique to get a random row comes from http://www.4guysfromrolla.com/webtech/042606-1.shtml
-                // When you set rowcount and then select into a scalar value, then the query is optimised so that
-                // just the last value is selected. So if n = ROWCOUNT then the query returns the n'th row.
-
-                int rowNumber = rnd.Next(Depth);
-
-                DbCommand com = conn.CreateCommand();
-                string cmdText = string.Format(
-                    @"SET ROWCOUNT {0};
-                          DECLARE @PK INT;
-                          SELECT @PK = PrimaryKey FROM {1} WITH(NOLOCK)
-                          SELECT @PK", rowNumber, table.TableName);
-
-                com.CommandText = cmdText;
-
-                object result = com.ExecuteScalarSyncOrAsync(CancellationToken.None, rnd).Result;
-                if (result == DBNull.Value)
-                {
-                    throw DataStressErrors.TestError(string.Format("Table {0} returned DBNull for primary key", table.TableName));
-                }
-                else
-                {
-                    int primaryKey = (int)result;
-                    return primaryKey;
-                }
-            }
-        }
-
-        private DbParameter CreateRandomParameter(Random rnd, string prefix, TableColumn column)
-        {
-            DbParameter param = DbFactory.CreateParameter();
-
-            param.ParameterName = GetParameterName(prefix);
-
-            param.Value = GetRandomData(rnd, column);
-
-            return param;
-        }
-
-        /// <summary>
-        /// Returns a random UPDATE command
-        /// </summary>
-        public DbCommand GetUpdateCommand(Random rnd, TableMetadata table, DataStressConnection conn)
-        {
-            DbCommand com = CreateCommand(rnd, conn);
-
-            StringBuilder cmdText = new StringBuilder();
-            cmdText.Append("UPDATE \"");
-            cmdText.Append(table.TableName);
-            cmdText.Append("\" SET ");
-
-            List<TableColumn> columns = table.Columns;
-            int numColumns = rnd.Next(2, columns.Count);
-            bool mostlyNull = rnd.NextBool(0.1); // 10% of rows have 90% chance of each column being null, in order to test nbcrow
-
-            for (int i = 0; i < numColumns; i++)
-            {
-                if (columns[i].ColumnName == "PrimaryKey") continue;
-                if (columns[i].ColumnName.ToUpper() == "TIMESTAMP_FLD") continue;
-
-                if (i > 1) cmdText.Append(", ");
-                cmdText.Append(columns[i].ColumnName);
-                cmdText.Append(" = ");
-
-                if (mostlyNull && rnd.NextBool(0.9))
-                {
-                    cmdText.Append("NULL");
-                }
-                else
-                {
-                    DbParameter param = CreateRandomParameter(rnd, string.Format("P{0}", (i + 1)), columns[i]);
-                    cmdText.Append(param.ParameterName);
-                    com.Parameters.Add(param);
-                }
-            }
-
-            cmdText.Append(" WHERE PrimaryKey = ");
-            string pName = GetParameterName("P0");
-            cmdText.Append(pName);
-            DbParameter keyParam = DbFactory.CreateParameter();
-            keyParam.ParameterName = pName;
-            keyParam.Value = GetRandomPK(rnd, table);
-            com.Parameters.Add(keyParam);
-
-            if (ShouldModifySession(rnd))
-            {
-                cmdText.Append(";").Append(GetRandomSessionModificationStatement(rnd));
-            }
-
-            com.CommandText = cmdText.ToString(); ;
-            return com;
-        }
-
-        /// <summary>
-        /// Returns a random INSERT command
-        /// </summary>
-        public DbCommand GetInsertCommand(Random rnd, TableMetadata table, DataStressConnection conn)
-        {
-            DbCommand com = CreateCommand(rnd, conn);
-
-            StringBuilder cmdText = new StringBuilder();
-            cmdText.Append("INSERT INTO \"");
-            cmdText.Append(table.TableName);
-            cmdText.Append("\" (");
-
-            StringBuilder valuesText = new StringBuilder();
-            valuesText.Append(") VALUES (");
-
-            List<TableColumn> columns = table.Columns;
-            int numColumns = rnd.Next(2, columns.Count);
-            bool mostlyNull = rnd.NextBool(0.1); // 10% of rows have 90% chance of each column being null, in order to test nbcrow
-
-            for (int i = 0; i < numColumns; i++)
-            {
-                if (columns[i].ColumnName.ToUpper() == "PRIMARYKEY") continue;
-
-                if (i > 1)
-                {
-                    cmdText.Append(", ");
-                    valuesText.Append(", ");
-                }
-
-                cmdText.Append(columns[i].ColumnName);
-
-                if (columns[i].ColumnName.ToUpper() == "TIMESTAMP_FLD")
-                {
-                    valuesText.Append("DEFAULT"); // Cannot insert an explicit value in a timestamp field
-                }
-                else if (mostlyNull && rnd.NextBool(0.9))
-                {
-                    valuesText.Append("NULL");
-                }
-                else
-                {
-                    DbParameter param = CreateRandomParameter(rnd, string.Format("P{0}", i + 1), columns[i]);
-
-                    valuesText.Append(param.ParameterName);
-                    com.Parameters.Add(param);
-                }
-            }
-
-            // To deal databases that do not support auto-incremented columns (Oracle?)
-            // if (!columns["PrimaryKey"].AutoIncrement)
-            if (PrimaryKeyValueIsRequired)
-            {
-                DbParameter param = CreateRandomParameter(rnd, "P0", table.GetColumn("PrimaryKey"));
-                cmdText.Append(", PrimaryKey");
-                valuesText.Append(", ");
-                valuesText.Append(param.ParameterName);
-                com.Parameters.Add(param);
-            }
-
-            valuesText.Append(")");
-            cmdText.Append(valuesText);
-
-            if (ShouldModifySession(rnd))
-            {
-                cmdText.Append(";").Append(GetRandomSessionModificationStatement(rnd));
-            }
-
-            com.CommandText = cmdText.ToString();
-            return com;
-        }
-
-        /// <summary>
-        /// Returns a random DELETE command
-        /// </summary>
-        public DbCommand GetDeleteCommand(Random rnd, TableMetadata table, DataStressConnection conn)
-        {
-            DbCommand com = CreateCommand(rnd, conn);
-
-            StringBuilder cmdText = new StringBuilder();
-            cmdText.Append("DELETE FROM \"");
-
-            List<TableColumn> columns = table.Columns;
-            string pName = GetParameterName("P0");
-            cmdText.Append(table.TableName);
-            cmdText.Append("\" WHERE PrimaryKey = ");
-            cmdText.Append(pName);
-
-            DbParameter param = DbFactory.CreateParameter();
-            param.ParameterName = pName;
-            param.Value = GetRandomPK(rnd, table);
-            com.Parameters.Add(param);
-
-            if (ShouldModifySession(rnd))
-            {
-                cmdText.Append(";").Append(GetRandomSessionModificationStatement(rnd));
-            }
-
-            com.CommandText = cmdText.ToString();
-            return com;
-        }
-
-        public bool ShouldModifySession(Random rnd)
-        {
-            // 33% of the time, we want to modify the user session on the server
-            return rnd.NextBool(.33);
-        }
-
-        /// <summary>
-        /// Returns a random statement that will modify the session on the server.
-        /// </summary>
-        public string GetRandomSessionModificationStatement(Random rnd)
-        {
-            string sessionStmt = null;
-            int select = rnd.Next(3);
-            switch (select)
-            {
-                case 0:
-                    // Create a SET CONTEXT_INFO statement using a hex string of random data
-                    StringBuilder sb = new StringBuilder("0x");
-                    int count = rnd.Next(1, 129);
-                    for (int i = 0; i < count; i++)
-                    {
-                        sb.AppendFormat("{0:x2}", (byte)rnd.Next(0, (int)(byte.MaxValue + 1)));
-                    }
-                    string contextInfoData = sb.ToString();
-                    sessionStmt = string.Format("SET CONTEXT_INFO {0}", contextInfoData);
-                    break;
-
-                case 1:
-                    // Create or drop the temp table
-                    sessionStmt = string.Format("IF OBJECT_ID('tempdb..{0}') IS NULL CREATE TABLE {0}(id INT) ELSE DROP TABLE {0}", s_tempTableName);
-                    break;
-
-                default:
-                    // Create a SET LANGUAGE statement
-                    sessionStmt = string.Format("SET LANGUAGE N'{0}'", s_languages[rnd.Next(s_languages.Length)]);
-                    break;
-            }
-            return sessionStmt;
-        }
-
-        /// <summary>
-        /// Returns random data
-        /// </summary>
-        public object GetRandomData(Random rnd, TableColumn column)
-        {
-            int length = column.MaxLength;
-            int maxTargetLength = (length > 255 || length == -1) ? 255 : length;
-
-            DbType dbType = GetDbType(column);
-            return GetRandomData(rnd, dbType, maxTargetLength);
-        }
-
-        private DbType GetDbType(TableColumn column)
-        {
-            switch (column.ColumnName)
-            {
-                case "bit_FLD": return DbType.Boolean;
-                case "tinyint_FLD": return DbType.Byte;
-                case "smallint_FLD": return DbType.Int16;
-                case "int_FLD": return DbType.Int32;
-                case "PrimaryKey": return DbType.Int32;
-                case "bigint_FLD": return DbType.Int64;
-                case "real_FLD": return DbType.Single;
-                case "float_FLD": return DbType.Double;
-                case "smallmoney_FLD": return DbType.Decimal;
-                case "money_FLD": return DbType.Decimal;
-                case "decimal_FLD": return DbType.Decimal;
-                case "numeric_FLD": return DbType.Decimal;
-                case "datetime_FLD": return DbType.DateTime;
-                case "smalldatetime_FLD": return DbType.DateTime;
-                case "datetime2_FLD": return DbType.DateTime2;
-                case "timestamp_FLD": return DbType.Binary;
-                case "date_FLD": return DbType.Date;
-                case "time_FLD": return DbType.Time;
-                case "datetimeoffset_FLD": return DbType.DateTimeOffset;
-                case "uniqueidentifier_FLD": return DbType.Guid;
-                case "sql_variant_FLD": return DbType.Object;
-                case "image_FLD": return DbType.Binary;
-                case "varbinary_FLD": return DbType.Binary;
-                case "binary_FLD": return DbType.Binary;
-                case "char_FLD": return DbType.String;
-                case "varchar_FLD": return DbType.String;
-                case "text_FLD": return DbType.String;
-                case "ntext_FLD": return DbType.String;
-                case "nvarchar_FLD": return DbType.String;
-                case "nchar_FLD": return DbType.String;
-                case "nvarcharmax_FLD": return DbType.String;
-                case "varbinarymax_FLD": return DbType.Binary;
-                case "varcharmax_FLD": return DbType.String;
-                case "xml_FLD": return DbType.Xml;
-                default: throw DataStressErrors.UnhandledCaseError(column.ColumnName);
-            }
-        }
-
-        protected virtual object GetRandomData(Random rnd, DbType dbType, int maxLength)
-        {
-            byte[] buffer;
-            switch (dbType)
-            {
-                case DbType.Boolean:
-                    return (rnd.Next(2) == 0 ? false : true);
-                case DbType.Byte:
-                    return rnd.Next(byte.MinValue, byte.MaxValue + 1);
-                case DbType.Int16:
-                    return rnd.Next(short.MinValue, short.MaxValue + 1);
-                case DbType.Int32:
-                    return (rnd.Next(2) == 0 ? int.MaxValue / rnd.Next(1, 3) : int.MinValue / rnd.Next(1, 3));
-                case DbType.Int64:
-                    return (rnd.Next(2) == 0 ? long.MaxValue / rnd.Next(1, 3) : long.MinValue / rnd.Next(1, 3));
-                case DbType.Single:
-                    return rnd.NextDouble() * (rnd.Next(2) == 0 ? float.MaxValue : float.MinValue);
-                case DbType.Double:
-                    return rnd.NextDouble() * (rnd.Next(2) == 0 ? double.MaxValue : double.MinValue);
-                case DbType.Decimal:
-                    return rnd.Next(short.MinValue, short.MaxValue + 1);
-                case DbType.DateTime:
-                case DbType.DateTime2:
-                    return DateTime.Now;
-                case DbType.Date:
-                    return DateTime.Now.Date;
-                case DbType.Time:
-                    return DateTime.Now.TimeOfDay.ToString("c");
-                case DbType.DateTimeOffset:
-                    return DateTimeOffset.Now;
-                case DbType.Guid:
-                    buffer = new byte[16];
-                    rnd.NextBytes(buffer);
-                    return (new Guid(buffer));
-                case DbType.Object:
-                case DbType.Binary:
-                    rnd.NextBytes(buffer = new byte[rnd.Next(1, maxLength)]);
-                    return buffer;
-                case DbType.String:
-                case DbType.Xml:
-                    string openTag = "<Data>";
-                    string closeTag = "</Data>";
-                    int tagLength = openTag.Length + closeTag.Length;
-
-                    if (tagLength > maxLength)
-                    {
-                        // Case (1): tagLength > maxTargetLength
-                        return "";
-                    }
-                    else
-                    {
-                        StringBuilder builder = new StringBuilder(maxLength);
-
-                        builder.Append(openTag);
-
-                        // The data is just a repeat of one character because to the managed provider
-                        // it is only really the length that matters, not the content of the data
-                        char characterToUse = (char)rnd.Next((int)'@', (int)'~');  // Choosing random characters in this range to avoid special
-                                                                                   // xml chars like '<' or '&'
-                        int numRepeats = rnd.Next(0, maxLength - tagLength); // Case (2): tagLength == maxTargetLength
-                                                                             // Case (3): tagLength < maxTargetLength <-- most common
-                        builder.Append(characterToUse, numRepeats);
-
-                        builder.Append(closeTag);
-
-                        DataStressErrors.Assert(builder.Length <= maxLength, "Incorrect length of randomly generated string");
-
-                        return builder.ToString();
-                    }
-                default:
-                    throw DataStressErrors.UnhandledCaseError(dbType);
-            }
-        }
-
-        #region Table information to be used by stress
-
-        // method used to create stress tables in the database
-        protected void BuildUserTables(List<TableMetadata> TableMetadataList)
-        {
-            string CreateTable1 =
-            "CREATE TABLE stress_test_table_1 (PrimaryKey int identity(1,1) primary key, int_FLD int, smallint_FLD smallint, real_FLD real, float_FLD float, decimal_FLD decimal(28,4), " +
-            "smallmoney_FLD smallmoney, bit_FLD bit, tinyint_FLD tinyint, uniqueidentifier_FLD uniqueidentifier, varbinary_FLD varbinary(756), binary_FLD binary(756), " +
-            "image_FLD image, varbinarymax_FLD varbinary(max), timestamp_FLD timestamp, char_FLD char(756), text_FLD text, varcharmax_FLD varchar(max), " +
-            "varchar_FLD varchar(756), nchar_FLD nchar(756), ntext_FLD ntext, nvarcharmax_FLD nvarchar(max), nvarchar_FLD nvarchar(756), datetime_FLD datetime, " +
-            "smalldatetime_FLD smalldatetime);" +
-            "CREATE UNIQUE INDEX stress_test_table_1 on stress_test_table_1 ( PrimaryKey );" +
-            "insert into stress_test_table_1(int_FLD, smallint_FLD, real_FLD, float_FLD, decimal_FLD, " +
-            "smallmoney_FLD, bit_FLD, tinyint_FLD, uniqueidentifier_FLD, varbinary_FLD, binary_FLD, " +
-            "image_FLD, varbinarymax_FLD, char_FLD, text_FLD, varcharmax_FLD, " +
-            "varchar_FLD, nchar_FLD, ntext_FLD, nvarcharmax_FLD, nvarchar_FLD, datetime_FLD, " +
-            "smalldatetime_FLD) values ( 0, 0, 0, 0, 0, $0, 0, 0, '00000000-0000-0000-0000-000000000000', " +
-            "0x00, 0x00, 0x00, 0x00, '0', '0', '0', '0', N'0', N'0', N'0', N'0', '01/11/2000 12:54:01', '01/11/2000 12:54:00' );"
-            ;
-
-            string CreateTable2 =
-            "CREATE TABLE stress_test_table_2 (PrimaryKey int identity(1,1) primary key, bigint_FLD bigint, money_FLD money, numeric_FLD numeric, " +
-            "time_FLD time, date_FLD date, datetimeoffset_FLD datetimeoffset, sql_variant_FLD sql_variant, " +
-            "datetime2_FLD datetime2, xml_FLD xml);" +
-            "CREATE UNIQUE INDEX stress_test_table_2 on stress_test_table_2 ( PrimaryKey );" +
-            "insert into stress_test_table_2(bigint_FLD, money_FLD, numeric_FLD, " +
-            "time_FLD, date_FLD, datetimeoffset_FLD, sql_variant_FLD, " +
-            "datetime2_FLD, xml_FLD) values ( 0, $0, 0, '01/11/2015 12:54:01', '01/11/2015 12:54:01', '01/11/2000 12:54:01 -08:00', 0, '01/11/2000 12:54:01', '0' );"
-            ;
-
-            if (TableMetadataList == null)
-            {
-                TableMetadataList = new List<TableMetadata>();
-            }
-
-            List<TableColumn> tableColumns1 = new List<TableColumn>();
-            tableColumns1.Add(new TableColumn("PrimaryKey", -1));
-            tableColumns1.Add(new TableColumn("int_FLD", -1));
-            tableColumns1.Add(new TableColumn("smallint_FLD", -1));
-            tableColumns1.Add(new TableColumn("real_FLD", -1));
-            tableColumns1.Add(new TableColumn("float_FLD", -1));
-            tableColumns1.Add(new TableColumn("decimal_FLD", -1));
-            tableColumns1.Add(new TableColumn("smallmoney_FLD", -1));
-            tableColumns1.Add(new TableColumn("bit_FLD", -1));
-            tableColumns1.Add(new TableColumn("tinyint_FLD", -1));
-            tableColumns1.Add(new TableColumn("uniqueidentifier_FLD", -1));
-            tableColumns1.Add(new TableColumn("varbinary_FLD", 756));
-            tableColumns1.Add(new TableColumn("binary_FLD", 756));
-            tableColumns1.Add(new TableColumn("image_FLD", -1));
-            tableColumns1.Add(new TableColumn("varbinarymax_FLD", -1));
-            tableColumns1.Add(new TableColumn("timestamp_FLD", -1));
-            tableColumns1.Add(new TableColumn("char_FLD", -1));
-            tableColumns1.Add(new TableColumn("text_FLD", -1));
-            tableColumns1.Add(new TableColumn("varcharmax_FLD", -1));
-            tableColumns1.Add(new TableColumn("varchar_FLD", 756));
-            tableColumns1.Add(new TableColumn("nchar_FLD", 756));
-            tableColumns1.Add(new TableColumn("ntext_FLD", -1));
-            tableColumns1.Add(new TableColumn("nvarcharmax_FLD", -1));
-            tableColumns1.Add(new TableColumn("nvarchar_FLD", 756));
-            tableColumns1.Add(new TableColumn("datetime_FLD", -1));
-            tableColumns1.Add(new TableColumn("smalldatetime_FLD", -1));
-            TableMetadata tableMeta1 = new TableMetadata("stress_test_table_1", tableColumns1);
-            TableMetadataList.Add(tableMeta1);
-
-            List<TableColumn> tableColumns2 = new List<TableColumn>();
-            tableColumns2.Add(new TableColumn("PrimaryKey", -1));
-            tableColumns2.Add(new TableColumn("bigint_FLD", -1));
-            tableColumns2.Add(new TableColumn("money_FLD", -1));
-            tableColumns2.Add(new TableColumn("numeric_FLD", -1));
-            tableColumns2.Add(new TableColumn("time_FLD", -1));
-            tableColumns2.Add(new TableColumn("date_FLD", -1));
-            tableColumns2.Add(new TableColumn("datetimeoffset_FLD", -1));
-            tableColumns2.Add(new TableColumn("sql_variant_FLD", -1));
-            tableColumns2.Add(new TableColumn("datetime2_FLD", -1));
-            tableColumns2.Add(new TableColumn("xml_FLD", -1));
-            TableMetadata tableMeta2 = new TableMetadata("stress_test_table_2", tableColumns2);
-            TableMetadataList.Add(tableMeta2);
-
-            using (DataStressConnection conn = CreateConnection(null))
-            {
-                conn.Open();
-                using (DbCommand com = conn.CreateCommand())
-                {
-                    try
-                    {
-                        com.CommandText = CreateTable1;
-                        com.ExecuteNonQuery();
-                    }
-                    catch (DbException de)
-                    {
-                        // This can be improved by doing a Drop Table if exists.
-                        if (de.Message.Contains("There is already an object named \'" + tableMeta1.TableName + "\' in the database."))
-                        {
-                            CleanupUserTables(tableMeta1);
-                            com.ExecuteNonQuery();
-                        }
-                        else
-                        {
-                            throw de;
-                        }
-                    }
-
-                    try
-                    {
-                        com.CommandText = CreateTable2;
-                        com.ExecuteNonQuery();
-                    }
-                    catch (DbException de)
-                    {
-                        // This can be improved by doing a Drop Table if exists in the query itself.
-                        if (de.Message.Contains("There is already an object named \'" + tableMeta2.TableName + "\' in the database."))
-                        {
-                            CleanupUserTables(tableMeta2);
-                            com.ExecuteNonQuery();
-                        }
-                        else
-                        {
-                            throw de;
-                        }
-                    }
-
-                    for (int i = 0; i < Depth; i++)
-                    {
-                        TrackedRandom randomInstance = new TrackedRandom();
-                        randomInstance.Mark();
-
-                        DbCommand comInsert1 = GetInsertCommand(randomInstance, tableMeta1, conn);
-                        comInsert1.ExecuteNonQuery();
-
-                        DbCommand comInsert2 = GetInsertCommand(randomInstance, tableMeta2, conn);
-                        comInsert2.ExecuteNonQuery();
-                    }
-                }
-            }
-        }
-
-        // method used to delete stress tables in the database
-        protected void CleanupUserTables(TableMetadata tableMetadata)
-        {
-            string DropTable = "drop TABLE " + tableMetadata.TableName + ";";
-
-            using (DataStressConnection conn = CreateConnection(null))
-            {
-                conn.Open();
-                using (DbCommand com = conn.CreateCommand())
-                {
-                    try
-                    {
-                        com.CommandText = DropTable;
-                        com.ExecuteNonQuery();
-                    }
-                    catch (Exception) { }
-                }
-            }
-        }
-
-        public List<TableMetadata> TableMetadataList
-        {
-            get;
-            private set;
-        }
-
-        public class TableMetadata
-        {
-            private string _tableName;
-            private List<TableColumn> _columns = new List<TableColumn>();
-
-            public TableMetadata(string tbleName, List<TableColumn> cols)
-            {
-                _tableName = tbleName;
-                _columns = cols;
-            }
-
-            public string TableName
-            {
-                get { return _tableName; }
-            }
-
-            public List<TableColumn> Columns
-            {
-                get { return _columns; }
-            }
-
-            public TableColumn GetColumn(string colName)
-            {
-                foreach (TableColumn column in _columns)
-                {
-                    if (column.ColumnName.Equals(colName))
-                    {
-                        return column;
-                    }
-                }
-                return null;
-            }
-        }
-
-        public class TableColumn
-        {
-            private string _columnName;
-            private int _maxLength;
-
-            public TableColumn(string colName, int maxLen)
-            {
-                _columnName = colName;
-                _maxLength = maxLen;
-            }
-
-            public string ColumnName
-            {
-                get { return _columnName; }
-            }
-
-            public int MaxLength
-            {
-                get { return _maxLength; }
-            }
-        }
-
-        private List<string> _applicationNames;
-
-        /// <summary>
-        /// Gets schema of all tables from the back-end database and fills
-        /// the m_Tables DataSet with this schema. This DataSet is used to
-        /// generate random command text for tests.
-        /// </summary>
-        public void InitializeSharedData(DataSource source)
-        {
-            Trace.WriteLine("Creating shared objects", this.ToString());
-
-            // Initialize m_sharedDataSet
-            TableMetadataList = new List<TableMetadata>();
-            BuildUserTables(TableMetadataList);
-
-            // Initialize m_applicationNames
-            _applicationNames = new List<string>();
-            for (int i = 0; i < GetNumDifferentApplicationNames(); i++)
-            {
-                _applicationNames.Add(GetRandomApplicationName());
-            }
-
-            // Initialize CurrentPoolingStressMode
-            CurrentPoolingStressMode = PoolingStressMode.RandomizeConnectionStrings;
-
-
-            Trace.WriteLine("Finished creating shared objects", this.ToString());
-        }
-
-        public void CleanupSharedData()
-        {
-            foreach (TableMetadata meta in TableMetadataList)
-            {
-                CleanupUserTables(meta);
-            }
-            TableMetadataList = null;
-        }
-
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressReader.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressReader.cs
deleted file mode 100644 (file)
index f9127c8..0000000
+++ /dev/null
@@ -1,350 +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.Xml;
-using System.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Stress.Data
-{
-    public class DataStressReader : IDisposable
-    {
-        #region Type method mapping
-
-        private static Dictionary<Type, Func<DataStressReader, int, CancellationToken, Random, Task<object>>> s_sqlTypes;
-        private static Dictionary<Type, Func<DataStressReader, int, CancellationToken, Random, Task<object>>> s_clrTypes;
-
-        static DataStressReader()
-        {
-            InitSqlTypes();
-            InitClrTypes();
-        }
-
-        private static void InitSqlTypes()
-        {
-            s_sqlTypes = new Dictionary<Type, Func<DataStressReader, int, CancellationToken, Random, Task<object>>>();
-
-            s_sqlTypes.Add(typeof(SqlBinary), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlBinary>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlBoolean), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlBoolean>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlByte), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlByte>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlBytes), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlBytes>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlChars), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlChars>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlDateTime), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlDateTime>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlDecimal), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlDecimal>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlDouble), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlDouble>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlGuid), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlGuid>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlInt16), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlInt16>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlInt32), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlInt32>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlInt64), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlInt64>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlMoney), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlMoney>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlSingle), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlSingle>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlString), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlString>(ordinal, token, rnd));
-            s_sqlTypes.Add(typeof(SqlXml), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<SqlXml>(ordinal, token, rnd));
-        }
-
-        private static void InitClrTypes()
-        {
-            s_clrTypes = new Dictionary<Type, Func<DataStressReader, int, CancellationToken, Random, Task<object>>>();
-
-            s_clrTypes.Add(typeof(bool), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Boolean>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(byte), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Byte>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(short), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Int16>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(int), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Int32>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(long), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Int64>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(float), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Single>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(double), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Double>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(string), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<String>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(char), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Char>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(decimal), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Decimal>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(Guid), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<Guid>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(DateTime), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<DateTime>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(TimeSpan), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<TimeSpan>(ordinal, token, rnd));
-            s_clrTypes.Add(typeof(DateTimeOffset), (reader, ordinal, token, rnd) => reader.GetFieldValueSyncOrAsync<DateTimeOffset>(ordinal, token, rnd));
-        }
-
-        #endregion
-
-        private readonly DbDataReader _reader;
-        private SemaphoreSlim _closeAsyncSemaphore;
-
-        public DataStressReader(DbDataReader internalReader)
-        {
-            _reader = internalReader;
-        }
-
-        public void Close()
-        {
-            _reader.Dispose();
-        }
-
-        public void Dispose()
-        {
-            _reader.Dispose();
-            if (_closeAsyncSemaphore != null) _closeAsyncSemaphore.Dispose();
-        }
-
-        public Task CloseAsync()
-        {
-            _closeAsyncSemaphore = new SemaphoreSlim(1);
-            return Task.Run(() => ExecuteWithCloseAsyncSemaphore(Close));
-        }
-
-        /// <summary>
-        /// Executes the action while holding the CloseAsync Semaphore.
-        /// This MUST be used for reader.Close() and all methods that are not safe to call at the same time as reader.Close(), i.e. all sync methods.
-        /// Otherwise we will see AV's.
-        /// </summary>
-        public void ExecuteWithCloseAsyncSemaphore(Action a)
-        {
-            try
-            {
-                if (_closeAsyncSemaphore != null) _closeAsyncSemaphore.Wait();
-                a();
-            }
-            finally
-            {
-                if (_closeAsyncSemaphore != null) _closeAsyncSemaphore.Release();
-            }
-        }
-
-        /// <summary>
-        /// Executes the action while holding the CloseAsync Semaphore.
-        /// This MUST be used for reader.Close() and all methods that are not safe to call at the same time as reader.Close(), i.e. all sync methods.
-        /// Otherwise we will see AV's.
-        /// </summary>
-        public T ExecuteWithCloseAsyncSemaphore<T>(Func<T> f)
-        {
-            try
-            {
-                if (_closeAsyncSemaphore != null) _closeAsyncSemaphore.Wait();
-                return f();
-            }
-            finally
-            {
-                if (_closeAsyncSemaphore != null) _closeAsyncSemaphore.Release();
-            }
-        }
-
-        #region SyncOrAsync methods
-
-        public Task<bool> ReadSyncOrAsync(CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                () => ExecuteWithCloseAsyncSemaphore(() => _reader.Read()),
-                () => ExecuteWithCloseAsyncSemaphore(() => _reader.ReadAsync(token)),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public Task<bool> NextResultSyncOrAsync(CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                () => ExecuteWithCloseAsyncSemaphore(() => _reader.NextResult()),
-                () => ExecuteWithCloseAsyncSemaphore(() => _reader.NextResultAsync(token)),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public Task<bool> IsDBNullSyncOrAsync(int ordinal, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                () => ExecuteWithCloseAsyncSemaphore(() => _reader.IsDBNull(ordinal)),
-                () => ExecuteWithCloseAsyncSemaphore(() => _reader.IsDBNullAsync(ordinal, token)),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public Task<object> GetValueSyncOrAsync(int ordinal, CancellationToken token, Random rnd)
-        {
-            if (rnd.NextBool(0.3))
-            {
-                // Use sync-only GetValue
-                return Task.FromResult(GetValue(ordinal));
-            }
-            else
-            {
-                // Use GetFieldValue or GetFieldValueAsync
-                Func<DataStressReader, int, CancellationToken, Random, Task<object>> getFieldValueFunc = null;
-
-                if (rnd.NextBool())
-                {
-                    // Choose provider-specific getter
-                    Type sqlType = GetProviderSpecificFieldType(ordinal);
-                    s_sqlTypes.TryGetValue(sqlType, out getFieldValueFunc);
-                }
-                else
-                {
-                    // Choose clr type getter
-                    Type clrType = GetFieldType(ordinal);
-                    s_clrTypes.TryGetValue(clrType, out getFieldValueFunc);
-                }
-
-                if (getFieldValueFunc != null)
-                {
-                    // Execute the type-specific func, e.g. GetFieldValue<int> or GetFieldValueAsync<int>
-                    return getFieldValueFunc(this, ordinal, token, rnd);
-                }
-                else
-                {
-                    // Execute GetFieldValue<object> or GetFieldValueAsync<object> as a fallback
-                    return GetFieldValueSyncOrAsync<object>(ordinal, token, rnd);
-                }
-            }
-        }
-
-        private Task<object> GetFieldValueSyncOrAsync<T>(int ordinal, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod<object>(
-                () => ExecuteWithCloseAsyncSemaphore(() => _reader.GetFieldValue<T>(ordinal)),
-                async () => ((object)(await ExecuteWithCloseAsyncSemaphore(() => _reader.GetFieldValueAsync<T>(ordinal, token)))),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        #endregion
-
-        #region Sync-only methods
-
-        public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length)
-        {
-            return ExecuteWithCloseAsyncSemaphore(() => _reader.GetBytes(ordinal, dataOffset, buffer, bufferOffset, length));
-        }
-
-        public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length)
-        {
-            return ExecuteWithCloseAsyncSemaphore(() => _reader.GetChars(ordinal, dataOffset, buffer, bufferOffset, length));
-        }
-
-        public Type GetFieldType(int ordinal)
-        {
-            return ExecuteWithCloseAsyncSemaphore(() => _reader.GetFieldType(ordinal));
-        }
-
-        public string GetName(int ordinal)
-        {
-            return ExecuteWithCloseAsyncSemaphore(() => _reader.GetName(ordinal));
-        }
-
-        public Type GetProviderSpecificFieldType(int ordinal)
-        {
-            return ExecuteWithCloseAsyncSemaphore(() => _reader.GetProviderSpecificFieldType(ordinal));
-        }
-
-
-        public DataStressStream GetStream(int ordinal)
-        {
-            Stream s = ExecuteWithCloseAsyncSemaphore(() => _reader.GetStream(ordinal));
-            return new DataStressStream(s, this);
-        }
-
-        public DataStressTextReader GetTextReader(int ordinal)
-        {
-            TextReader t = ExecuteWithCloseAsyncSemaphore(() => _reader.GetTextReader(ordinal));
-            return new DataStressTextReader(t, this);
-        }
-
-        public DataStressXmlReader GetXmlReader(int ordinal)
-        {
-            XmlReader x = ExecuteWithCloseAsyncSemaphore(() => ((SqlDataReader)_reader).GetXmlReader(ordinal));
-            return new DataStressXmlReader(x, this);
-        }
-
-        public object GetValue(int ordinal)
-        {
-            return ExecuteWithCloseAsyncSemaphore(() => _reader.GetValue(ordinal));
-        }
-
-        public int FieldCount
-        {
-            get { return ExecuteWithCloseAsyncSemaphore(() => _reader.FieldCount); }
-        }
-
-        #endregion
-    }
-
-    public class DataStressStream : IDisposable
-    {
-        private Stream _stream;
-        private DataStressReader _reader;
-
-        public DataStressStream(Stream stream, DataStressReader reader)
-        {
-            _stream = stream;
-            _reader = reader;
-        }
-
-        public void Dispose()
-        {
-            _stream.Dispose();
-        }
-
-        public Task<int> ReadSyncOrAsync(byte[] buffer, int offset, int count, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                () => _reader.ExecuteWithCloseAsyncSemaphore(() => _stream.Read(buffer, offset, count)),
-                () => _reader.ExecuteWithCloseAsyncSemaphore(() => _stream.ReadAsync(buffer, offset, count)),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-    }
-
-    public class DataStressTextReader : IDisposable
-    {
-        private TextReader _textReader;
-        private DataStressReader _reader;
-
-        public DataStressTextReader(TextReader textReader, DataStressReader reader)
-        {
-            _textReader = textReader;
-            _reader = reader;
-        }
-
-        public void Dispose()
-        {
-            _textReader.Dispose();
-        }
-
-        public int Peek()
-        {
-            return _reader.ExecuteWithCloseAsyncSemaphore(() => _textReader.Peek());
-        }
-
-        public Task<int> ReadSyncOrAsync(char[] buffer, int index, int count, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                () => _reader.ExecuteWithCloseAsyncSemaphore(() => _textReader.Read(buffer, index, count)),
-                () => _reader.ExecuteWithCloseAsyncSemaphore(() => _textReader.ReadAsync(buffer, index, count)),
-                AsyncUtils.ChooseSyncAsyncMode(rnd));
-        }
-    }
-
-    public class DataStressXmlReader : IDisposable
-    {
-        private XmlReader _xmlReader;
-        private DataStressReader _reader;
-
-        public DataStressXmlReader(XmlReader xmlReader, DataStressReader reader)
-        {
-            _xmlReader = xmlReader;
-            _reader = reader;
-        }
-
-        public void Dispose()
-        {
-            _xmlReader.Dispose();
-        }
-
-        public void Read()
-        {
-            _reader.ExecuteWithCloseAsyncSemaphore(() => _xmlReader.Read());
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressSettings.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressSettings.cs
deleted file mode 100644 (file)
index 0b5fcf9..0000000
+++ /dev/null
@@ -1,305 +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.Data.SqlClient;
-using System.Diagnostics;
-using System.Linq;
-using System.Text;
-
-namespace Stress.Data
-{
-    /// <summary>
-    /// Loads dataStressSettings section from Stress.Data.Framework.dll.config (App.config in source tree)
-    /// </summary>
-    public class DataStressSettings
-    {
-
-        internal static readonly string s_configFileName = "StressTest.config";
-
-        // use Instance to access the settings
-        private DataStressSettings()
-        {
-        }
-
-        private bool Initialized { get; set; }
-
-        private DataStressConfigurationSection _dataStressSettings = new DataStressConfigurationSection();
-
-        // list of sources read from the config file
-        private Dictionary<string, DataSource> _sources = new Dictionary<string, DataSource>(StringComparer.CurrentCultureIgnoreCase);
-        public ErrorHandlingAction ActionOnProductError
-        {
-            get;
-            private set;
-        }
-        public ErrorHandlingAction ActionOnTestError
-        {
-            get;
-            private set;
-        }
-        public ErrorHandlingAction ActionOnProgrammingError
-        {
-            get;
-            private set;
-        }
-
-        public int NumberOfConnectionPools
-        {
-            get;
-            private set;
-        }
-
-        // singleton instance, lazy evaluation
-        private static DataStressSettings s_instance = new DataStressSettings();
-        public static DataStressSettings Instance
-        {
-            get
-            {
-                if (!s_instance.Initialized)
-                {
-                    lock (s_instance)
-                    {
-                        if (!s_instance.Initialized)
-                        {
-                            s_instance.Load();
-                        }
-                    }
-                }
-                return s_instance;
-            }
-        }
-
-        #region Configuration file handlers
-
-        private class DataStressConfigurationSection
-        {
-            private List<DataSourceElement> _sources = new List<DataSourceElement>();
-            private ErrorHandlingPolicyElement _errorHandlingPolicy = new ErrorHandlingPolicyElement();
-            private ConnectionPoolPolicyElement _connectionPoolPolicy = new ConnectionPoolPolicyElement();
-
-            StressConfigReader reader = new StressConfigReader(s_configFileName);
-
-            public List<DataSourceElement> Sources
-            {
-                get
-                {
-                    if (_sources.Count == 0)
-                    {
-                        reader.Load();
-                        _sources = reader.Sources;
-                    }
-                    return _sources;
-                }
-            }
-
-            public ErrorHandlingPolicyElement ErroHandlingPolicy
-            {
-                get
-                {
-                    return _errorHandlingPolicy;
-                }
-            }
-
-            public ConnectionPoolPolicyElement ConnectionPoolPolicy
-            {
-                get
-                {
-                    return _connectionPoolPolicy;
-                }
-            }
-        }
-
-
-        internal class DataSourceElement
-        {
-            private string _name;
-            private string _type;
-            private bool _isDefault = false;
-
-            public readonly Dictionary<string, string> SourceProperties = new Dictionary<string, string>();
-
-
-            public DataSourceElement(string ds_name,
-                                    string ds_type,
-                                    string ds_server,
-                                    string ds_datasource,
-                                    string ds_database,
-                                    string ds_user,
-                                    string ds_password,
-                                    bool ds_isDefault = false,
-                                    bool ds_winAuth = false,
-                                    bool ds_isLocal = false,
-                                    string ds_dbFile = null,
-                                    bool disableMultiSubnetFailoverSetup = true,
-                                    bool disableNamedPipes = true)
-            {
-                _name = ds_name;
-                _type = ds_type;
-                _isDefault = ds_isDefault;
-
-                if (ds_server != null)
-                {
-                    SourceProperties.Add("server", ds_server);
-                }
-                if (ds_datasource != null)
-                {
-                    SourceProperties.Add("dataSource", ds_datasource);
-                }
-                if (ds_database != null)
-                {
-                    SourceProperties.Add("database", ds_database);
-                }
-                if (ds_user != null)
-                {
-                    SourceProperties.Add("user", ds_user);
-                }
-                if (ds_password != null)
-                {
-                    SourceProperties.Add("password", ds_password);
-                }
-
-                SourceProperties.Add("supportsWindowsAuthentication", ds_winAuth.ToString());
-                SourceProperties.Add("islocal", ds_isLocal.ToString());
-
-                SourceProperties.Add("DisableMultiSubnetFailoverSetup", disableMultiSubnetFailoverSetup.ToString());
-
-                SourceProperties.Add("DisableNamedPipes", disableNamedPipes.ToString());
-
-
-                if (ds_dbFile != null)
-                {
-                    SourceProperties.Add("databaseFile", ds_dbFile);
-                }
-            }
-
-            public string Name
-            {
-                get { return _name; }
-            }
-
-            public string Type
-            {
-                get { return _type; }
-            }
-
-            public bool IsDefault
-            {
-                get { return _isDefault; }
-            }
-        }
-
-        private class ErrorHandlingPolicyElement
-        {
-            private string _onProductError = "debugBreak";
-            private string _onTestError = "throwException";
-            private string _onProgrammingError = "debugBreak";
-
-            public string OnProductError
-            {
-                get
-                {
-                    return _onProductError;
-                }
-            }
-
-            public string OnTestError
-            {
-                get
-                {
-                    return _onTestError;
-                }
-            }
-
-            public string OnProgrammingError
-            {
-                get
-                {
-                    return _onProgrammingError;
-                }
-            }
-        }
-
-        private class ConnectionPoolPolicyElement
-        {
-            private int _numberOfPools = 10;
-
-            public int NumberOfPools
-            {
-                get
-                {
-                    return _numberOfPools;
-                }
-            }
-        }
-
-        #endregion
-
-        /// <summary>
-        /// loads the configuration data from the app config file (Stress.Data.Framework.dll.config) and initializes the Sources collection
-        /// </summary>
-        private void Load()
-        {
-            // Parse <sources>
-            foreach (DataSourceElement sourceElement in _dataStressSettings.Sources)
-            {
-                // if Parse raises exception, check that the type attribute is set to the relevant the SourceType enumeration value name
-                DataSourceType sourceType = (DataSourceType)Enum.Parse(typeof(DataSourceType), sourceElement.Type, true);
-
-                DataSource newSource = DataSource.Create(sourceElement.Name, sourceType, sourceElement.IsDefault, sourceElement.SourceProperties);
-                _sources.Add(newSource.Name, newSource);
-            }
-
-            // Parse <errorhandlingpolicy>
-            // if Parse raises exception, check that the action attribute is set to a valid ActionOnProductBugFound enumeration value name
-            this.ActionOnProductError = (ErrorHandlingAction)Enum.Parse(typeof(ErrorHandlingAction), _dataStressSettings.ErroHandlingPolicy.OnProductError, true);
-            this.ActionOnTestError = (ErrorHandlingAction)Enum.Parse(typeof(ErrorHandlingAction), _dataStressSettings.ErroHandlingPolicy.OnTestError, true);
-            this.ActionOnProgrammingError = (ErrorHandlingAction)Enum.Parse(typeof(ErrorHandlingAction), _dataStressSettings.ErroHandlingPolicy.OnProgrammingError, true);
-
-            // Parse <connectionPoolPolicy>
-            this.NumberOfConnectionPools = _dataStressSettings.ConnectionPoolPolicy.NumberOfPools;
-
-            this.Initialized = true;
-        }
-
-
-        /// <summary>
-        /// use this method to retrieve the source data by its name (represented with 'name' attribute in config file)
-        /// </summary>
-        /// <param name="name">case-sensitive name</param>
-        public DataSource GetSourceByName(string name)
-        {
-            return _sources[name];
-        }
-
-        /// <summary>
-        /// Use this method to retrieve the default source associated with the type specified.
-        /// The type of the node is specified with 'type' attribute on the sources file - see DataSourceType enum for list of supported types.
-        /// If there is a source node with isDefault=true, this node is returned (first one found in config file).
-        /// Otherwise, first source node from type specified is returned.
-        /// </summary>
-        public DataSource GetDefaultSourceByType(DataSourceType type)
-        {
-            DataSource defaultSource = null;
-            foreach (DataSource source in _sources.Values)
-            {
-                if (source.Type == type)
-                {
-                    if (defaultSource == null)
-                    {
-                        // use the first found source, if default is not set
-                        defaultSource = source;
-                    }
-                    else if (source.IsDefault)
-                    {
-                        defaultSource = source;
-                        break;
-                    }
-                }
-            }
-            return defaultSource;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataTestGroup.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataTestGroup.cs
deleted file mode 100644 (file)
index b29851c..0000000
+++ /dev/null
@@ -1,698 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-
-using DPStressHarness;
-
-namespace Stress.Data
-{
-    /// <summary>
-    ///  basic set of tests to run on each managed provider
-    /// </summary>
-    public abstract class DataTestGroup
-    {
-        // random is not thread-safe, create one per thread - use RandomInstance to access it.
-        // note that each thread and each test method has a different instance of this object, so it
-        // doesn't need to be synchronised or have [ThreadStatic], etc
-        private TrackedRandom _randomInstance = new TrackedRandom();
-        protected Random RandomInstance
-        {
-            get
-            {
-                _randomInstance.Mark();
-                return _randomInstance;
-            }
-        }
-
-        /// <summary>
-        /// Test factory to use for generation of connection strings and other test objects. Factory is initialized during setup.
-        /// null is not returned - if setup was not called yet, exception is raised
-        /// This is static so that is shared across all threads (since stresstest will create a new DataTestGroup object for each thread)
-        /// </summary>
-        private static DataStressFactory s_factory;
-        public static DataStressFactory Factory
-        {
-            get
-            {
-                DataStressErrors.Assert(s_factory != null, "Tried to access DataTestGroup.Factory before Setup has been called");
-                return s_factory;
-            }
-        }
-
-        /// <summary>
-        /// This method is called to create the stress factory used to create connections, commands, etc...
-        /// Implementation should set the source and the scenario to valid values if inputs are null/empty.
-        /// </summary>
-        /// <param name="scenario">Scenario string specified by the user or empty to set default</param>
-        /// <param name="dataSource">DataSource string specified by the user or empty to use connection string as is, useful when developing new tests</param>
-        protected abstract DataStressFactory CreateFactory(ref string scenario, ref DataSource source);
-
-        /// <summary>
-        /// scenario to run, initialized in setup
-        /// null is not returned - if setup was not called yet, exception is raised
-        /// This is static so that is shared across all threads (since stresstest will create a new DataTestGroup object for each thread)
-        /// </summary>
-        private static string s_scenario;
-        protected static string Scenario
-        {
-            get
-            {
-                DataStressErrors.Assert(s_scenario != null, "Tried to access DataTestGroup.Scenario before Setup has been called");
-                return s_scenario;
-            }
-        }
-
-        /// <summary>
-        /// data source information used by stress, initialized in Setup
-        /// null is not returned - if setup was not called yet, exception is raised
-        /// This is static so that is shared across all threads (since stresstest will create a new DataTestGroup object for each thread)
-        /// </summary>
-        private static DataSource s_source;
-        protected static DataSource Source
-        {
-            get
-            {
-                DataStressErrors.Assert(s_source != null, "Tried to access DataTestGroup.Source before Setup has been called");
-                return s_source;
-            }
-        }
-
-
-        /// <summary>
-        /// Does test setup that is shared across all threads. This method will be called only once, before
-        /// any [TestSetup] methods are called.
-        /// If you override this method you must call base.GlobalTestSetup() at the beginning.
-        /// </summary>
-        [GlobalTestSetup]
-        public virtual void GlobalTestSetup()
-        {
-            // Preconditions - ensure this setup is only called once
-            DataStressErrors.Assert(string.IsNullOrEmpty(s_scenario), "Scenario was already set");
-            DataStressErrors.Assert(s_source == null, "Source was already set");
-            DataStressErrors.Assert(s_factory == null, "Factory was already set");
-
-            // Set m_scenario
-            string userProvidedScenario;
-            TestMetrics.Overrides.TryGetValue("scenario", out userProvidedScenario);
-            // Empty means default scenario for the test group
-            s_scenario = (userProvidedScenario ?? string.Empty);
-            s_scenario = s_scenario.ToUpperInvariant();
-
-            // Set m_source
-            // Empty means that test group will peek the default data source from the config file based on the scenario
-            string userProvidedSourceName;
-            if (TestMetrics.Overrides.TryGetValue("source", out userProvidedSourceName))
-            {
-                s_source = DataStressSettings.Instance.GetSourceByName(userProvidedSourceName);
-            }
-
-            // Set m_factory
-            s_factory = CreateFactory(ref s_scenario, ref s_source);
-            s_factory.InitializeSharedData(s_source);
-
-            // Postconditions
-            DataStressErrors.Assert(!string.IsNullOrEmpty(s_scenario), "Scenario was not set");
-            DataStressErrors.Assert(s_source != null, "Source was not set");
-            DataStressErrors.Assert(s_factory != null, "Factory was not set");
-        }
-
-        /// <summary>
-        /// Does test cleanup that is shared across all threads. This method will not be called until all
-        /// threads have finished executing [StressTest] methods. This method will be called only once.
-        /// If you override this method you must call base.GlobalTestSetup() at the beginning.
-        /// </summary>
-        [GlobalTestCleanup]
-        public virtual void GlobalTestCleanup()
-        {
-            s_factory.CleanupSharedData();
-            s_source = null;
-            s_scenario = null;
-            s_factory.Dispose();
-            s_factory = null;
-        }
-
-
-        protected bool OpenConnection(DataStressConnection conn)
-        {
-            try
-            {
-                conn.Open();
-                return true;
-            }
-            catch (Exception e)
-            {
-                if (IsServerNotAccessibleException(e, conn.DbConnection.ConnectionString, conn.DbConnection.DataSource))
-                {
-                    // Ignore this exception.
-                    // This exception will fire when using named pipes with MultiSubnetFailover option set to true.
-                    // MultiSubnetFailover=true only works with TCP/IP protocol and will result in exception when using with named pipes.
-                    return false;
-                }
-                else
-                {
-                    throw e;
-                }
-            }
-        }
-
-
-        [GlobalExceptionHandler]
-        public virtual void GlobalExceptionHandler(Exception e)
-        {
-        }
-
-        /// <summary>
-        /// Returns whether or not the datareader should be closed
-        /// </summary>
-        protected virtual bool ShouldCloseDataReader()
-        {
-            // Ignore commandCancelled, instead randomly close it 9/10 of the time
-            return RandomInstance.Next(10) != 0;
-        }
-
-
-        #region CommandExecute and Consume methods
-
-        /// <summary>
-        /// Utility function used by command tests
-        /// </summary>
-        protected virtual void CommandExecute(Random rnd, DbCommand com, bool query)
-        {
-            AsyncUtils.WaitAndUnwrapException(CommandExecuteAsync(rnd, com, query));
-        }
-
-        protected async virtual Task CommandExecuteAsync(Random rnd, DbCommand com, bool query)
-        {
-            CancellationTokenSource cts = null;
-
-            // Cancel 1/10 commands
-            Task cancelTask = null;
-            bool cancelCommand = rnd.NextBool(0.1);
-            if (cancelCommand)
-            {
-                if (rnd.NextBool())
-                {
-                    // Use DbCommand.Cancel
-                    cancelTask = Task.Run(() => CommandCancel(com));
-                }
-                else
-                {
-                    // Use CancellationTokenSource
-                    if (cts == null) cts = new CancellationTokenSource();
-                    cancelTask = Task.Run(() => cts.Cancel());
-                }
-            }
-
-            // Get the CancellationToken
-            CancellationToken token = (cts != null) ? cts.Token : CancellationToken.None;
-
-            DataStressReader reader = null;
-            try
-            {
-                if (query)
-                {
-                    CommandBehavior commandBehavior = CommandBehavior.Default;
-                    if (rnd.NextBool(0.5)) commandBehavior |= CommandBehavior.SequentialAccess;
-                    if (rnd.NextBool(0.25)) commandBehavior |= CommandBehavior.KeyInfo;
-                    if (rnd.NextBool(0.1)) commandBehavior |= CommandBehavior.SchemaOnly;
-
-                    // Get the reader
-                    reader = new DataStressReader(await com.ExecuteReaderSyncOrAsync(commandBehavior, token, rnd));
-
-                    // Consume the reader's data
-                    await ConsumeReaderAsync(reader, commandBehavior.HasFlag(CommandBehavior.SequentialAccess), token, rnd);
-                }
-                else
-                {
-                    await com.ExecuteNonQuerySyncOrAsync(token, rnd);
-                }
-            }
-            catch (Exception e)
-            {
-                if (cancelCommand && IsCommandCancelledException(e))
-                {
-                    // Catch command canceled exception
-                }
-                else
-                {
-                    throw;
-                }
-            }
-            finally
-            {
-                if (cancelTask != null) AsyncUtils.WaitAndUnwrapException(cancelTask);
-                if (reader != null && ShouldCloseDataReader()) reader.Close();
-            }
-        }
-
-        /// <summary>
-        /// Utility function to consume a reader in a random fashion
-        /// </summary>
-        protected virtual async Task ConsumeReaderAsync(DataStressReader reader, bool sequentialAccess, CancellationToken token, Random rnd)
-        {
-            // Close 1/10 of readers while they are reading
-            Task closeTask = null;
-            if (AllowReaderCloseDuringReadAsync() && rnd.NextBool(0.1))
-            {
-                // Begin closing now on another thread
-                closeTask = reader.CloseAsync();
-            }
-
-            try
-            {
-                do
-                {
-                    while (await reader.ReadSyncOrAsync(token, rnd))
-                    {
-                        // Optionally stop reading the current result set
-                        if (rnd.NextBool(0.1)) break;
-
-                        // Read the current row
-                        await ConsumeRowAsync(reader, sequentialAccess, token, rnd);
-                    }
-
-                    // Executing NextResult only 50% of the time
-                    if (rnd.NextBool())
-                        break;
-                } while (await reader.NextResultSyncOrAsync(token, rnd));
-            }
-            catch (Exception e)
-            {
-                if (closeTask != null && IsReaderClosedException(e))
-                {
-                    // Catch reader closed exception
-                }
-                else
-                {
-                    throw;
-                }
-            }
-            finally
-            {
-                if (closeTask != null) AsyncUtils.WaitAndUnwrapException(closeTask);
-            }
-        }
-
-        /// <summary>
-        /// Utility function to consume a single row of a reader in a random fashion after Read/ReadAsync has been invoked.
-        /// </summary>
-        protected virtual async Task ConsumeRowAsync(DataStressReader reader, bool sequentialAccess, CancellationToken token, Random rnd)
-        {
-            for (int i = 0; i < reader.FieldCount; i++)
-            {
-                if (rnd.Next(10) == 0) break; // stop reading from this row
-                if (rnd.Next(2) == 0) continue; // skip this field
-                bool hasBeenRead = false;
-
-                // If the field is not null, we can optionally use streaming API
-                if ((!await reader.IsDBNullSyncOrAsync(i, token, rnd)) && (rnd.NextBool()))
-                {
-                    Type t = reader.GetFieldType(i);
-                    if (t == typeof(byte[]))
-                    {
-                        await ConsumeBytesAsync(reader, i, token, rnd);
-                        hasBeenRead = true;
-                    }
-                    else if (t == typeof(string))
-                    {
-                        await ConsumeCharsAsync(reader, i, token, rnd);
-                        hasBeenRead = true;
-                    }
-                }
-
-                // If the field has not yet been read, or if it is non-sequential then we can re-read it
-                if ((!hasBeenRead) || (!sequentialAccess))
-                {
-                    if (!await reader.IsDBNullSyncOrAsync(i, token, rnd))
-                    {
-                        // Field value is not null, we can use new GetFieldValue<T> methods
-                        await reader.GetValueSyncOrAsync(i, token, rnd);
-                    }
-                    else
-                    {
-                        // Field value is null, we have to use old GetValue method
-                        reader.GetValue(i);
-                    }
-                }
-
-                // Do IsDBNull check again with 50% probability
-                if (rnd.NextBool()) await reader.IsDBNullSyncOrAsync(i, token, rnd);
-            }
-        }
-
-        protected virtual async Task ConsumeBytesAsync(DataStressReader reader, int i, CancellationToken token, Random rnd)
-        {
-            byte[] buffer = new byte[255];
-
-            if (rnd.NextBool())
-            {
-                // We can optionally use GetBytes
-                reader.GetBytes(i, rnd.Next(20), buffer, rnd.Next(20), rnd.Next(200));
-            }
-            else if (reader.GetName(i) != "timestamp_FLD")
-            {
-                // Timestamp appears to be binary, but cannot be read by Stream
-                DataStressStream stream = reader.GetStream(i);
-                await stream.ReadSyncOrAsync(buffer, rnd.Next(20), rnd.Next(200), token, rnd);
-            }
-            else
-            {
-                // It is timestamp column, so read it later with GetValueSyncOrAsync
-                await reader.GetValueSyncOrAsync(i, token, rnd);
-            }
-        }
-
-        protected virtual async Task ConsumeCharsAsync(DataStressReader reader, int i, CancellationToken token, Random rnd)
-        {
-            char[] buffer = new char[255];
-
-            if (rnd.NextBool())
-            {
-                // Read with GetChars
-                reader.GetChars(i, rnd.Next(20), buffer, rnd.Next(20), rnd.Next(200));
-            }
-            else if (reader.GetProviderSpecificFieldType(i) == typeof(SqlXml))
-            {
-                // SqlClient only: Xml is read by XmlReader
-                DataStressXmlReader xmlReader = reader.GetXmlReader(i);
-                xmlReader.Read();
-            }
-            else
-            {
-                // Read with TextReader
-                DataStressTextReader textReader = reader.GetTextReader(i);
-                if (rnd.NextBool())
-                {
-                    textReader.Peek();
-                }
-                await textReader.ReadSyncOrAsync(buffer, rnd.Next(20), rnd.Next(200), rnd);
-                if (rnd.NextBool())
-                {
-                    textReader.Peek();
-                }
-            }
-        }
-
-        /// <summary>
-        /// Returns true if the given exception is expected for the current provider when a command is cancelled by another thread.
-        /// </summary>
-        /// <param name="e"></param>
-        protected virtual bool IsCommandCancelledException(Exception e)
-        {
-            return e is TaskCanceledException;
-        }
-
-        /// <summary>
-        /// Returns true if the given exception is expected for the current provider when trying to read from a reader that has been closed
-        /// </summary>
-        /// <param name="e"></param>
-        protected virtual bool IsReaderClosedException(Exception e)
-        {
-            return false;
-        }
-
-        /// <summary>
-        /// Returns true if the given exception is expected for the current provider when trying to connect to unavailable/non-existent server
-        /// </summary>
-        /// <param name="e"></param>
-        protected bool IsServerNotAccessibleException(Exception e, string connString, string dataSource)
-        {
-            return
-                e is ArgumentException &&
-                connString.Contains("MultiSubnetFailover=True") &&
-                dataSource.Contains("np:") &&
-                e.Message.Contains("Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol.");
-        }
-
-        /// <summary>
-        /// Returns true if the backend provider supports closing a datareader while asynchronously reading from it
-        /// </summary>
-        /// <returns></returns>
-        protected virtual bool AllowReaderCloseDuringReadAsync()
-        {
-            return false;
-        }
-
-        /// <summary>
-        /// Thread Callback function which cancels queries using DbCommand.Cancel()
-        /// </summary>
-        /// <param name="cmd"></param>
-        protected void CommandCancel(object o)
-        {
-            try
-            {
-                DbCommand cmd = (DbCommand)o;
-                cmd.Cancel();
-            }
-            catch (Exception ex)
-            {
-                Trace.WriteLine(ex.ToString(), this.ToString());
-            }
-        }
-
-        #endregion
-
-        #region Command and Parameter Tests
-
-        /// <summary>
-        /// Command Reader Test: Executes a simple SELECT statement without parameters
-        /// </summary>
-        [StressTest("TestCommandReader", Weight = 10)]
-        public void TestCommandReader()
-        {
-            Random rnd = RandomInstance;
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                DbCommand com = Factory.GetCommand(rnd, table, conn, true);
-                CommandExecute(rnd, com, true);
-            }
-        }
-
-        /// <summary>
-        /// Command Select Test: Executes a single SELECT statement with parameters
-        /// </summary>
-        [StressTest("TestCommandSelect", Weight = 10)]
-        public void TestCommandSelect()
-        {
-            Random rnd = RandomInstance;
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                DbCommand com = Factory.GetSelectCommand(rnd, table, conn);
-                CommandExecute(rnd, com, true);
-            }
-        }
-
-        /// <summary>
-        /// Command Insert Test: Executes a single INSERT statement with parameters
-        /// </summary>
-        [StressTest("TestCommandInsert", Weight = 10)]
-        public void TestCommandInsert()
-        {
-            Random rnd = RandomInstance;
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                DbCommand com = Factory.GetInsertCommand(rnd, table, conn);
-                CommandExecute(rnd, com, false);
-            }
-        }
-
-        /// <summary>
-        /// Command Update Test: Executes a single UPDATE statement with parameters
-        /// </summary>
-        [StressTest("TestCommandUpdate", Weight = 10)]
-        public void TestCommandUpdate()
-        {
-            Random rnd = RandomInstance;
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                DbCommand com = Factory.GetUpdateCommand(rnd, table, conn);
-                CommandExecute(rnd, com, false);
-            }
-        }
-
-        /// <summary>
-        /// Command Update Test: Executes a single DELETE statement with parameters
-        /// </summary>
-        [StressTest("TestCommandDelete", Weight = 10)]
-        public void TestCommandDelete()
-        {
-            Random rnd = RandomInstance;
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                DbCommand com = Factory.GetDeleteCommand(rnd, table, conn);
-                CommandExecute(rnd, com, false);
-            }
-        }
-
-        [StressTest("TestCommandTimeout", Weight = 10)]
-        public void TestCommandTimeout()
-        {
-            Random rnd = RandomInstance;
-            DataStressConnection conn = null;
-            try
-            {
-                // Use a transaction 50% of the time
-                if (rnd.NextBool())
-                {
-                }
-
-                // Create a select command
-                conn = Factory.CreateConnection(rnd);
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                DbCommand com = Factory.GetSelectCommand(rnd, table, conn);
-
-                // Setup timeout. We want to see various possibilities of timeout happening before, after, or at the same time as when the result comes in.
-                int delay = rnd.Next(0, 10); // delay is from 0 to 9 seconds inclusive
-                int timeout = rnd.Next(1, 10); // timeout is from 1 to 9 seconds inclusive
-                com.CommandText += string.Format("; WAITFOR DELAY '00:00:0{0}'", delay);
-                com.CommandTimeout = timeout;
-
-                // Execute command and catch timeout exception
-                try
-                {
-                    CommandExecute(rnd, com, true);
-                }
-                catch (DbException e)
-                {
-                    if (e is SqlException && ((SqlException)e).Number == 3989)
-                    {
-                        throw DataStressErrors.ProductError("Timing issue between OnTimeout and ReadAsyncCallback results in SqlClient's packet parsing going out of sync", e);
-                    }
-                    else if (!e.Message.ToLower().Contains("timeout"))
-                    {
-                        throw;
-                    }
-                }
-            }
-            finally
-            {
-                if (conn != null) conn.Dispose();
-            }
-        }
-
-        [StressTest("TestCommandAndReaderAsync", Weight = 10)]
-        public void TestCommandAndReaderAsync()
-        {
-            // Since we're calling an "async" method, we need to do a Wait() here.
-            AsyncUtils.WaitAndUnwrapException(TestCommandAndReaderAsyncInternal());
-        }
-
-        /// <summary>
-        /// Utility method to test Async scenario using await keyword
-        /// </summary>
-        /// <returns></returns>
-        protected virtual async Task TestCommandAndReaderAsyncInternal()
-        {
-            Random rnd = RandomInstance;
-            using (DataStressConnection conn = Factory.CreateConnection(rnd))
-            {
-                if (!OpenConnection(conn)) return;
-                DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                DbCommand com;
-
-                com = Factory.GetInsertCommand(rnd, table, conn);
-                await CommandExecuteAsync(rnd, com, false);
-
-                com = Factory.GetDeleteCommand(rnd, table, conn);
-                await CommandExecuteAsync(rnd, com, false);
-
-                com = Factory.GetSelectCommand(rnd, table, conn);
-                await com.ExecuteScalarAsync();
-
-                com = Factory.GetSelectCommand(rnd, table, conn);
-                await CommandExecuteAsync(rnd, com, true);
-            }
-        }
-
-        /// <summary>
-        /// Utility function used by MARS tests
-        /// </summary>
-        private void TestCommandMARS(Random rnd, bool query)
-        {
-            if (Source.Type != DataSourceType.SqlServer)
-                return; // skip for non-SQL Server databases
-
-            using (DataStressConnection conn = Factory.CreateConnection(rnd, DataStressFactory.ConnectionStringOptions.EnableMars))
-            {
-                if (!OpenConnection(conn)) return;
-                DbCommand[] commands = new DbCommand[rnd.Next(5, 10)];
-                List<Task> tasks = new List<Task>();
-                // Create commands
-                for (int i = 0; i < commands.Length; i++)
-                {
-                    DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd);
-                    commands[i] = Factory.GetCommand(rnd, table, conn, query);
-                }
-
-                try
-                {
-                    // Execute commands
-                    for (int i = 0; i < commands.Length; i++)
-                    {
-                        if (rnd.NextBool(0.7))
-                            tasks.Add(CommandExecuteAsync(rnd, commands[i], query));
-                        else
-                            CommandExecute(rnd, commands[i], query);
-                    }
-                }
-                finally
-                {
-                    // All commands must be complete before closing the connection
-                    AsyncUtils.WaitAll(tasks.ToArray());
-                }
-            }
-        }
-
-        /// <summary>
-        /// Command MARS Test: Tests MARS by executing multiple readers on same connection
-        /// </summary>
-        [StressTest("TestCommandMARSRead", Weight = 10)]
-        public void TestCommandMARSRead()
-        {
-            Random rnd = RandomInstance;
-            TestCommandMARS(rnd, true);
-        }
-
-        /// <summary>
-        /// Command MARS Test: Tests MARS by getting multiple connection objects from same connection
-        /// </summary>
-        [StressTest("TestCommandMARSWrite", Weight = 10)]
-        public void TestCommandMARSWrite()
-        {
-            Random rnd = RandomInstance;
-            TestCommandMARS(rnd, false);
-        }
-
-        #endregion
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/Extensions.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/Extensions.cs
deleted file mode 100644 (file)
index a480fb4..0000000
+++ /dev/null
@@ -1,94 +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.Data;
-using System.Data.Common;
-using System.Data.SqlClient;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Xml;
-
-namespace Stress.Data
-{
-    public static class Extensions
-    {
-        /// <param name="probability">the probability that true will be returned</param>
-        public static bool NextBool(this Random rnd, double probability)
-        {
-            return rnd.NextDouble() < probability;
-        }
-
-        /// <summary>
-        /// Generate a true or false with equal probability.
-        /// </summary>
-        public static bool NextBool(this Random rnd)
-        {
-            return rnd.NextBool(0.5);
-        }
-
-        public static Task<int> ExecuteNonQuerySyncOrAsync(this DbCommand command, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                command.ExecuteNonQuery,
-                () => command.ExecuteNonQueryAsync(token),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public static Task<object> ExecuteScalarSyncOrAsync(this DbCommand command, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                command.ExecuteScalar,
-                () => command.ExecuteScalarAsync(token),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public static Task<DbDataReader> ExecuteReaderSyncOrAsync(this DbCommand command, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                command.ExecuteReader,
-                () => command.ExecuteReaderAsync(token),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public static Task<DbDataReader> ExecuteReaderSyncOrAsync(this DbCommand command, CommandBehavior cb, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                () => command.ExecuteReader(cb),
-                () => command.ExecuteReaderAsync(cb, token),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public static Task<SqlDataReader> ExecuteReaderSyncOrAsync(this SqlCommand command, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                command.ExecuteReader,
-                () => command.ExecuteReaderAsync(token),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public static Task<SqlDataReader> ExecuteReaderSyncOrAsync(this SqlCommand command, CommandBehavior cb, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                () => command.ExecuteReader(cb),
-                () => command.ExecuteReaderAsync(cb, token),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-
-        public static Task<XmlReader> ExecuteXmlReaderSyncOrAsync(this SqlCommand command, CancellationToken token, Random rnd)
-        {
-            return AsyncUtils.SyncOrAsyncMethod(
-                command.ExecuteXmlReader,
-                () => command.ExecuteXmlReaderAsync(token),
-                AsyncUtils.ChooseSyncAsyncMode(rnd)
-                );
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/StressConfigReader.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/StressConfigReader.cs
deleted file mode 100644 (file)
index 5200108..0000000
+++ /dev/null
@@ -1,83 +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.Generic;
-using System.IO;
-using System.Xml;
-using System.Xml.XPath;
-using static Stress.Data.DataStressSettings;
-
-namespace Stress.Data
-{
-    /// <summary>
-    /// Reads the configuration from a configuration file and provides the configuration
-    /// </summary>
-    internal class StressConfigReader
-    {
-        private string _configFilePath;
-        private const string dataStressSettings = "dataStressSettings";
-        private const string sourcePath = "//dataStressSettings/sources/source";
-        internal List<DataSourceElement> Sources
-        {
-            get; private set;
-        }
-
-        public StressConfigReader(string configFilePath)
-        {
-            this._configFilePath = configFilePath;
-        }
-
-        internal void Load()
-        {
-            XmlReader reader = null;
-            try {
-                Sources = new List<DataSourceElement>();
-                reader = CreateReader();
-
-                XPathDocument xpathDocument = new XPathDocument(reader);
-
-                XPathNavigator navigator = xpathDocument.CreateNavigator();
-
-                XPathNodeIterator sourceIterator = navigator.Select(sourcePath);
-
-                foreach (XPathNavigator sourceNavigator in sourceIterator)
-                {
-                    string nsUri = sourceNavigator.NamespaceURI;
-                    string sourceName = sourceNavigator.GetAttribute("name", nsUri);
-                    string sourceType = sourceNavigator.GetAttribute("type", nsUri);
-                    bool isDefault;
-                    isDefault = bool.TryParse(sourceNavigator.GetAttribute("isDefault", nsUri), out isDefault) ? isDefault : false;
-                    string dataSource = sourceNavigator.GetAttribute("dataSource", nsUri);
-                    string user = sourceNavigator.GetAttribute("user", nsUri);
-                    string password = sourceNavigator.GetAttribute("password", nsUri);
-                    string database = sourceNavigator.GetAttribute("database", nsUri);
-                    bool supportsWindowsAuthentication;
-                    supportsWindowsAuthentication = bool.TryParse(sourceNavigator.GetAttribute("supportsWindowsAuthentication", nsUri), out supportsWindowsAuthentication) ? supportsWindowsAuthentication : false;
-                    bool isLocal;
-                    isLocal = bool.TryParse(sourceNavigator.GetAttribute("isLocal", nsUri), out isLocal) ? isLocal : false;
-                    bool disableMultiSubnetFailover;
-                    disableMultiSubnetFailover = bool.TryParse(sourceNavigator.GetAttribute("disableMultiSubnetFailover", nsUri), out disableMultiSubnetFailover) ? disableMultiSubnetFailover : false;
-                    bool disableNamedPipes;
-                    disableMultiSubnetFailover = bool.TryParse(sourceNavigator.GetAttribute("disableNamedPipes", nsUri), out disableNamedPipes) ? disableNamedPipes : false;
-
-                    DataSourceElement element = new DataSourceElement(sourceName, sourceType, null, dataSource, database, user, password, ds_isDefault: isDefault, ds_isLocal: isLocal, disableMultiSubnetFailoverSetup: disableMultiSubnetFailover, disableNamedPipes: disableNamedPipes);
-                    Sources.Add(element);
-                }
-            }
-            finally
-            {
-                reader.Dispose();
-            }
-        }
-
-        private XmlReader CreateReader()
-        {
-            FileStream configurationStream = new FileStream(this._configFilePath, FileMode.Open);
-            XmlReaderSettings settings = new XmlReaderSettings();
-            settings.DtdProcessing = DtdProcessing.Prohibit;
-            XmlReader reader = XmlReader.Create(configurationStream, settings);
-            return reader;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/StressTest.config b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/StressTest.config
deleted file mode 100644 (file)
index c343a4a..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<configuration>
-  <dataStressSettings>
-    <sources>
-      <source
-        name="LocalSqlServer"
-        type="SqlServer"
-        isDefault="true"
-        dataSource="(local)"
-        database="stress"
-        user="stress"
-        password=""
-        supportsWindowsAuthentication="false"
-        islocal='true'
-        disableMultiSubnetFailover = 'true'
-        disableNamedPipes = 'true'> 
-      </source>
-    </sources>
-  </dataStressSettings>
-</configuration>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/System.Data.StressFramework.csproj b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/System.Data.StressFramework.csproj
deleted file mode 100644 (file)
index 76649bd..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <RootNamespace>Stress.Data</RootNamespace>
-    <Configurations>$(NetCoreAppCurrent)-Unix-Debug;$(NetCoreAppCurrent)-Unix-Release;$(NetCoreAppCurrent)-Windows_NT-Debug;$(NetCoreAppCurrent)-Windows_NT-Release;$(NetFrameworkCurrent)-Windows_NT-Debug;$(NetFrameworkCurrent)-Windows_NT-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\System.Data.StressRunner\System.Data.StressRunner.csproj" />
-    <Compile Include="AsyncUtils.cs" />
-    <Compile Include="DataSource.cs" />
-    <Compile Include="DataStressConnection.cs" />
-    <Compile Include="DataStressErrors.cs" />
-    <Compile Include="DataStressFactory.cs" />
-    <Compile Include="DataStressReader.cs" />
-    <Compile Include="DataStressSettings.cs" />
-    <Compile Include="DataTestGroup.cs" />
-    <Compile Include="Extensions.cs" />
-    <Compile Include="StressConfigReader.cs" />
-    <Compile Include="TrackedRandom.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="StressTest.config">
-      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
-    </None>
-  </ItemGroup>
-  <PropertyGroup Condition=" '$(TargetsWindows)' != 'true' ">
-    <DefineConstants>$(DefineConstants);PROJECTK</DefineConstants>
-  </PropertyGroup>
-  <!--Import the targets-->
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/TrackedRandom.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/TrackedRandom.cs
deleted file mode 100644 (file)
index 669a645..0000000
+++ /dev/null
@@ -1,184 +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;
-
-namespace Stress.Data
-{
-    /// <summary>
-    /// Random number generator that tracks information necessary to reproduce a sequence of random numbers.
-    /// </summary>
-    /// <remarks>
-    /// There are three items maintained by instances of this class
-    /// that are used to assist in the reproduction of a sequence of generated numbers:
-    ///
-    /// 1. The seed used for initialization.
-    /// 2. The count of numbers generated.
-    /// 3. Markers to indicate relevant points in the sequence.
-    ///
-    /// For tests that use random numbers to control execution,
-    /// these tracked items can be used to help determine the specific code path that was executed.
-    /// Here's an example:
-    ///
-    /// A test starts to execute, and retrieves an instance of this class.
-    /// If an instance of this class has not been created beforehand, it is constructed and the *seed* is stored.
-    /// The test inserts a *marker* to track the *count* of numbers generated before the test starts its work.
-    /// As the test executes, it asks for a sequence of random numbers.  At some point, the test causes a crash.
-    /// Using the resulting dump (or live debugging session if available), it is possible to examine an instance
-    /// of this class to recreate the sequence of numbers used by the test.
-    /// You can create an instance of a Random offline using the tracked *seed*,
-    /// and generate numbers up to the *marked* count to determine the starting point for the sequence of numbers used by the test.
-    /// The length of the sequence is indicated by the last *count* of number generated.
-    /// So for a failed test, you can use the numbers from Mark+1 to Count to retrace the code path taken by the test.
-    ///
-    /// Instances of this class keep track of a finite number of multiple marks,
-    /// so it is possible to track the beginning and end of a series of tests,
-    /// assuming they all mark at least the start of their execution.
-    /// </remarks>
-    public class TrackedRandom : Random
-    {
-        private readonly int _seed;
-
-        /// <summary>
-        /// Number of random numbers generated.
-        /// </summary>
-        private long _count;
-
-        /// <summary>
-        /// Circular buffer to track the most recent marks that indicate the count at the time a given mark was created.
-        /// </summary>
-        private readonly long[] _marks = new long[16];
-
-        /// <summary>
-        /// Index of where to place next mark in buffer.
-        /// This index is incremented after each mark, and wraps around as necessary.
-        /// </summary>
-        private int _nextMark;
-
-        private const int EmptyMark = -1;
-
-        public TrackedRandom()
-            : this(Environment.TickCount)
-        {
-        }
-
-        public TrackedRandom(int seed)
-            : base(seed)
-        {
-            _seed = seed;
-
-            for (int i = 0; i < _marks.Length; i++)
-            {
-                _marks[i] = EmptyMark;
-            }
-        }
-
-        public int Seed
-        {
-            get
-            {
-                return _seed;
-            }
-        }
-
-        public long Count
-        {
-            get
-            {
-                return _count;
-            }
-        }
-
-        public void Mark()
-        {
-            long mark = _count;
-
-            // marking forward
-            _marks[_nextMark++] = mark;
-
-            // wrap when necessary
-            if (_nextMark == _marks.Length)
-            {
-                _nextMark = 0;
-            }
-        }
-
-        /// <summary>
-        /// Return an enumerable that can be used to iterate over the most recent marks,
-        /// starting from the most recent, and ending with the earliest mark still being tracked.
-        /// </summary>
-        public IEnumerable<long> Marks
-        {
-            get
-            {
-                // Iterate backwards through the mark array,
-                // starting just before the index of the next mark,
-                // and ending at the next mark.
-                // Iteration stops earlier if an empty mark is found.
-                int index;
-                long mark;
-
-                for (int i = 1; i <= _marks.Length; i++)
-                {
-                    // Index of current element determined by:
-                    // ((L+n) - i) % L
-                    // where
-                    // L is the length of the array,
-                    // n is the index of where to insert the next mark, 0 <= n < L,
-                    // i is the current iteration variable value, 0 < i <= L.
-                    index = (_marks.Length + _nextMark - i) % _marks.Length;
-                    mark = _marks[index];
-
-                    if (mark == EmptyMark)
-                    {
-                        break;
-                    }
-
-                    yield return mark;
-                }
-            }
-        }
-
-        private void IncrementCount()
-        {
-            if (_count == long.MaxValue)
-            {
-                _count = -1;
-            }
-
-            ++_count;
-        }
-
-        public override int Next()
-        {
-            IncrementCount();
-            return base.Next();
-        }
-
-        public override int Next(int minValue, int maxValue)
-        {
-            IncrementCount();
-            return base.Next(minValue, maxValue);
-        }
-
-        public override int Next(int maxValue)
-        {
-            IncrementCount();
-            return base.Next(maxValue);
-        }
-
-        public override void NextBytes(byte[] buffer)
-        {
-            IncrementCount();
-            base.NextBytes(buffer);
-        }
-
-        public override double NextDouble()
-        {
-            IncrementCount();
-            return base.NextDouble();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Configurations.props b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Configurations.props
deleted file mode 100644 (file)
index f350311..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      $(NetCoreAppCurrent)-Unix;
-      $(NetCoreAppCurrent)-Windows_NT;
-      $(NetFrameworkCurrent)-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Constants.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Constants.cs
deleted file mode 100644 (file)
index 10f0ecb..0000000
+++ /dev/null
@@ -1,53 +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.Text;
-
-namespace DPStressHarness
-{
-    public static class Constants
-    {
-        public const string XML_ELEM_RESULTS = "PerfResults";
-        public const string XML_ELEM_RUN = "Run";
-        public const string XML_ELEM_RUN_METRIC = "RunMetric";
-        public const string XML_ELEM_TEST = "Test";
-        public const string XML_ELEM_TEST_METRIC = "TestMetric";
-        public const string XML_ELEM_EXCEPTION = "Exception";
-
-        public const string XML_ATTR_RUN_LABEL = "label";
-        public const string XML_ATTR_RUN_START_TIME = "startTime";
-        public const string XML_ATTR_RUN_OFFICIAL = "official";
-        public const string XML_ATTR_RUN_MILESTONE = "milestone";
-        public const string XML_ATTR_RUN_BRANCH = "branch";
-        public const string XML_ATTR_RUN_UPLOADED = "uploaded";
-        public const string XML_ATTR_RUN_METRIC_NAME = "name";
-        public const string XML_ATTR_TEST_NAME = "name";
-        public const string XML_ATTR_TEST_METRIC_NAME = "name";
-        public const string XML_ATTR_TEST_METRIC_UNITS = "units";
-        public const string XML_ATTR_TEST_METRIC_ISHIGHERBETTER = "isHigherBetter";
-
-        public const string XML_ATTR_VALUE_TRUE = "true";
-        public const string XML_ATTR_VALUE_FALSE = "false";
-
-        public const string RUN_METRIC_PROCESSOR_COUNT = "Processor Count";
-        public const string RUN_DNS_HOST_NAME = "DNS Host Name";
-        public const string RUN_IDENTITY_NAME = "Identity Name";
-        public const string RUN_PROCESS_MACHINE_NAME = "Process Machine Name";
-
-        public const string TEST_METRIC_TEST_ASSEMBLY = "Test Assembly";
-        public const string TEST_METRIC_TEST_IMPROVEMENT = "Improvement";
-        public const string TEST_METRIC_TEST_OWNER = "Owner";
-        public const string TEST_METRIC_TEST_CATEGORY = "Category";
-        public const string TEST_METRIC_TEST_PRIORITY = "Priority";
-        public const string TEST_METRIC_APPLICATION_NAME = "Application Name";
-        public const string TEST_METRIC_TARGET_ASSEMBLY_NAME = "Target Assembly Name";
-        public const string TEST_METRIC_ELAPSED_SECONDS = "Elapsed Seconds";
-        public const string TEST_METRIC_RPS = "Requests Per Second";
-        public const string TEST_METRIC_PEAK_WORKING_SET = "Peak Working Set";
-        public const string TEST_METRIC_WORKING_SET = "Working Set";
-        public const string TEST_METRIC_PRIVATE_BYTES = "Private Bytes";
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/DeadlockDetection.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/DeadlockDetection.cs
deleted file mode 100644 (file)
index c36a229..0000000
+++ /dev/null
@@ -1,192 +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.Reflection;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace DPStressHarness
-{
-    public class DeadlockDetection
-    {
-        /// <summary>
-        /// Information for a thread relating to deadlock detection. All of its information is stored in a reference object to make updating it easier.
-        /// </summary>
-        private class ThreadInfo
-        {
-            public ThreadInfo(long dueTime)
-            {
-                this.DueTime = dueTime;
-            }
-
-            /// <summary>
-            /// The time (in ticks) when the thread should be completed
-            /// </summary>
-            public long DueTime;
-
-            /// <summary>
-            /// True if the thread should not be aborted
-            /// </summary>
-            public bool DisableAbort;
-
-            /// <summary>
-            /// The time when DisableAbort was set to true
-            /// </summary>
-            public long DisableAbortTime;
-        }
-
-        /// <summary>
-        /// Maximum time that a test thread (i.e. a thread that is directly executing a [StressTest] method) can
-        /// execute before it is considered to be deadlocked. This should be longer than the
-        /// TaskThreadDeadlockTimeoutTicks because if the test is waiting for a task then the test will always
-        /// take longer to execute than the task.
-        /// </summary>
-        public const long TestThreadDeadlockTimeoutTicks = 20 * 60 * TimeSpan.TicksPerSecond;
-
-        /// <summary>
-        /// Maximum time that any Task can execute before it is considered to be deadlocked
-        /// </summary>
-        public const long TaskThreadDeadlockTimeoutTicks = 10 * 60 * TimeSpan.TicksPerSecond;
-
-        /// <summary>
-        /// Dictionary that maps Threads to the time (in ticks) when they should be completed. If they are not completed by that time then
-        /// they are considered to be deadlocked.
-        /// </summary>
-        private static ConcurrentDictionary<Thread, ThreadInfo> s_threadDueTimes = null;
-
-        /// <summary>
-        /// Timer that scans through _threadDueTimes to find deadlocked threads
-        /// </summary>
-        private static Timer s_deadlockWatchdog = null;
-
-        /// <summary>
-        /// Interval of _deadlockWatchdog, in milliseconds
-        /// </summary>
-        private const int _watchdogIntervalMs = 60 * 1000;
-
-        /// <summary>
-        /// true if deadlock detection is enabled, otherwise false. Should be set only at process startup.
-        /// </summary>
-        private static bool s_isEnabled = false;
-
-        /// <summary>
-        /// Enables deadlock detection.
-        /// </summary>
-        public static void Enable()
-        {
-            // Switch out the default TaskScheduler. We must use reflection because it is private.
-            FieldInfo defaultTaskScheduler = typeof(TaskScheduler).GetField("s_defaultTaskScheduler", BindingFlags.NonPublic | BindingFlags.Static);
-            DeadlockDetectionTaskScheduler newTaskScheduler = new DeadlockDetectionTaskScheduler();
-            defaultTaskScheduler.SetValue(null, newTaskScheduler);
-
-            s_threadDueTimes = new ConcurrentDictionary<Thread, ThreadInfo>();
-            s_deadlockWatchdog = new Timer(CheckForDeadlocks, null, _watchdogIntervalMs, _watchdogIntervalMs);
-
-            s_isEnabled = true;
-        }
-
-        /// <summary>
-        /// Adds the current Task execution thread to the tracked thread collection.
-        /// </summary>
-        public static void AddTaskThread()
-        {
-            if (s_isEnabled)
-            {
-                long dueTime = DateTime.UtcNow.Ticks + TaskThreadDeadlockTimeoutTicks;
-                AddThread(dueTime);
-            }
-        }
-
-        /// <summary>
-        /// Adds the current Test execution thread (i.e. a thread that is directly executing a [StressTest] method) to the tracked thread collection.
-        /// </summary>
-        public static void AddTestThread()
-        {
-            if (s_isEnabled)
-            {
-                long dueTime = DateTime.UtcNow.Ticks + TestThreadDeadlockTimeoutTicks;
-                AddThread(dueTime);
-            }
-        }
-
-        private static void AddThread(long dueTime)
-        {
-            s_threadDueTimes.TryAdd(Thread.CurrentThread, new ThreadInfo(dueTime));
-        }
-
-        /// <summary>
-        /// Removes the current thread from the tracked thread collection
-        /// </summary>
-        public static void RemoveThread()
-        {
-            if (s_isEnabled)
-            {
-                ThreadInfo unused;
-                s_threadDueTimes.TryRemove(Thread.CurrentThread, out unused);
-            }
-        }
-
-        /// <summary>
-        /// Disables abort of current thread. Call this when the current thread is waiting on a task.
-        /// </summary>
-        public static void DisableThreadAbort()
-        {
-            if (s_isEnabled)
-            {
-                ThreadInfo threadInfo;
-                if (s_threadDueTimes.TryGetValue(Thread.CurrentThread, out threadInfo))
-                {
-                    threadInfo.DisableAbort = true;
-                    threadInfo.DisableAbortTime = DateTime.UtcNow.Ticks;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Enables abort of current thread after calling DisableThreadAbort(). The elapsed time since calling DisableThreadAbort() is added to the due time.
-        /// </summary>
-        public static void EnableThreadAbort()
-        {
-            if (s_isEnabled)
-            {
-                ThreadInfo threadInfo;
-                if (s_threadDueTimes.TryGetValue(Thread.CurrentThread, out threadInfo))
-                {
-                    threadInfo.DueTime += DateTime.UtcNow.Ticks - threadInfo.DisableAbortTime;
-                    threadInfo.DisableAbort = false;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Looks through the tracked thread collection and aborts any thread that is past its due time
-        /// </summary>
-        /// <param name="state">unused</param>
-        private static void CheckForDeadlocks(object state)
-        {
-            if (s_isEnabled)
-            {
-                long now = DateTime.UtcNow.Ticks;
-
-                // Find candidate threads
-                foreach (var threadDuePair in s_threadDueTimes)
-                {
-                    if (!threadDuePair.Value.DisableAbort && now > threadDuePair.Value.DueTime)
-                    {
-                        // Abort the misbehaving thread and the return
-                        // NOTE: We only want to abort a single thread at a time to allow the other thread in the deadlock pair to continue
-                        Thread t = threadDuePair.Key;
-                        Console.WriteLine("Deadlock detected on thread with managed thread id {0}", t.ManagedThreadId);
-                        Debugger.Break();
-                        t.Join();
-                        return;
-                    }
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/DeadlockDetectionTaskScheduler.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/DeadlockDetectionTaskScheduler.cs
deleted file mode 100644 (file)
index a96ac40..0000000
+++ /dev/null
@@ -1,94 +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.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace DPStressHarness
-{
-    public class DeadlockDetectionTaskScheduler : TaskScheduler
-    {
-        private readonly WaitCallback _runTaskCallback;
-        private readonly ParameterizedThreadStart _runTaskThreadStart;
-#if DEBUG
-        private readonly ConcurrentDictionary<Task, object> _queuedItems = new ConcurrentDictionary<Task, object>();
-#endif
-
-        public DeadlockDetectionTaskScheduler()
-        {
-            _runTaskCallback = new WaitCallback(RunTask);
-            _runTaskThreadStart = new ParameterizedThreadStart(RunTask);
-        }
-
-        // This is only used for debugging, so for retail we'd prefer the perf
-        protected override IEnumerable<Task> GetScheduledTasks()
-        {
-#if DEBUG
-            return _queuedItems.Keys;
-#else
-            return new Task[0];
-#endif
-        }
-
-        protected override void QueueTask(Task task)
-        {
-            if ((task.CreationOptions & TaskCreationOptions.LongRunning) == TaskCreationOptions.LongRunning)
-            {
-                // Create a new background thread for long running tasks
-                Thread thread = new Thread(_runTaskThreadStart) { IsBackground = true };
-                thread.Start(task);
-            }
-            else
-            {
-                // Otherwise queue the work on the threadpool
-#if DEBUG
-                _queuedItems.TryAdd(task, null);
-#endif
-
-                ThreadPool.QueueUserWorkItem(_runTaskCallback, task);
-            }
-        }
-
-        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
-        {
-            if (!taskWasPreviouslyQueued)
-            {
-                // Run the task inline
-                RunTask(task);
-                return true;
-            }
-
-            // Couldn't run the task
-            return false;
-        }
-
-        private void RunTask(object state)
-        {
-            Task inTask = state as Task;
-
-#if DEBUG
-            // Remove from the dictionary of queued items
-            object ignored;
-            _queuedItems.TryRemove(inTask, out ignored);
-#endif
-
-            // Note when the thread started work
-            DeadlockDetection.AddTaskThread();
-
-            try
-            {
-                // Run the task
-                base.TryExecuteTask(inTask);
-            }
-            finally
-            {
-                // Remove the thread from the list when complete
-                DeadlockDetection.RemoveThread();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/FakeConsole.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/FakeConsole.cs
deleted file mode 100644 (file)
index f13949a..0000000
+++ /dev/null
@@ -1,34 +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.Text;
-
-namespace DPStressHarness
-{
-    public static class FakeConsole
-    {
-        public static void Write(string value)
-        {
-#if DEBUG
-            Console.Write(value);
-#endif
-        }
-
-        public static void WriteLine(string value)
-        {
-#if DEBUG
-            Console.WriteLine(value);
-#endif
-        }
-
-        public static void WriteLine(string format, params object[] arg)
-        {
-#if DEBUG
-            Console.WriteLine(format, arg);
-#endif
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalExceptionHandlerAttribute.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalExceptionHandlerAttribute.cs
deleted file mode 100644 (file)
index 810580d..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
-    public class GlobalExceptionHandlerAttribute : Attribute
-    {
-        public GlobalExceptionHandlerAttribute()
-        {
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalTestCleanupAttribute.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalTestCleanupAttribute.cs
deleted file mode 100644 (file)
index 2159d26..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
-    public class GlobalTestCleanupAttribute : Attribute
-    {
-        public GlobalTestCleanupAttribute()
-        {
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalTestSetupAttribute.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/GlobalTestSetupAttribute.cs
deleted file mode 100644 (file)
index 00ed3d5..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
-    public class GlobalTestSetupAttribute : Attribute
-    {
-        public GlobalTestSetupAttribute()
-        {
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/ITestAttributeFilter.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/ITestAttributeFilter.cs
deleted file mode 100644 (file)
index c3afa92..0000000
+++ /dev/null
@@ -1,11 +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 DPStressHarness
-{
-    public interface ITestAttributeFilter
-    {
-        bool MatchFilter(string filterString);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Logger.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Logger.cs
deleted file mode 100644 (file)
index 5c2fe8b..0000000
+++ /dev/null
@@ -1,227 +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.Xml;
-using System.Diagnostics;
-
-namespace DPStressHarness
-{
-    public class Logger
-    {
-        private const string _resultDocumentName = "perfout.xml";
-
-        private XmlDocument _doc;
-        private XmlElement _runElem;
-        private XmlElement _testElem;
-
-        public Logger(string runLabel, bool isOfficial, string milestone, string branch)
-        {
-            _doc = GetTestResultDocument();
-
-            _runElem = GetRunElement(_doc, runLabel, DateTime.Now.ToString(), isOfficial, milestone, branch);
-
-            Process currentProcess = Process.GetCurrentProcess();
-            AddRunMetric(Constants.RUN_PROCESS_MACHINE_NAME, currentProcess.MachineName);
-            AddRunMetric(Constants.RUN_DNS_HOST_NAME, System.Net.Dns.GetHostName());
-            AddRunMetric(Constants.RUN_IDENTITY_NAME, System.Security.Principal.WindowsIdentity.GetCurrent().Name);
-            AddRunMetric(Constants.RUN_METRIC_PROCESSOR_COUNT, Environment.ProcessorCount.ToString());
-
-        }
-
-        public void AddRunMetric(string metricName, string metricValue)
-        {
-            Debug.Assert(_runElem != null);
-
-            if (metricValue.Equals(string.Empty))
-                return;
-
-            AddRunMetricElement(_runElem, metricName, metricValue);
-        }
-
-        public void AddTest(string testName)
-        {
-            Debug.Assert(_runElem != null);
-
-            _testElem = AddTestElement(_runElem, testName);
-        }
-
-        public void AddTestMetric(string metricName, string metricValue, string metricUnits)
-        {
-            AddTestMetric(metricName, metricValue, metricUnits, null);
-        }
-
-        public void AddTestMetric(string metricName, string metricValue, string metricUnits, bool? isHigherBetter)
-        {
-            Debug.Assert(_runElem != null);
-            Debug.Assert(_testElem != null);
-
-            if (metricValue.Equals(string.Empty))
-                return;
-
-            AddTestMetricElement(_testElem, metricName, metricValue, metricUnits, isHigherBetter);
-        }
-
-        public void AddTestException(string exceptionData)
-        {
-            Debug.Assert(_runElem != null);
-            Debug.Assert(_testElem != null);
-
-            AddTestExceptionElement(_testElem, exceptionData);
-        }
-
-        public void Save()
-        {
-            FileStream resultDocumentStream = new FileStream(_resultDocumentName, FileMode.Create);
-            _doc.Save(resultDocumentStream);
-            resultDocumentStream.Dispose();
-        }
-
-        private static XmlDocument GetTestResultDocument()
-        {
-            if (File.Exists(_resultDocumentName))
-            {
-                XmlDocument doc = new XmlDocument();
-                FileStream resultDocumentStream = new FileStream(_resultDocumentName, FileMode.Open, FileAccess.Read);
-                doc.Load(resultDocumentStream);
-                resultDocumentStream.Dispose();
-                return doc;
-            }
-            else
-            {
-                XmlDocument doc = new XmlDocument();
-                doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><PerfResults></PerfResults>");
-                FileStream resultDocumentStream = new FileStream(_resultDocumentName, FileMode.CreateNew);
-                doc.Save(resultDocumentStream);
-                resultDocumentStream.Dispose();
-                return doc;
-            }
-        }
-
-
-        private static XmlElement GetRunElement(XmlDocument doc, string label, string startTime, bool isOfficial, string milestone, string branch)
-        {
-            foreach (XmlNode node in doc.DocumentElement.ChildNodes)
-            {
-                if (node.NodeType == XmlNodeType.Element &&
-                     node.Name.Equals(Constants.XML_ELEM_RUN) &&
-                     ((XmlElement)node).GetAttribute(Constants.XML_ATTR_RUN_LABEL).Equals(label))
-                {
-                    return (XmlElement)node;
-                }
-            }
-
-            XmlElement runElement = doc.CreateElement(Constants.XML_ELEM_RUN);
-
-            XmlAttribute attrLabel = doc.CreateAttribute(Constants.XML_ATTR_RUN_LABEL);
-            attrLabel.Value = label;
-            runElement.Attributes.Append(attrLabel);
-
-            XmlAttribute attrStartTime = doc.CreateAttribute(Constants.XML_ATTR_RUN_START_TIME);
-            attrStartTime.Value = startTime;
-            runElement.Attributes.Append(attrStartTime);
-
-            XmlAttribute attrOfficial = doc.CreateAttribute(Constants.XML_ATTR_RUN_OFFICIAL);
-            attrOfficial.Value = isOfficial.ToString();
-            runElement.Attributes.Append(attrOfficial);
-
-            if (milestone != null)
-            {
-                XmlAttribute attrMilestone = doc.CreateAttribute(Constants.XML_ATTR_RUN_MILESTONE);
-                attrMilestone.Value = milestone;
-                runElement.Attributes.Append(attrMilestone);
-            }
-
-            if (branch != null)
-            {
-                XmlAttribute attrBranch = doc.CreateAttribute(Constants.XML_ATTR_RUN_BRANCH);
-                attrBranch.Value = branch;
-                runElement.Attributes.Append(attrBranch);
-            }
-
-            doc.DocumentElement.AppendChild(runElement);
-
-            return runElement;
-        }
-
-
-        private static void AddRunMetricElement(XmlElement runElement, string name, string value)
-        {
-            // First check and make sure the metric hasn't already been added.
-            // If it has, it's from a previous test in the same run, so just return.
-            foreach (XmlNode node in runElement.ChildNodes)
-            {
-                if (node.NodeType == XmlNodeType.Element && node.Name.Equals(Constants.XML_ELEM_RUN_METRIC))
-                {
-                    if (node.Attributes[Constants.XML_ATTR_RUN_METRIC_NAME].Value.Equals(name))
-                        return;
-                }
-            }
-
-            XmlElement runMetricElement = runElement.OwnerDocument.CreateElement(Constants.XML_ELEM_RUN_METRIC);
-
-            XmlAttribute attrName = runElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_RUN_METRIC_NAME);
-            attrName.Value = name;
-            runMetricElement.Attributes.Append(attrName);
-
-            XmlText nodeValue = runElement.OwnerDocument.CreateTextNode(value);
-            runMetricElement.AppendChild(nodeValue);
-
-            runElement.AppendChild(runMetricElement);
-        }
-
-
-        private static XmlElement AddTestElement(XmlElement runElement, string name)
-        {
-            XmlElement testElement = runElement.OwnerDocument.CreateElement(Constants.XML_ELEM_TEST);
-
-            XmlAttribute attrName = runElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_NAME);
-            attrName.Value = name;
-            testElement.Attributes.Append(attrName);
-
-            runElement.AppendChild(testElement);
-
-            return testElement;
-        }
-
-
-        private static void AddTestMetricElement(XmlElement testElement, string name, string value, string units, bool? isHigherBetter)
-        {
-            XmlElement testMetricElement = testElement.OwnerDocument.CreateElement(Constants.XML_ELEM_TEST_METRIC);
-
-            XmlAttribute attrName = testElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_METRIC_NAME);
-            attrName.Value = name;
-            testMetricElement.Attributes.Append(attrName);
-
-            if (units != null)
-            {
-                XmlAttribute attrUnits = testElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_METRIC_UNITS);
-                attrUnits.Value = units;
-                testMetricElement.Attributes.Append(attrUnits);
-            }
-
-            if (isHigherBetter.HasValue)
-            {
-                XmlAttribute attrIsHigherBetter = testElement.OwnerDocument.CreateAttribute(Constants.XML_ATTR_TEST_METRIC_ISHIGHERBETTER);
-                attrIsHigherBetter.Value = isHigherBetter.ToString();
-                testMetricElement.Attributes.Append(attrIsHigherBetter);
-            }
-
-            XmlText nodeValue = testElement.OwnerDocument.CreateTextNode(value);
-            testMetricElement.AppendChild(nodeValue);
-
-            testElement.AppendChild(testMetricElement);
-        }
-
-        private static void AddTestExceptionElement(XmlElement testElement, string exceptionData)
-        {
-            XmlElement testFailureElement = testElement.OwnerDocument.CreateElement(Constants.XML_ELEM_EXCEPTION);
-            XmlText txtNode = testFailureElement.OwnerDocument.CreateTextNode(exceptionData);
-            testFailureElement.AppendChild(txtNode);
-
-            testElement.AppendChild(testFailureElement);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MemApi.Unix.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MemApi.Unix.cs
deleted file mode 100644 (file)
index 6dfb335..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    internal static class MemApi
-    {
-        public static IntPtr GetCurrentProcess()
-        {
-            return IntPtr.Zero;
-        }
-
-        public static bool SetProcessWorkingSetSize(IntPtr hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize)
-        {
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MemApi.Windows.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MemApi.Windows.cs
deleted file mode 100644 (file)
index 053aea0..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    static class MemApi
-    {
-        [DllImport("KERNEL32")]
-        public static extern IntPtr GetCurrentProcess();
-
-        [DllImport("KERNEL32")]
-        public static extern bool SetProcessWorkingSetSize(IntPtr hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MonitorLoadUtils.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MonitorLoadUtils.cs
deleted file mode 100644 (file)
index bfe2d87..0000000
+++ /dev/null
@@ -1,49 +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 Monitoring;
-using System.Reflection;
-
-namespace DPStressHarness
-{
-    public static class MonitorLoader
-    {
-        public static IMonitorLoader LoadMonitorLoaderAssembly()
-
-        {
-            IMonitorLoader monitorloader = null;
-            const string classname = "Monitoring.MonitorLoader";
-            const string interfacename = "IMonitorLoader";
-            Assembly mainAssembly = typeof(Monitoring.IMonitorLoader).GetTypeInfo().Assembly;
-
-            Type t = mainAssembly.GetType(classname);
-            //make sure the type is derived from IMonitorLoader
-            Type[] interfaces = t.GetInterfaces();
-            bool derivedFromIMonitorLoader = false;
-            if (interfaces != null)
-            {
-                foreach (Type intrface in interfaces)
-                {
-                    if (intrface.Name == interfacename)
-                    {
-                        derivedFromIMonitorLoader = true;
-                    }
-                }
-            }
-            if (derivedFromIMonitorLoader)
-
-            {
-                monitorloader = (IMonitorLoader)Activator.CreateInstance(t);
-
-                monitorloader.AssemblyPath = mainAssembly.FullName;
-            }
-            else
-            {
-                throw new Exception("The specified assembly does not implement " + interfacename + "!!");
-            }
-            return monitorloader;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MultithreadedTest.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/MultithreadedTest.cs
deleted file mode 100644 (file)
index 01ea961..0000000
+++ /dev/null
@@ -1,170 +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.Reflection;
-using System.Diagnostics;
-using System.Threading;
-
-namespace DPStressHarness
-{
-    internal class MultiThreadedTest : TestBase
-    {
-        private MultiThreadedTestAttribute _attr;
-        public static bool _continue;
-        public static int _threadsRunning;
-        public static int _rps;
-        public static Exception _firstException = null;
-
-        private struct TestInfo
-        {
-            public object _instance;
-            public TestMethodDelegate _delegateTest;
-        }
-
-        public MultiThreadedTest(MultiThreadedTestAttribute attr,
-                                 MethodInfo testMethodInfo,
-                                 Type type,
-                                 List<MethodInfo> setupMethods,
-                                 List<MethodInfo> cleanupMethods)
-            : base(attr, testMethodInfo, type, setupMethods, cleanupMethods)
-
-        {
-            _attr = attr;
-        }
-
-        public override void Run()
-        {
-            try
-            {
-                Stopwatch timer = new Stopwatch();
-                long warmupDuration = (long)_attr.WarmupDuration * Stopwatch.Frequency;
-                long testDuration = (long)_attr.TestDuration * Stopwatch.Frequency;
-                int threads = _attr.Threads;
-
-                TestInfo[] info = new TestInfo[threads];
-                ConstructorInfo targetConstructor = _type.GetConstructor(Type.EmptyTypes);
-
-                for (int i = 0; i < threads; i++)
-                {
-                    info[i] = new TestInfo();
-                    info[i]._instance = targetConstructor.Invoke(null);
-                    info[i]._delegateTest = CreateTestMethodDelegate();
-
-                    SetVariations(info[i]._instance);
-                    ExecuteSetupPhase(info[i]._instance);
-                }
-
-                _firstException = null;
-                _continue = true;
-                _rps = 0;
-
-                for (int i = 0; i < threads; i++)
-                {
-                    Interlocked.Increment(ref _threadsRunning);
-                    Thread t = new Thread(new ParameterizedThreadStart(MultiThreadedTest.RunThread));
-                    t.Start(info[i]);
-                }
-
-                timer.Reset();
-                timer.Start();
-
-                while (timer.ElapsedTicks < warmupDuration)
-                {
-                    Thread.Sleep(1000);
-                }
-
-                int warmupRequests = Interlocked.Exchange(ref _rps, 0);
-                timer.Reset();
-                timer.Start();
-                TestMetrics.StartCollection();
-
-                while (timer.ElapsedTicks < testDuration)
-                {
-                    Thread.Sleep(1000);
-                }
-
-                int requests = Interlocked.Exchange(ref _rps, 0);
-                double elapsedSeconds = timer.ElapsedTicks / Stopwatch.Frequency;
-                TestMetrics.StopCollection();
-                _continue = false;
-
-                while (_threadsRunning > 0)
-                {
-                    Thread.Sleep(1000);
-                }
-
-                for (int i = 0; i < threads; i++)
-                {
-                    ExecuteCleanupPhase(info[i]._instance);
-                }
-
-                double rps = (double)requests / elapsedSeconds;
-
-                if (_firstException == null)
-                {
-                    LogTest(rps);
-                }
-                else
-                {
-                    LogTestFailure(_firstException.ToString());
-                }
-            }
-            catch (TargetInvocationException e)
-            {
-                LogTestFailure(e.InnerException.ToString());
-            }
-            catch (Exception e)
-            {
-                LogTestFailure(e.ToString());
-            }
-        }
-
-
-        public static void RunThread(object state)
-        {
-            try
-            {
-                while (_continue)
-                {
-                    TestInfo info = (TestInfo)state;
-                    info._delegateTest(info._instance);
-                    Interlocked.Increment(ref _rps);
-                }
-            }
-            catch (Exception e)
-            {
-                if (_firstException == null)
-                {
-                    _firstException = e;
-                }
-                _continue = false;
-            }
-            finally
-            {
-                Interlocked.Decrement(ref _threadsRunning);
-            }
-        }
-
-        protected void LogTest(double rps)
-        {
-            Logger logger = new Logger(TestMetrics.RunLabel, TestMetrics.IsOfficial, TestMetrics.Milestone, TestMetrics.Branch);
-            logger.AddTest(this.Title);
-
-            LogStandardMetrics(logger);
-
-            logger.AddTestMetric(Constants.TEST_METRIC_RPS, string.Format("{0:F2}", rps), "rps", true);
-
-            logger.Save();
-
-            Console.WriteLine("{0}: Requests per Second={1:F2}, Working Set={2}, Peak Working Set={3}, Private Bytes={4}",
-                              this.Title,
-                              rps,
-                              TestMetrics.WorkingSet,
-                              TestMetrics.PeakWorkingSet,
-                              TestMetrics.PrivateBytes);
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/PerfCounters.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/PerfCounters.cs
deleted file mode 100644 (file)
index 3921ca1..0000000
+++ /dev/null
@@ -1,34 +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.Diagnostics;
-
-namespace DPStressHarness
-{
-    public class PerfCounters
-    {
-        private long _requestsCounter;
-        //private long rpsCounter;
-
-        private long _exceptionsCounter;
-        //private long epsCounter;
-
-        public PerfCounters()
-        {
-
-        }
-
-        public void IncrementRequestsCounter()
-        {
-            _requestsCounter++;
-        }
-
-        public void IncrementExceptionsCounter()
-        {
-            _exceptionsCounter++;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Program.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Program.cs
deleted file mode 100644 (file)
index 19e3327..0000000
+++ /dev/null
@@ -1,276 +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.Collections.Generic;
-using System.Text;
-using System.Reflection;
-
-
-namespace DPStressHarness
-{
-    public class Program
-    {
-        public static void Main(string[] args)
-        {
-            Init(args);
-            Run();
-        }
-        public enum RunMode
-        {
-            RunAll,
-            RunVerify,
-            Help,
-            ExitWithError
-        };
-
-        private static RunMode s_mode = RunMode.RunAll;
-        private static IEnumerable<TestBase> s_tests;
-        private static StressEngine s_eng;
-        private static string s_error;
-
-
-        public static void Init(string[] args)
-        {
-            for (int i = 0; i < args.Length; i++)
-            {
-                switch (args[i])
-                {
-                    case "-a":
-                        string assemblyName = args[++i];
-                        TestFinder.AssemblyName = new AssemblyName(assemblyName);
-                        break;
-
-                    case "-all":
-                        s_mode = RunMode.RunAll;
-                        break;
-
-                    case "-override":
-                        TestMetrics.Overrides.Add(args[++i], args[++i]);
-                        break;
-
-                    case "-variation":
-                        TestMetrics.Variations.Add(args[++i]);
-                        break;
-
-                    case "-test":
-                        TestMetrics.SelectedTests.Add(args[++i]);
-                        break;
-
-                    case "-duration":
-                        TestMetrics.StressDuration = int.Parse(args[++i]);
-                        break;
-
-                    case "-threads":
-                        TestMetrics.StressThreads = int.Parse(args[++i]);
-                        break;
-
-                    case "-verify":
-                        s_mode = RunMode.RunVerify;
-                        break;
-
-                    case "-debug":
-                        if (System.Diagnostics.Debugger.IsAttached)
-                        {
-                            System.Diagnostics.Debugger.Break();
-                        }
-                        else
-                        {
-                            Console.WriteLine("Current PID: {0}, attach the debugger and press Enter to continue the execution...", System.Diagnostics.Process.GetCurrentProcess().Id);
-                            Console.ReadLine();
-                        }
-                        break;
-
-                    case "-exceptionThreshold":
-                        TestMetrics.ExceptionThreshold = int.Parse(args[++i]);
-                        break;
-
-                    case "-monitorenabled":
-                        TestMetrics.MonitorEnabled = bool.Parse(args[++i]);
-                        break;
-
-                    case "-randomSeed":
-                        TestMetrics.RandomSeed = int.Parse(args[++i]);
-                        break;
-
-                    case "-filter":
-                        TestMetrics.Filter = args[++i];
-                        break;
-
-                    case "-printMethodName":
-                        TestMetrics.PrintMethodName = true;
-                        break;
-
-                    case "-deadlockdetection":
-                        if (bool.Parse(args[++i]))
-                        {
-                            DeadlockDetection.Enable();
-                        }
-                        break;
-
-                    default:
-                        s_mode = RunMode.Help;
-                        break;
-                }
-            }
-
-            if (TestFinder.AssemblyName != null)
-            {
-                Console.WriteLine("Assembly Found for the Assembly Name " + TestFinder.AssemblyName);
-
-                if (TestFinder.AssemblyName != null)
-                {
-                    // get and load all the tests
-                    s_tests = TestFinder.GetTests(Assembly.Load(TestFinder.AssemblyName));
-
-                    // instantiate the stress engine
-                    s_eng = new StressEngine(TestMetrics.StressThreads, TestMetrics.StressDuration, s_tests, TestMetrics.RandomSeed);
-                }
-                else
-                {
-                    Program.s_error = string.Format("Assembly {0} cannot be found.", TestFinder.AssemblyName);
-                    s_mode = RunMode.ExitWithError;
-                }
-            }
-        }
-
-        public static void TestCase(Assembly assembly,
-                                    RunMode mode,
-                                    int duration,
-                                    int threads,
-                                    int? exceptionThreshold = null,
-                                    bool printMethodName = false,
-                                    bool deadlockDetection = false,
-                                    int randomSeed = 0,
-                                    string[] selectedTests = null,
-                                    string[] overrides = null,
-                                    string[] variations = null,
-                                    string filter = null,
-                                    bool monitorEnabled = false,
-                                    string monitorMachineName = "localhost")
-        {
-            TestMetrics.Reset();
-            TestFinder.AssemblyName = assembly.GetName();
-            mode = RunMode.RunAll;
-
-            for (int i = 0; overrides != null && i < overrides.Length; i++)
-            {
-                TestMetrics.Overrides.Add(overrides[i], overrides[++i]);
-            }
-
-            for (int i = 0; variations != null && i < variations.Length; i++)
-            {
-                TestMetrics.Variations.Add(variations[i]);
-            }
-
-            for (int i = 0; selectedTests != null && i < selectedTests.Length; i++)
-            {
-                TestMetrics.SelectedTests.Add(selectedTests[i]);
-            }
-
-            TestMetrics.StressDuration = duration;
-            TestMetrics.StressThreads = threads;
-            TestMetrics.ExceptionThreshold = exceptionThreshold;
-            TestMetrics.MonitorEnabled = monitorEnabled;
-            TestMetrics.MonitorMachineName = monitorMachineName;
-            TestMetrics.RandomSeed = randomSeed;
-            TestMetrics.Filter = filter;
-            TestMetrics.PrintMethodName = printMethodName;
-
-            if (deadlockDetection)
-            {
-                DeadlockDetection.Enable();
-            }
-
-            // get and load all the tests
-            s_tests = TestFinder.GetTests(assembly);
-
-            // instantiate the stress engine
-            s_eng = new StressEngine(TestMetrics.StressThreads, TestMetrics.StressDuration, s_tests, TestMetrics.RandomSeed);
-        }
-
-        public static void Run()
-        {
-            if (TestFinder.AssemblyName == null)
-            {
-                s_mode = RunMode.Help;
-            }
-            switch (s_mode)
-            {
-                case RunMode.RunAll:
-                    RunStress();
-                    break;
-
-                case RunMode.RunVerify:
-                    RunVerify();
-                    break;
-
-                case RunMode.ExitWithError:
-                    ExitWithError();
-                    break;
-
-                case RunMode.Help:
-                    PrintHelp();
-                    break;
-            }
-        }
-
-        private static void PrintHelp()
-        {
-            Console.WriteLine("stresstest.exe [-a <module name>] <arguments>");
-            Console.WriteLine();
-            Console.WriteLine("   -a <module name> should specify path to the assembly containing the tests.");
-            Console.WriteLine();
-            Console.WriteLine("Supported options are:");
-            Console.WriteLine();
-            Console.WriteLine("   -all                        Run all tests - best for debugging, not perf measurements.");
-            Console.WriteLine();
-            Console.WriteLine("   -verify                     Run in functional verification mode.");
-            Console.WriteLine();
-            Console.WriteLine("   -duration <n>               Duration of the test in seconds.");
-            Console.WriteLine();
-            Console.WriteLine("   -threads <n>                Number of threads to use.");
-            Console.WriteLine();
-            Console.WriteLine("   -override <name> <value>    Override the value of a test property.");
-            Console.WriteLine();
-            Console.WriteLine("   -test <name>                Run specific test(s) using their name.");
-            Console.WriteLine();
-            Console.WriteLine("   -debug                      Print process ID in the beginning and wait for Enter (to give your time to attach the debugger).");
-            Console.WriteLine();
-            Console.WriteLine("   -exceptionThreshold <n>     An optional limit on exceptions which will be caught. When reached, test will halt.");
-            Console.WriteLine();
-            Console.WriteLine("   -monitorenabled             True or False to enable monitoring. Default is false");
-            Console.WriteLine();
-            Console.WriteLine("   -randomSeed                 Enables setting of the random number generator used internally.  This serves both the purpose");
-            Console.WriteLine("                               of helping to improve reproducibility and making it deterministic from Chess's perspective");
-            Console.WriteLine("                               for a given schedule. Default is " + TestMetrics.RandomSeed + ".");
-            Console.WriteLine();
-            Console.WriteLine("   -filter                     Run tests whose stress test attributes match the given filter. Filter is not applied if attribute");
-            Console.WriteLine("                               does not implement ITestAttributeFilter. Example: -filter TestType=Query,Update;IsServerTest=True ");
-            Console.WriteLine();
-            Console.WriteLine("   -printMethodName            Print tests' title in console window");
-            Console.WriteLine();
-            Console.WriteLine("   -deadlockdetection          True or False to enable deadlock detection. Default is false");
-            Console.WriteLine();
-        }
-
-        private static int ExitWithError()
-        {
-            Environment.FailFast("Exit with error(s).");
-            return 1;
-        }
-
-        private static int RunVerify()
-        {
-            throw new NotImplementedException();
-        }
-
-        private static int RunStress()
-        {
-            return s_eng.Run();
-        }
-    }
-
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/RecordedExceptions.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/RecordedExceptions.cs
deleted file mode 100644 (file)
index a12e38f..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Text;
-using System.Collections.Concurrent;
-using System.Diagnostics;
-using System.Threading;
-
-namespace DPStressHarness
-{
-    public class RecordedExceptions
-    {
-        // Reference wrapper around an integer which is used in order to make updating a little easier & more efficient
-        public class ExceptionCount
-        {
-            public int Count = 0;
-        }
-
-        private ConcurrentDictionary<string, ConcurrentDictionary<string, ExceptionCount>> _exceptions = new ConcurrentDictionary<string, ConcurrentDictionary<string, ExceptionCount>>();
-
-        /// <summary>
-        /// Records an exception and returns true if the threshold is exceeded for that exception
-        /// </summary>
-        public bool Record(string testName, Exception ex)
-        {
-            // Converting from exception to string can be expensive so only do it once and cache the string
-            string exceptionString = ex.ToString();
-            TraceException(testName, exceptionString);
-
-            // Get the exceptions for the current test case
-            ConcurrentDictionary<string, ExceptionCount> exceptionsForTest = _exceptions.GetOrAdd(testName, _ => new ConcurrentDictionary<string, ExceptionCount>());
-
-            // Get the count for the current exception
-            ExceptionCount exCount = exceptionsForTest.GetOrAdd(exceptionString, _ => new ExceptionCount());
-
-            // Increment the count
-            Interlocked.Increment(ref exCount.Count);
-
-            // If the count is over the threshold, return true
-            return TestMetrics.ExceptionThreshold.HasValue && (exCount.Count > TestMetrics.ExceptionThreshold);
-        }
-
-        private void TraceException(string testName, string exceptionString)
-        {
-            StringBuilder status = new StringBuilder();
-            status.AppendLine("========================================================================");
-            status.AppendLine("Exception Report");
-            status.AppendLine("========================================================================");
-
-            status.AppendLine(string.Format("Test: {0}", testName));
-            status.AppendLine(exceptionString);
-
-            status.AppendLine("========================================================================");
-            status.AppendLine("End of Exception Report");
-            status.AppendLine("========================================================================");
-            Trace.WriteLine(status.ToString());
-        }
-
-        public void TraceAllExceptions()
-        {
-            StringBuilder status = new StringBuilder();
-            status.AppendLine("========================================================================");
-            status.AppendLine("All Exceptions Report");
-            status.AppendLine("========================================================================");
-
-            foreach (string testName in _exceptions.Keys)
-            {
-                ConcurrentDictionary<string, ExceptionCount> exceptionsForTest = _exceptions[testName];
-
-                status.AppendLine(string.Format("Test: {0}", testName));
-                foreach (var exceptionString in exceptionsForTest.Keys)
-                {
-                    status.AppendLine(string.Format("Count: {0}", exceptionsForTest[exceptionString].Count));
-                    status.AppendLine(string.Format("Exception: {0}", exceptionString));
-                    status.AppendLine();
-                }
-
-                status.AppendLine();
-                status.AppendLine();
-            }
-
-            status.AppendLine("========================================================================");
-            status.AppendLine("End of All Exceptions Report");
-            status.AppendLine("========================================================================");
-            Trace.WriteLine(status.ToString());
-        }
-
-        public int GetExceptionsCount()
-        {
-            int count = 0;
-
-            foreach (string testName in _exceptions.Keys)
-            {
-                ConcurrentDictionary<string, ExceptionCount> exceptionsForTest = _exceptions[testName];
-
-                foreach (var exceptionString in exceptionsForTest.Keys)
-                {
-                    count += exceptionsForTest[exceptionString].Count;
-                }
-            }
-
-            return count;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/SqlScript.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/SqlScript.cs
deleted file mode 100644 (file)
index f159a47..0000000
+++ /dev/null
@@ -1,64 +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.Data;
-using System.Data.SqlClient;
-using System.Text.RegularExpressions;
-
-namespace DPStressHarness
-{
-    /// <summary>
-    /// Use SqlScript.Execute to run sql scripts prior to test execution.
-    /// Recommended practice is to store the sql scripts as a resource in your dll (if it's complicated),
-    /// or just as a string in your assembly.
-    /// </summary>
-    public static class SqlScript
-    {
-        public static void Execute(string script, string connectionString)
-        {
-            //script = Regex.Replace(script, @"/\*((?!\*/)(.|\n)*?)\*/", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
-
-            //Regex re = new Regex(@"(?<GO>^GO)|(?<COMMAND>((?!^GO)(.|\n))+)", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
-
-            //MatchCollection matches = re.Matches(script);
-
-            //foreach (Match m in matches)
-            //{
-            //    Console.WriteLine(m.Groups["GO"]);
-            //    Console.WriteLine(m.Groups["COMMAND"]);
-            //}
-
-            //Console.WriteLine();
-
-
-            SqlConnection conn = new SqlConnection(connectionString);
-            conn.Open();
-
-            try
-            {
-                script = Regex.Replace(script, @"/\*((?!\*/)(.|\n)*?)\*/", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
-
-                Regex re = new Regex(@"(?<GO>^GO)|(?<COMMAND>((?!^GO)(.|\n))+)", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
-                MatchCollection matches = re.Matches(script);
-
-                foreach (Match m in matches)
-                {
-                    string cmdText = m.Groups["COMMAND"].Value.Trim();
-
-                    if (cmdText == string.Empty)
-                        continue;
-
-                    SqlCommand cmd = new SqlCommand(cmdText, conn);
-                    cmd.CommandTimeout = 300;
-                    cmd.ExecuteNonQuery();
-                }
-            }
-            finally
-            {
-                conn.Close();
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/StressEngine.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/StressEngine.cs
deleted file mode 100644 (file)
index 9897472..0000000
+++ /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.Collections.Generic;
-using System.Threading;
-using System.Diagnostics;
-using Monitoring;
-
-namespace DPStressHarness
-{
-    public class StressEngine
-    {
-        private Random _rnd;
-        private int _threads;
-        private int _duration;
-        private int _threadsRunning;
-        private bool _continue;
-        private List<StressTest> _allTests;
-        private RecordedExceptions _exceptions = new RecordedExceptions();
-        private PerfCounters _perfcounters = null;
-        private static long s_globalRequestsCounter = 0;
-
-        public StressEngine(int threads, int duration, IEnumerable<TestBase> allTests, int seed)
-        {
-            if (seed != 0)
-            {
-                _rnd = new Random(seed);
-            }
-            else
-            {
-                Random rndBootstrap = new Random();
-
-                seed = rndBootstrap.Next();
-
-                _rnd = new Random(seed);
-            }
-
-            Console.WriteLine("Seeding stress engine random number generator with {0}\n", seed);
-
-
-            _threads = threads;
-            _duration = duration;
-            _allTests = new List<StressTest>();
-
-            List<StressTest> tmpWeightedLookup = new List<StressTest>();
-
-            foreach (TestBase t in allTests)
-            {
-                if (t is StressTest)
-                {
-                    _allTests.Add(t as StressTest);
-                }
-            }
-
-            try
-            {
-                _perfcounters = new PerfCounters();
-            }
-            catch (Exception e)
-            {
-                Console.WriteLine("Warning: An error occurred initializing performance counters. Performance counters can only be initialized when running with Administrator privileges. Error Message: " + e.Message);
-            }
-        }
-
-        public int Run()
-        {
-            TraceListener listener = new TextWriterTraceListener(Console.Out);
-            Trace.Listeners.Add(listener);
-            Trace.UseGlobalLock = true;
-
-            _threadsRunning = 0;
-            _continue = true;
-
-            if (_allTests.Count == 0)
-            {
-                throw new ArgumentException("The specified assembly doesn't contain any tests to run. Test methods must be decorated with a Test, StressTest, MultiThreadedTest, or ThreadPoolTest attribute.");
-            }
-
-            // Run any global setup
-            StressTest firstStressTest = _allTests.Find(t => t is StressTest);
-            if (null != firstStressTest)
-            {
-                firstStressTest.RunGlobalSetup();
-            }
-
-            //Monitoring Start
-            IMonitorLoader _monitorloader = null;
-            if (TestMetrics.MonitorEnabled)
-            {
-                _monitorloader = MonitorLoader.LoadMonitorLoaderAssembly();
-                if (_monitorloader != null)
-                {
-                    _monitorloader.Enabled = TestMetrics.MonitorEnabled;
-                    _monitorloader.HostMachine = TestMetrics.MonitorMachineName;
-                    _monitorloader.TestName = firstStressTest.Title;
-                    _monitorloader.Action(MonitorLoaderUtils.MonitorAction.Start);
-                }
-            }
-
-            for (int i = 0; i < _threads; i++)
-            {
-                Interlocked.Increment(ref _threadsRunning);
-                Thread t = new Thread(new ThreadStart(this.RunStressThread));
-                t.Start();
-            }
-
-            while (_threadsRunning > 0)
-            {
-                Thread.Sleep(1000);
-            }
-
-            //Monitoring Stop
-            if (TestMetrics.MonitorEnabled)
-            {
-                if (_monitorloader != null)
-                    _monitorloader.Action(MonitorLoaderUtils.MonitorAction.Stop);
-            }
-
-            // Run any global cleanup
-            if (null != firstStressTest)
-            {
-                firstStressTest.RunGlobalCleanup();
-            }
-
-            // Write out all exceptions
-            _exceptions.TraceAllExceptions();
-            return _exceptions.GetExceptionsCount();
-        }
-
-
-        public void RunStressThread()
-        {
-            try
-            {
-                StressTest[] tests = new StressTest[_allTests.Count];
-                List<int> tmpWeightedLookup = new List<int>();
-
-                for (int i = 0; i < tests.Length; i++)
-                {
-                    tests[i] = _allTests[i].Clone();
-                    tests[i].RunSetup();
-
-                    for (int j = 0; j < tests[i].Weight; j++)
-                    {
-                        tmpWeightedLookup.Add(i);
-                    }
-                }
-
-                int[] weightedLookup = tmpWeightedLookup.ToArray();
-
-                Stopwatch timer = new Stopwatch();
-                long testDuration = (long)_duration * Stopwatch.Frequency;
-
-                timer.Reset();
-                timer.Start();
-
-                while (_continue && timer.ElapsedTicks < testDuration)
-                {
-                    int n = _rnd.Next(0, weightedLookup.Length);
-                    StressTest t = tests[weightedLookup[n]];
-
-                    if (TestMetrics.PrintMethodName)
-                    {
-                        FakeConsole.WriteLine("{0}: {1}", ++s_globalRequestsCounter, t.Title);
-                    }
-
-                    try
-                    {
-                        DeadlockDetection.AddTestThread();
-                        t.Run();
-                        if (_perfcounters != null)
-                            _perfcounters.IncrementRequestsCounter();
-                    }
-                    catch (Exception e)
-                    {
-                        if (_perfcounters != null)
-                            _perfcounters.IncrementExceptionsCounter();
-
-                        t.HandleException(e);
-
-                        bool thresholdExceeded = _exceptions.Record(t.Title, e);
-                        if (thresholdExceeded)
-                        {
-                            FakeConsole.WriteLine("Exception Threshold of {0} has been exceeded on {1} - Halting!\n",
-                                TestMetrics.ExceptionThreshold, t.Title);
-                            break;
-                        }
-                    }
-                    finally
-                    {
-                        DeadlockDetection.RemoveThread();
-                    }
-                }
-
-                foreach (StressTest t in tests)
-                {
-                    t.RunCleanup();
-                }
-            }
-            finally
-            {
-                _continue = false;
-                Interlocked.Decrement(ref _threadsRunning);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/StressTest.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/StressTest.cs
deleted file mode 100644 (file)
index c2637d5..0000000
+++ /dev/null
@@ -1,155 +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.Reflection;
-using System.Reflection.Emit;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-
-namespace DPStressHarness
-{
-    internal class StressTest : TestBase
-    {
-        private StressTestAttribute _attr;
-        private object _targetInstance;
-        private TestMethodDelegate _tmd;
-
-        // TODO: MethodInfo objects below can have associated delegates to improve
-        // runtime performance.
-        protected MethodInfo _globalSetupMethod;
-        protected MethodInfo _globalCleanupMethod;
-
-        public delegate void ExceptionHandler(Exception e);
-
-        /// <summary>
-        /// Cache the global exception handler method reference. It is
-        /// recommended not to actually use this reference to call the
-        /// method. Use the delegate instead.
-        /// </summary>
-        protected MethodInfo _globalExceptionHandlerMethod;
-
-        /// <summary>
-        /// Create a delegate to call global exception handler method.
-        /// Use this delegate to call test assembly's exception handler.
-        /// </summary>
-        protected ExceptionHandler _globalExceptionHandlerDelegate;
-
-        public StressTest(StressTestAttribute attr,
-                    MethodInfo testMethodInfo,
-                    MethodInfo globalSetupMethod,
-                    MethodInfo globalCleanupMethod,
-                    Type type,
-                    List<MethodInfo> setupMethods,
-                    List<MethodInfo> cleanupMethods,
-                    MethodInfo globalExceptionHandlerMethod)
-            : base(attr, testMethodInfo, type, setupMethods, cleanupMethods)
-        {
-            _attr = attr;
-            _globalSetupMethod = globalSetupMethod;
-            _globalCleanupMethod = globalCleanupMethod;
-            _globalExceptionHandlerMethod = globalExceptionHandlerMethod;
-        }
-
-        public StressTest Clone()
-        {
-            StressTest t = new StressTest(_attr, this._testMethod, this._globalSetupMethod, this._globalCleanupMethod, this._type, this._setupMethods, this._cleanupMethods, this._globalExceptionHandlerMethod);
-            return t;
-        }
-
-        private void InitTargetInstance()
-        {
-            _targetInstance = _type.GetConstructor(Type.EmptyTypes).Invoke(null);
-
-            // Create a delegate for exception handling on _targetInstance
-            if (_globalExceptionHandlerMethod != null)
-            {
-                _globalExceptionHandlerDelegate = (ExceptionHandler)_globalExceptionHandlerMethod.CreateDelegate(
-                    typeof(ExceptionHandler),
-                    _targetInstance
-                    );
-            }
-        }
-
-        /// <summary>
-        /// Perform any global initialization for the test assembly. For example, make the connection to the database, load a workspace, etc.
-        /// </summary>
-        public void RunGlobalSetup()
-        {
-            if (null == _targetInstance)
-            {
-                InitTargetInstance();
-            }
-
-            if (null != _globalSetupMethod)
-            {
-                _globalSetupMethod.Invoke(_targetInstance, null);
-            }
-        }
-
-        /// <summary>
-        /// Run any per-thread setup needed
-        /// </summary>
-        public void RunSetup()
-        {
-            // create an instance of the class that defines the test method.
-            if (null == _targetInstance)
-            {
-                InitTargetInstance();
-            }
-            _tmd = CreateTestMethodDelegate();
-
-            // Set variation fields on the target instance
-            SetVariations(_targetInstance);
-
-            // Execute the setup phase for this thread.
-            ExecuteSetupPhase(_targetInstance);
-        }
-
-        /// <summary>
-        /// Execute the test method(s)
-        /// </summary>
-        public override void Run()
-        {
-            _tmd(_targetInstance);
-        }
-
-        /// <summary>
-        /// Provide an opportunity to handle the exception
-        /// </summary>
-        /// <param name="e"></param>
-        public void HandleException(Exception e)
-        {
-            if (null != _globalExceptionHandlerDelegate)
-            {
-                _globalExceptionHandlerDelegate(e);
-            }
-        }
-
-        /// <summary>
-        /// Run any per-thread cleanup for the test
-        /// </summary>
-        public void RunCleanup()
-        {
-            ExecuteCleanupPhase(_targetInstance);
-        }
-
-        /// <summary>
-        /// Run final global cleanup for the test assembly. Could be used to release resources or for reporting, etc.
-        /// </summary>
-        public void RunGlobalCleanup()
-        {
-            if (null != _globalCleanupMethod)
-            {
-                _globalCleanupMethod.Invoke(_targetInstance, null);
-            }
-        }
-
-        public int Weight
-        {
-            get { return _attr.Weight; }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/System.Data.StressRunner.csproj b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/System.Data.StressRunner.csproj
deleted file mode 100644 (file)
index 8978d12..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <RootNamespace>DPStressHarness</RootNamespace>
-    <OutputType>Exe</OutputType>
-    <NoWarn>3021</NoWarn>
-    <Configurations>$(NetCoreAppCurrent)-Unix-Debug;$(NetCoreAppCurrent)-Unix-Release;$(NetCoreAppCurrent)-Windows_NT-Debug;$(NetCoreAppCurrent)-Windows_NT-Release;$(NetFrameworkCurrent)-Windows_NT-Debug;$(NetFrameworkCurrent)-Windows_NT-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\IMonitorLoader\IMonitorLoader.csproj" />
-  </ItemGroup>
-  <ItemGroup Condition=" '$(TargetsWindows)' != 'true' ">
-    <Compile Include="MemApi.Unix.cs" />
-  </ItemGroup>
-  <ItemGroup Condition=" '$(TargetsWindows)' == 'true' ">
-    <Compile Include="MemApi.Windows.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="DeadlockDetection.cs" />
-    <Compile Include="DeadlockDetectionTaskScheduler.cs" />
-    <Compile Include="ITestAttributeFilter.cs" />
-    <Compile Include="MonitorLoadUtils.cs" />
-    <Compile Include="Constants.cs" />
-    <Compile Include="FakeConsole.cs" />
-    <Compile Include="GlobalTestCleanupAttribute.cs" />
-    <Compile Include="GlobalTestSetupAttribute.cs" />
-    <Compile Include="GlobalExceptionHandlerAttribute.cs" />
-    <Compile Include="Logger.cs" />
-    <Compile Include="MultithreadedTest.cs" />
-    <Compile Include="PerfCounters.cs" />
-    <Compile Include="Program.cs" />
-    <Compile Include="RecordedExceptions.cs" />
-    <Compile Include="SqlScript.cs" />
-    <Compile Include="StressEngine.cs" />
-    <Compile Include="StressTest.cs" />
-    <Compile Include="Test.cs" />
-    <Compile Include="TestAttribute.cs" />
-    <Compile Include="TestBase.cs" />
-    <Compile Include="TestCleanupAttribute.cs" />
-    <Compile Include="TestFinder.cs" />
-    <Compile Include="TestMetrics.cs" />
-    <Compile Include="TestSetupAttribute.cs" />
-    <Compile Include="TestVariationAttribute.cs" />
-    <Compile Include="ThreadPoolTest.cs" />
-    <Compile Include="VersionUtil.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Test.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/Test.cs
deleted file mode 100644 (file)
index 63eb114..0000000
+++ /dev/null
@@ -1,119 +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.Reflection;
-using System.Reflection.Emit;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-
-
-namespace DPStressHarness
-{
-    internal class Test : TestBase
-    {
-        private TestAttribute _attr;
-        private int _overrideIterations = -1;
-        private int _overrideWarmup = -1;
-
-        public Test(TestAttribute attr,
-                    MethodInfo testMethodInfo,
-                    Type type,
-                    List<MethodInfo> setupMethods,
-                    List<MethodInfo> cleanupMethods)
-            : base(attr, testMethodInfo, type, setupMethods, cleanupMethods)
-        {
-            _attr = attr;
-        }
-
-
-        public override void Run()
-        {
-            try
-            {
-                // create an instance of the class that defines the test method.
-                object targetInstance = _type.GetConstructor(Type.EmptyTypes).Invoke(null);
-
-                SetVariations(targetInstance);
-
-                ExecuteSetupPhase(targetInstance);
-
-                TestMethodDelegate tmd = CreateTestMethodDelegate();
-
-                ExecuteTest(targetInstance, tmd);
-
-                ExecuteCleanupPhase(targetInstance);
-
-                LogTest();
-            }
-            catch (TargetInvocationException e)
-            {
-                LogTestFailure(e.InnerException.ToString());
-            }
-            catch (Exception e)
-            {
-                LogTestFailure(e.ToString());
-            }
-        }
-
-        protected void LogTest()
-        {
-            Logger logger = new Logger(TestMetrics.RunLabel, TestMetrics.IsOfficial, TestMetrics.Milestone, TestMetrics.Branch);
-            logger.AddTest(this.Title);
-
-            LogStandardMetrics(logger);
-
-            logger.AddTestMetric(Constants.TEST_METRIC_ELAPSED_SECONDS, string.Format("{0:F2}", TestMetrics.ElapsedSeconds), "sec", false);
-
-            logger.Save();
-
-            Console.WriteLine("{0}: Elapsed Seconds={1:F2}, Working Set={2}, Peak Working Set={3}, Private Bytes={4}",
-                              this.Title,
-                              TestMetrics.ElapsedSeconds,
-                              TestMetrics.WorkingSet,
-                              TestMetrics.PeakWorkingSet,
-                              TestMetrics.PrivateBytes);
-        }
-
-
-        private void ExecuteTest(object targetInstance, TestMethodDelegate tmd)
-        {
-            int warmupIterations = _attr.WarmupIterations;
-            int testIterations = _attr.TestIterations;
-
-            if (_overrideIterations >= 0)
-            {
-                testIterations = _overrideIterations;
-            }
-            if (_overrideWarmup >= 0)
-            {
-                warmupIterations = _overrideWarmup;
-            }
-
-            /** do some cleanup to make memory tests more accurate **/
-            System.GC.Collect();
-            System.GC.WaitForPendingFinalizers();
-            System.GC.Collect();
-
-            IntPtr h = MemApi.GetCurrentProcess();
-            bool fRes = MemApi.SetProcessWorkingSetSize(h, -1, -1);
-            /****/
-
-            System.Threading.Thread.Sleep(10000);
-
-            for (int i = 0; i < warmupIterations; i++)
-            {
-                tmd(targetInstance);
-            }
-
-            TestMetrics.StartCollection();
-            for (int i = 0; i < testIterations; i++)
-            {
-                tmd(targetInstance);
-            }
-            TestMetrics.StopCollection();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestAttribute.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestAttribute.cs
deleted file mode 100644 (file)
index 3146c2d..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    public enum TestPriority
-    {
-        BVT = 0,
-        High = 1,
-        Medium = 2,
-        Low = 3
-    }
-
-    public class TestAttributeBase : Attribute
-    {
-        private string _title;
-        private string _description = "none provided";
-        private string _applicationName = "unknown";
-        private string _improvement = "ADONETV3";
-        private string _owner = "unknown";
-        private string _category = "unknown";
-        private TestPriority _priority = TestPriority.BVT;
-
-        public TestAttributeBase(string title)
-        {
-            _title = title;
-        }
-
-        public string Title
-        {
-            get { return _title; }
-            set { _title = value; }
-        }
-
-        public string Description
-        {
-            get { return _description; }
-            set { _description = value; }
-        }
-
-        public string Improvement
-        {
-            get { return _improvement; }
-            set { _improvement = value; }
-        }
-
-        public string Owner
-        {
-            get { return _owner; }
-            set { _owner = value; }
-        }
-
-        public string ApplicationName
-        {
-            get { return _applicationName; }
-            set { _applicationName = value; }
-        }
-
-        public TestPriority Priority
-        {
-            get { return _priority; }
-            set { _priority = value; }
-        }
-
-        public string Category
-        {
-            get { return _category; }
-            set { _category = value; }
-        }
-    }
-
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
-    public class TestAttribute : TestAttributeBase
-    {
-        private int _warmupIterations = 0;
-        private int _testIterations = 1;
-
-        public TestAttribute(string title) : base(title)
-        {
-        }
-
-        public int WarmupIterations
-        {
-            get
-            {
-                string propName = "WarmupIterations";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _warmupIterations;
-                }
-            }
-            set { _warmupIterations = value; }
-        }
-
-        public int TestIterations
-        {
-            get
-            {
-                string propName = "TestIterations";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _testIterations;
-                }
-            }
-            set { _testIterations = value; }
-        }
-    }
-
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
-    public class StressTestAttribute : TestAttributeBase
-    {
-        private int _weight = 1;
-
-        public StressTestAttribute(string title)
-            : base(title)
-        {
-        }
-
-        public int Weight
-        {
-            get { return _weight; }
-            set { _weight = value; }
-        }
-    }
-
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
-    public class MultiThreadedTestAttribute : TestAttributeBase
-    {
-        private int _warmupDuration = 60;
-        private int _testDuration = 60;
-        private int _threads = 16;
-
-        public MultiThreadedTestAttribute(string title)
-            : base(title)
-        {
-        }
-
-        public int WarmupDuration
-        {
-            get
-            {
-                string propName = "WarmupDuration";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _warmupDuration;
-                }
-            }
-            set { _warmupDuration = value; }
-        }
-
-        public int TestDuration
-        {
-            get
-            {
-                string propName = "TestDuration";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _testDuration;
-                }
-            }
-            set { _testDuration = value; }
-        }
-
-        public int Threads
-        {
-            get
-            {
-                string propName = "Threads";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _threads;
-                }
-            }
-            set { _threads = value; }
-        }
-    }
-
-    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
-    public class ThreadPoolTestAttribute : TestAttributeBase
-    {
-        private int _warmupDuration = 60;
-        private int _testDuration = 60;
-        private int _threads = 64;
-
-        public ThreadPoolTestAttribute(string title)
-            : base(title)
-        {
-        }
-
-        public int WarmupDuration
-        {
-            get
-            {
-                string propName = "WarmupDuration";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _warmupDuration;
-                }
-            }
-            set { _warmupDuration = value; }
-        }
-
-        public int TestDuration
-        {
-            get
-            {
-                string propName = "TestDuration";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _testDuration;
-                }
-            }
-            set { _testDuration = value; }
-        }
-
-        public int Threads
-        {
-            get
-            {
-                string propName = "Threads";
-
-                if (TestMetrics.Overrides.ContainsKey(propName))
-                {
-                    return int.Parse(TestMetrics.Overrides[propName]);
-                }
-                else
-                {
-                    return _threads;
-                }
-            }
-            set { _threads = value; }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestBase.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestBase.cs
deleted file mode 100644 (file)
index 72eb006..0000000
+++ /dev/null
@@ -1,173 +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.Reflection;
-using System.Reflection.Emit;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace DPStressHarness
-{
-    public abstract class TestBase
-    {
-        private TestAttributeBase _attr;
-        private string _variationSuffix = "";
-
-        [System.CLSCompliantAttribute(false)]
-        protected MethodInfo _testMethod;
-        [System.CLSCompliantAttribute(false)]
-        protected Type _type;
-
-        [System.CLSCompliantAttribute(false)]
-        protected List<MethodInfo> _setupMethods;
-
-        [System.CLSCompliantAttribute(false)]
-        protected List<MethodInfo> _cleanupMethods;
-
-        protected delegate void TestMethodDelegate(object t);
-
-        public TestBase(TestAttributeBase attr,
-                        MethodInfo testMethodInfo,
-                        Type type,
-                        List<MethodInfo> setupMethods,
-                        List<MethodInfo> cleanupMethods)
-        {
-            _attr = attr;
-            _testMethod = testMethodInfo;
-            _type = type;
-            _setupMethods = setupMethods;
-            _cleanupMethods = cleanupMethods;
-        }
-
-        public string Title
-        {
-            get { return _attr.Title + _variationSuffix; }
-        }
-
-        public string Description
-        {
-            get { return _attr.Description; }
-        }
-
-        public string Category
-        {
-            get { return _attr.Category; }
-        }
-
-        public TestPriority Priority
-        {
-            get { return _attr.Priority; }
-        }
-
-        public List<string> GetVariations()
-        {
-            FieldInfo[] fields = _type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
-
-            List<string> variations = new List<string>(10);
-            foreach (FieldInfo fi in fields)
-            {
-                TestVariationAttribute[] attrs = (TestVariationAttribute[])fi.GetCustomAttributes(typeof(TestVariationAttribute), false);
-
-                foreach (TestVariationAttribute testVarAttr in attrs)
-                {
-                    if (!variations.Contains(testVarAttr.VariationName))
-                    {
-                        variations.Add(testVarAttr.VariationName);
-                    }
-                }
-            }
-
-            return variations;
-        }
-
-        public abstract void Run();
-
-
-        protected void ExecuteSetupPhase(object targetInstance)
-        {
-            if (_setupMethods != null)
-            {
-                foreach (MethodInfo setupMthd in _setupMethods)
-                {
-                    setupMthd.Invoke(targetInstance, null);
-                }
-            }
-        }
-
-        protected void ExecuteCleanupPhase(object targetInstance)
-        {
-            if (_cleanupMethods != null)
-            {
-                foreach (MethodInfo cleanupMethod in _cleanupMethods)
-                {
-                    cleanupMethod.Invoke(targetInstance, null);
-                }
-            }
-        }
-
-        protected void SetVariations(object targetInstance)
-        {
-            FieldInfo[] fields = targetInstance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
-
-            foreach (FieldInfo fi in fields)
-            {
-                TestVariationAttribute[] attrs = (TestVariationAttribute[])fi.GetCustomAttributes(typeof(TestVariationAttribute), false);
-
-                foreach (TestVariationAttribute testVarAttr in attrs)
-                {
-                    foreach (string specifiedVariation in TestMetrics.Variations)
-                    {
-                        if (specifiedVariation.Equals(testVarAttr.VariationName))
-                        {
-                            fi.SetValue(targetInstance, testVarAttr.VariationValue);
-                            _variationSuffix += "_" + testVarAttr.VariationName;
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-
-        protected TestMethodDelegate CreateTestMethodDelegate()
-        {
-            Type[] args = { typeof(object) };
-            return new TestMethodDelegate((instance) => _testMethod.Invoke(instance, null));
-        }
-
-
-        protected void LogTestFailure(string exceptionData)
-        {
-            Console.WriteLine("{0}: Failed", this.Title);
-            Console.WriteLine(exceptionData);
-
-            Logger logger = new Logger(TestMetrics.RunLabel, false, TestMetrics.Milestone, TestMetrics.Branch);
-            logger.AddTest(this.Title);
-            logger.AddTestMetric("Test Assembly", _testMethod.Module.FullyQualifiedName, null);
-            logger.AddTestException(exceptionData);
-            logger.Save();
-        }
-
-        protected void LogStandardMetrics(Logger logger)
-        {
-            logger.AddTestMetric(Constants.TEST_METRIC_TEST_ASSEMBLY, _testMethod.Module.FullyQualifiedName, null);
-            logger.AddTestMetric(Constants.TEST_METRIC_TEST_IMPROVEMENT, _attr.Improvement, null);
-            logger.AddTestMetric(Constants.TEST_METRIC_TEST_OWNER, _attr.Owner, null);
-            logger.AddTestMetric(Constants.TEST_METRIC_TEST_CATEGORY, _attr.Category, null);
-            logger.AddTestMetric(Constants.TEST_METRIC_TEST_PRIORITY, _attr.Priority.ToString(), null);
-            logger.AddTestMetric(Constants.TEST_METRIC_APPLICATION_NAME, _attr.Improvement, null);
-
-            if (TestMetrics.TargetAssembly != null)
-            {
-                logger.AddTestMetric(Constants.TEST_METRIC_TARGET_ASSEMBLY_NAME, (new AssemblyName(TestMetrics.TargetAssembly.FullName)).Name, null);
-            }
-
-            logger.AddTestMetric(Constants.TEST_METRIC_PEAK_WORKING_SET, string.Format("{0}", TestMetrics.PeakWorkingSet), "bytes");
-            logger.AddTestMetric(Constants.TEST_METRIC_WORKING_SET, string.Format("{0}", TestMetrics.WorkingSet), "bytes");
-            logger.AddTestMetric(Constants.TEST_METRIC_PRIVATE_BYTES, string.Format("{0}", TestMetrics.PrivateBytes), "bytes");
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestCleanupAttribute.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestCleanupAttribute.cs
deleted file mode 100644 (file)
index 32bc5ee..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
-    public class TestCleanupAttribute : Attribute
-    {
-        public TestCleanupAttribute()
-        {
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestFinder.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestFinder.cs
deleted file mode 100644 (file)
index 8e491e7..0000000
+++ /dev/null
@@ -1,167 +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.Reflection;
-using System.IO;
-
-namespace DPStressHarness
-{
-    internal class TestFinder
-    {
-        private static AssemblyName s_assemblyName;
-
-        public static AssemblyName AssemblyName
-        {
-            get { return s_assemblyName; }
-            set { s_assemblyName = value; }
-        }
-
-        public static IEnumerable<TestBase> GetTests(Assembly assembly)
-        {
-            List<TestBase> tests = new List<TestBase>();
-
-
-            Type[] typesInModule = null;
-            try
-            {
-                typesInModule = assembly.GetTypes();
-            }
-            catch (ReflectionTypeLoadException ex)
-            {
-                Console.WriteLine("ReflectionTypeLoadException Errors");
-                foreach (Exception loadEx in ex.LoaderExceptions)
-                {
-                    Console.WriteLine("\t" + loadEx.Message);
-                }
-            }
-            catch (Exception ex)
-            {
-                Console.WriteLine("Error." + ex.Message);
-            }
-
-            foreach (Type t in typesInModule)
-            {
-                MethodInfo[] methods = t.GetMethods(BindingFlags.Instance | BindingFlags.Public);
-                List<MethodInfo> setupMethods = new List<MethodInfo>();
-                List<MethodInfo> cleanupMethods = new List<MethodInfo>();
-
-                MethodInfo globalSetupMethod = null;
-                MethodInfo globalCleanupMethod = null;
-                MethodInfo globalExceptionHandlerMethod = null;
-
-                foreach (MethodInfo m in methods)
-                {
-                    GlobalTestSetupAttribute[] globalSetupAttributes = (GlobalTestSetupAttribute[])m.GetCustomAttributes(typeof(GlobalTestSetupAttribute), true);
-                    if (globalSetupAttributes.Length > 0)
-                    {
-                        if (null == globalSetupMethod)
-                        {
-                            globalSetupMethod = m;
-                        }
-                        else
-                        {
-                            throw new NotSupportedException("Only one GlobalTestSetup method may be specified per type.");
-                        }
-                    }
-
-                    GlobalTestCleanupAttribute[] globalCleanupAttributes = (GlobalTestCleanupAttribute[])m.GetCustomAttributes(typeof(GlobalTestCleanupAttribute), true);
-                    if (globalCleanupAttributes.Length > 0)
-                    {
-                        if (null == globalCleanupMethod)
-                        {
-                            globalCleanupMethod = m;
-                        }
-                        else
-                        {
-                            throw new NotSupportedException("Only one GlobalTestCleanup method may be specified per type.");
-                        }
-                    }
-
-                    GlobalExceptionHandlerAttribute[] globalExceptionHandlerAttributes = (GlobalExceptionHandlerAttribute[])m.GetCustomAttributes(typeof(GlobalExceptionHandlerAttribute), true);
-                    if (globalExceptionHandlerAttributes.Length > 0)
-                    {
-                        if (null == globalExceptionHandlerMethod)
-                        {
-                            globalExceptionHandlerMethod = m;
-                        }
-                        else
-                        {
-                            throw new NotSupportedException("Only one GlobalExceptionHandler method may be specified.");
-                        }
-                    }
-
-                    TestSetupAttribute[] testSetupAttrs = (TestSetupAttribute[])m.GetCustomAttributes(typeof(TestSetupAttribute), true);
-                    if (testSetupAttrs.Length > 0)
-                    {
-                        setupMethods.Add(m); ;
-                    }
-
-                    TestCleanupAttribute[] testCleanupAttrs = (TestCleanupAttribute[])m.GetCustomAttributes(typeof(TestCleanupAttribute), true);
-                    if (testCleanupAttrs.Length > 0)
-                    {
-                        cleanupMethods.Add(m); ;
-                    }
-                }
-
-                foreach (MethodInfo m in methods)
-                {
-                    // add single-threaded tests to the list
-                    TestAttribute[] testAttrs = (TestAttribute[])m.GetCustomAttributes(typeof(TestAttribute), true);
-                    foreach (TestAttribute attr in testAttrs)
-                    {
-                        tests.Add(new Test(attr, m, t, setupMethods, cleanupMethods));
-                    }
-
-                    // add any declared stress tests.
-                    StressTestAttribute[] stressTestAttrs = (StressTestAttribute[])m.GetCustomAttributes(typeof(StressTestAttribute), true);
-                    foreach (StressTestAttribute attr in stressTestAttrs)
-                    {
-                        if (TestMetrics.IncludeTest(attr) && MatchFilter(attr))
-                            tests.Add(new StressTest(attr, m, globalSetupMethod, globalCleanupMethod, t, setupMethods, cleanupMethods, globalExceptionHandlerMethod));
-                    }
-
-                    // add multi-threaded (non thread pool) tests to the list
-                    MultiThreadedTestAttribute[] multiThreadedTestAttrs = (MultiThreadedTestAttribute[])m.GetCustomAttributes(typeof(MultiThreadedTestAttribute), true);
-                    foreach (MultiThreadedTestAttribute attr in multiThreadedTestAttrs)
-                    {
-                        if (TestMetrics.IncludeTest(attr))
-                            tests.Add(new MultiThreadedTest(attr, m, t, setupMethods, cleanupMethods));
-                    }
-
-                    // add multi-threaded (with thread pool) tests to the list
-                    ThreadPoolTestAttribute[] threadPoolTestAttrs = (ThreadPoolTestAttribute[])m.GetCustomAttributes(typeof(ThreadPoolTestAttribute), true);
-                    foreach (ThreadPoolTestAttribute attr in threadPoolTestAttrs)
-                    {
-                        if (TestMetrics.IncludeTest(attr))
-                            tests.Add(new ThreadPoolTest(attr, m, t, setupMethods, cleanupMethods));
-                    }
-                }
-            }
-
-            return tests;
-        }
-
-        private static bool MatchFilter(StressTestAttribute attr)
-        {
-            // This change should not have impacts on any existing tests.
-            //    1. If filter is not provided in command line, we do not apply filter and select all the tests.
-            //    2. If current test attribute (such as StressTestAttribute) does not implement ITestAttriuteFilter, it is not affected and still selected.
-
-            if (string.IsNullOrEmpty(TestMetrics.Filter))
-            {
-                return true;
-            }
-
-            var filter = attr as ITestAttributeFilter;
-            if (filter == null)
-            {
-                return true;
-            }
-
-            return filter.MatchFilter(TestMetrics.Filter);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestMetrics.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestMetrics.cs
deleted file mode 100644 (file)
index eb4952b..0000000
+++ /dev/null
@@ -1,362 +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.Collections.Generic;
-using System.Reflection;
-using System.Globalization;
-
-namespace DPStressHarness
-{
-    public static class TestMetrics
-    {
-        private const string _defaultValue = "unknown";
-
-        private static bool s_valid = false;
-        private static bool s_reset = true;
-        private static Stopwatch s_stopwatch = new Stopwatch();
-        private static long s_workingSet;
-        private static long s_peakWorkingSet;
-        private static long s_privateBytes;
-        private static Assembly s_targetAssembly;
-        private static string s_fileVersion = _defaultValue;
-        private static string s_privateBuild = _defaultValue;
-        private static string s_runLabel = DateTime.Now.ToString();
-        private static Dictionary<string, string> s_overrides;
-        private static List<string> s_variations = null;
-        private static List<string> s_selectedTests = null;
-        private static bool s_isOfficial = false;
-        private static string s_milestone = _defaultValue;
-        private static string s_branch = _defaultValue;
-        private static List<string> s_categories = null;
-        private static bool s_profileMeasuredCode = false;
-        private static int s_stressThreads = 16;
-        private static int s_stressDuration = -1;
-        private static int? s_exceptionThreshold = null;
-        private static bool s_monitorenabled = false;
-        private static string s_monitormachinename = "localhost";
-        private static int s_randomSeed = 0;
-        private static string s_filter = null;
-        private static bool s_printMethodName = false;
-
-        /// <summary>Starts the sample profiler.</summary>
-        /// <remarks>
-        /// Do not inline to avoid errors when the functionality is not used
-        /// and the profiling DLL is not available.
-        /// </remarks>
-        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
-        private static void InternalStartProfiling()
-        {
-            //            Microsoft.VisualStudio.Profiler.DataCollection.StartProfile(
-            //                Microsoft.VisualStudio.Profiler.ProfileLevel.Global,
-            //                Microsoft.VisualStudio.Profiler.DataCollection.CurrentId);
-        }
-
-        /// <summary>Stops the sample profiler.</summary>
-        /// <remarks>
-        /// Do not inline to avoid errors when the functionality is not used
-        /// and the profiling DLL is not available.
-        /// </remarks>
-        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
-        private static void InternalStopProfiling()
-        {
-            //            Microsoft.VisualStudio.Profiler.DataCollection.StopProfile(
-            //                Microsoft.VisualStudio.Profiler.ProfileLevel.Global,
-            //                Microsoft.VisualStudio.Profiler.DataCollection.CurrentId);
-        }
-
-        public static void StartCollection()
-        {
-            s_valid = false;
-
-            s_stopwatch.Reset();
-            s_stopwatch.Start();
-            s_reset = true;
-        }
-
-        public static void StartProfiling()
-        {
-            if (s_profileMeasuredCode)
-            {
-                InternalStartProfiling();
-            }
-        }
-
-        public static void StopProfiling()
-        {
-            if (s_profileMeasuredCode)
-            {
-                InternalStopProfiling();
-            }
-        }
-
-        public static void StopCollection()
-        {
-            s_stopwatch.Stop();
-
-            Process p = Process.GetCurrentProcess();
-            s_workingSet = p.WorkingSet64;
-            s_peakWorkingSet = p.PeakWorkingSet64;
-            s_privateBytes = p.PrivateMemorySize64;
-
-            s_valid = true;
-        }
-
-        public static void PauseTimer()
-        {
-            s_stopwatch.Stop();
-        }
-
-        public static void UnPauseTimer()
-        {
-            if (s_reset)
-            {
-                s_stopwatch.Reset();
-                s_reset = false;
-            }
-
-            s_stopwatch.Start();
-        }
-
-        private static void ThrowIfInvalid()
-        {
-            if (!s_valid) throw new InvalidOperationException("Collection must be stopped before accessing this metric.");
-        }
-
-        public static void Reset()
-        {
-            s_valid = false;
-            s_reset = true;
-            s_stopwatch = new Stopwatch();
-            s_workingSet = new long();
-            s_peakWorkingSet = new long();
-            s_privateBytes = new long();
-            s_targetAssembly = null;
-            s_fileVersion = _defaultValue;
-            s_privateBuild = _defaultValue;
-            s_runLabel = DateTime.Now.ToString();
-            s_overrides = null;
-            s_variations = null;
-            s_selectedTests = null;
-            s_isOfficial = false;
-            s_milestone = _defaultValue;
-            s_branch = _defaultValue;
-            s_categories = null;
-            s_profileMeasuredCode = false;
-            s_stressThreads = 16;
-            s_stressDuration = -1;
-            s_exceptionThreshold = null;
-            s_monitorenabled = false;
-            s_monitormachinename = "localhost";
-            s_randomSeed = 0;
-            s_filter = null;
-            s_printMethodName = false;
-        }
-
-        public static string FileVersion
-        {
-            get { return s_fileVersion; }
-            set { s_fileVersion = value; }
-        }
-
-        public static string PrivateBuild
-        {
-            get { return s_privateBuild; }
-            set { s_privateBuild = value; }
-        }
-
-        public static Assembly TargetAssembly
-        {
-            get { return s_targetAssembly; }
-
-            set
-            {
-                s_targetAssembly = value;
-                s_fileVersion = VersionUtil.GetFileVersion(s_targetAssembly.ManifestModule.FullyQualifiedName);
-                s_privateBuild = VersionUtil.GetPrivateBuild(s_targetAssembly.ManifestModule.FullyQualifiedName);
-            }
-        }
-
-        public static string RunLabel
-        {
-            get { return s_runLabel; }
-            set { s_runLabel = value; }
-        }
-
-        public static string Milestone
-        {
-            get { return s_milestone; }
-            set { s_milestone = value; }
-        }
-
-        public static string Branch
-        {
-            get { return s_branch; }
-            set { s_branch = value; }
-        }
-
-        public static bool IsOfficial
-        {
-            get { return s_isOfficial; }
-            set { s_isOfficial = value; }
-        }
-
-        public static bool IsDefaultValue(string val)
-        {
-            return val.Equals(_defaultValue);
-        }
-
-        public static double ElapsedSeconds
-        {
-            get
-            {
-                ThrowIfInvalid();
-                return s_stopwatch.ElapsedMilliseconds / 1000.0;
-            }
-        }
-
-        public static long WorkingSet
-        {
-            get
-            {
-                ThrowIfInvalid();
-                return s_workingSet;
-            }
-        }
-
-        public static long PeakWorkingSet
-        {
-            get
-            {
-                ThrowIfInvalid();
-                return s_peakWorkingSet;
-            }
-        }
-
-        public static long PrivateBytes
-        {
-            get
-            {
-                ThrowIfInvalid();
-                return s_privateBytes;
-            }
-        }
-
-
-        public static Dictionary<string, string> Overrides
-        {
-            get
-            {
-                if (s_overrides == null)
-                {
-                    s_overrides = new Dictionary<string, string>(8);
-                }
-                return s_overrides;
-            }
-        }
-
-        public static List<string> Variations
-        {
-            get
-            {
-                if (s_variations == null)
-                {
-                    s_variations = new List<string>(8);
-                }
-
-                return s_variations;
-            }
-        }
-
-        public static List<string> SelectedTests
-        {
-            get
-            {
-                if (s_selectedTests == null)
-                {
-                    s_selectedTests = new List<string>(8);
-                }
-
-                return s_selectedTests;
-            }
-        }
-
-        public static bool IncludeTest(TestAttributeBase test)
-        {
-            if (s_selectedTests == null || s_selectedTests.Count == 0)
-                return true; // user has no selection - run all
-            else
-                return s_selectedTests.Contains(test.Title);
-        }
-
-        public static List<string> Categories
-        {
-            get
-            {
-                if (s_categories == null)
-                {
-                    s_categories = new List<string>(8);
-                }
-
-                return s_categories;
-            }
-        }
-
-        public static bool ProfileMeasuredCode
-        {
-            get { return s_profileMeasuredCode; }
-            set { s_profileMeasuredCode = value; }
-        }
-
-        public static int StressDuration
-        {
-            get { return s_stressDuration; }
-            set { s_stressDuration = value; }
-        }
-
-        public static int StressThreads
-        {
-            get { return s_stressThreads; }
-            set { s_stressThreads = value; }
-        }
-
-        public static int? ExceptionThreshold
-        {
-            get { return s_exceptionThreshold; }
-            set { s_exceptionThreshold = value; }
-        }
-
-        public static bool MonitorEnabled
-        {
-            get { return s_monitorenabled; }
-            set { s_monitorenabled = value; }
-        }
-
-
-        public static string MonitorMachineName
-        {
-            get { return s_monitormachinename; }
-            set { s_monitormachinename = value; }
-        }
-
-        public static int RandomSeed
-        {
-            get { return s_randomSeed; }
-            set { s_randomSeed = value; }
-        }
-
-        public static string Filter
-        {
-            get { return s_filter; }
-            set { s_filter = value; }
-        }
-
-        public static bool PrintMethodName
-        {
-            get { return s_printMethodName; }
-            set { s_printMethodName = value; }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestSetupAttribute.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestSetupAttribute.cs
deleted file mode 100644 (file)
index 5626032..0000000
+++ /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;
-
-namespace DPStressHarness
-{
-    [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
-    public class TestSetupAttribute : Attribute
-    {
-        public TestSetupAttribute()
-        {
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestVariationAttribute.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/TestVariationAttribute.cs
deleted file mode 100644 (file)
index e54acfa..0000000
+++ /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.Collections.Generic;
-using System.Text;
-
-namespace DPStressHarness
-{
-    [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)]
-    public class TestVariationAttribute : Attribute
-    {
-        private string _variationName;
-        private object _variationValue;
-
-        public TestVariationAttribute(string variationName, object variationValue)
-        {
-            _variationName = variationName;
-            _variationValue = variationValue;
-        }
-
-        public string VariationName
-        {
-            get { return _variationName; }
-            set { _variationName = value; }
-        }
-
-        public object VariationValue
-        {
-            get { return _variationValue; }
-            set { _variationValue = value; }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/ThreadPoolTest.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/ThreadPoolTest.cs
deleted file mode 100644 (file)
index f065c15..0000000
+++ /dev/null
@@ -1,174 +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.Reflection;
-using System.Reflection.Emit;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Threading;
-
-namespace DPStressHarness
-{
-    internal class ThreadPoolTest : TestBase
-    {
-        private ThreadPoolTestAttribute _attr;
-        public static bool _continue;
-        public static int _threadsRunning;
-        public static int _rps;
-        public static WaitCallback _waitCallback = new WaitCallback(RunThreadPool);
-        public static Exception _firstException = null;
-
-        private struct TestInfo
-        {
-            public object _instance;
-            public TestMethodDelegate _delegateTest;
-        }
-
-        public ThreadPoolTest(ThreadPoolTestAttribute attr,
-                                 MethodInfo testMethodInfo,
-                                 Type type,
-                                 List<MethodInfo> setupMethods,
-                                 List<MethodInfo> cleanupMethods)
-            : base(attr, testMethodInfo, type, setupMethods, cleanupMethods)
-        {
-            _attr = attr;
-        }
-
-        public override void Run()
-        {
-            try
-            {
-                Stopwatch timer = new Stopwatch();
-                long warmupDuration = (long)_attr.WarmupDuration * Stopwatch.Frequency;
-                long testDuration = (long)_attr.TestDuration * Stopwatch.Frequency;
-                int threads = _attr.Threads;
-
-                TestInfo[] info = new TestInfo[threads];
-                ConstructorInfo targetConstructor = _type.GetConstructor(Type.EmptyTypes);
-
-                for (int i = 0; i < threads; i++)
-                {
-                    info[i] = new TestInfo();
-                    info[i]._instance = targetConstructor.Invoke(null);
-                    info[i]._delegateTest = CreateTestMethodDelegate();
-
-                    ExecuteSetupPhase(info[i]._instance);
-                }
-
-                _firstException = null;
-                _continue = true;
-                _rps = 0;
-
-                for (int i = 0; i < threads; i++)
-                {
-                    Interlocked.Increment(ref _threadsRunning);
-                    ThreadPool.QueueUserWorkItem(_waitCallback, info[i]);
-                }
-
-                timer.Reset();
-                timer.Start();
-
-                while (timer.ElapsedTicks < warmupDuration)
-                {
-                    Thread.Sleep(1000);
-                }
-
-                int warmupRequests = Interlocked.Exchange(ref _rps, 0);
-                timer.Reset();
-                timer.Start();
-                TestMetrics.StartCollection();
-
-                while (timer.ElapsedTicks < testDuration)
-                {
-                    Thread.Sleep(1000);
-                }
-
-                int requests = Interlocked.Exchange(ref _rps, 0);
-                double elapsedSeconds = timer.ElapsedTicks / Stopwatch.Frequency;
-                TestMetrics.StopCollection();
-                _continue = false;
-
-                while (_threadsRunning > 0)
-                {
-                    Thread.Sleep(1000);
-                }
-
-                for (int i = 0; i < threads; i++)
-                {
-                    ExecuteCleanupPhase(info[i]._instance);
-                }
-
-                double rps = (double)requests / elapsedSeconds;
-
-                if (_firstException == null)
-                {
-                    LogTest(rps);
-                }
-                else
-                {
-                    LogTestFailure(_firstException.ToString());
-                }
-            }
-            catch (TargetInvocationException e)
-            {
-                LogTestFailure(e.InnerException.ToString());
-            }
-            catch (Exception e)
-            {
-                LogTestFailure(e.ToString());
-            }
-        }
-
-
-        public static void RunThreadPool(object state)
-        {
-            try
-            {
-                TestInfo info = (TestInfo)state;
-                info._delegateTest(info._instance);
-                Interlocked.Increment(ref _rps);
-            }
-            catch (Exception e)
-            {
-                if (_firstException == null)
-                {
-                    _firstException = e;
-                }
-                _continue = false;
-            }
-            finally
-            {
-                if (_continue)
-                {
-                    ThreadPool.QueueUserWorkItem(_waitCallback, state);
-                }
-                else
-                {
-                    Interlocked.Decrement(ref _threadsRunning);
-                }
-            }
-        }
-
-        protected void LogTest(double rps)
-        {
-            Logger logger = new Logger(TestMetrics.RunLabel, TestMetrics.IsOfficial, TestMetrics.Milestone, TestMetrics.Branch);
-            logger.AddTest(this.Title);
-
-            LogStandardMetrics(logger);
-
-            logger.AddTestMetric(Constants.TEST_METRIC_RPS, string.Format("{0:F2}", rps), "rps", true);
-
-            logger.Save();
-
-            Console.WriteLine("{0}: Requests per Second={1:F2}, Working Set={2}, Peak Working Set={3}, Private Bytes={4}",
-                              this.Title,
-                              rps,
-                              TestMetrics.WorkingSet,
-                              TestMetrics.PeakWorkingSet,
-                              TestMetrics.PrivateBytes);
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/VersionUtil.cs b/src/libraries/System.Data.SqlClient/tests/StressTests/System.Data.StressRunner/VersionUtil.cs
deleted file mode 100644 (file)
index dd4e76e..0000000
+++ /dev/null
@@ -1,42 +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;
-using System.Diagnostics;
-using System.Reflection;
-
-#pragma warning disable 618
-
-namespace DPStressHarness
-{
-    public class VersionUtil
-    {
-        public static string GetFileVersion(string moduleName)
-        {
-            FileVersionInfo info = GetFileVersionInfo(moduleName);
-            return info.FileVersion;
-        }
-
-        public static string GetPrivateBuild(string moduleName)
-        {
-            FileVersionInfo info = GetFileVersionInfo(moduleName);
-            return info.PrivateBuild;
-        }
-
-        private static FileVersionInfo GetFileVersionInfo(string moduleName)
-        {
-            if (File.Exists(moduleName))
-            {
-                return FileVersionInfo.GetVersionInfo(Path.GetFullPath(moduleName));
-            }
-            else
-            {
-                string moduleInRuntimeDir = AppContext.BaseDirectory + moduleName;
-                return FileVersionInfo.GetVersionInfo(moduleInRuntimeDir);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/Configurations.props b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/Configurations.props
deleted file mode 100644 (file)
index 69f0b7d..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0-Unix;
-      netstandard2.0-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/FederatedAuthenticationTicketService.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/FederatedAuthenticationTicketService.cs
deleted file mode 100644 (file)
index 6f1d603..0000000
+++ /dev/null
@@ -1,42 +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.SqlServer.TDS.Login7;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.FederatedAuthentication
-{
-    /// <summary>
-    /// Point of entry for the Federated Authentication Ticket Service
-    /// </summary>
-    public class FederatedAuthenticationTicketService
-    {
-        /// <summary>
-        /// Given a Federated Authentication ticket, returns the Session Key from the authentication service
-        /// </summary>
-        public static IFederatedAuthenticationTicket DecryptTicket(TDSFedAuthLibraryType ticketType, byte[] encryptedTicket)
-        {
-            if (encryptedTicket == null)
-            {
-                throw new NullReferenceException("encryptedTicket is null. Unable to decrypt.");
-            }
-
-            switch (ticketType)
-            {
-                case TDSFedAuthLibraryType.IDCRL:
-                    return RpsTicket.DecryptTicket(encryptedTicket);
-
-                case TDSFedAuthLibraryType.SECURITY_TOKEN:
-                    return JwtTicket.DecryptTicket(encryptedTicket);
-
-                case TDSFedAuthLibraryType.ADAL:
-                    // For now, fake fed auth tokens are sent for ADAL, so just return null
-                    return null;
-
-                default:
-                    throw new ArgumentOutOfRangeException("Unexpected Federated Authentication ticket type.");
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/IFederatedAuthenticationTicket.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/IFederatedAuthenticationTicket.cs
deleted file mode 100644 (file)
index 78a111e..0000000
+++ /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.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.FederatedAuthentication
-{
-    /// <summary>
-    /// Interface for federated authentication ticket
-    /// </summary>
-    public interface IFederatedAuthenticationTicket
-    {
-        /// <summary>
-        /// Computes and returns the signature of the provided buffer using the internal session Key associated with the auth
-        /// ticket.
-        /// </summary>
-        byte[] GetSignature(byte[] bufferToSign);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/Rps.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/Rps.cs
deleted file mode 100644 (file)
index ab9e0c3..0000000
+++ /dev/null
@@ -1,126 +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.Reflection;
-using System.Linq;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.FederatedAuthentication
-{
-    /// <summary>
-    /// Wrapper for dynamic loading of RPS dll
-    /// </summary>
-    internal class RPS
-    {
-        /// <summary>
-        /// Instance of the dynamically loaded RPS assembly from Microsoft.Passport.RPS
-        /// </summary>
-        private Assembly _rpsAssembly = null;
-
-        /// <summary>
-        /// Type of Microsoft.Passport.RPS.RPS
-        /// </summary>
-        private readonly Type _rpsType = null;
-
-        /// <summary>
-        /// Type of Microsoft.Passport.RPS.RPSTicket
-        /// </summary>
-        private readonly Type _rpsTicketType = null;
-
-        /// <summary>
-        /// Type of Microsoft.Passport.RPS.RPSPropBag
-        /// </summary>
-        private readonly Type _rpsPropBagType = null;
-
-        /// <summary>
-        /// Type of Microsoft.Passport.RPS.RPSAuth
-        /// </summary>
-        private readonly Type _rpsAuthType = null;
-
-        /// <summary>
-        /// Type of Microsoft.Passport.RPS.RPSTicket.RPSTicketProperty
-        /// </summary>
-        private readonly Type _rpsTicketPropertyType = null;
-
-        /// <summary>
-        /// Instance of the Microsoft.Passport.RPS.RPS object
-        /// </summary>
-        private object _rps = null;
-
-        /// <summary>
-        /// RPS Wrapper constructor
-        /// </summary>
-        public RPS()
-        {
-            // Load dynamically the assembly
-            _rpsAssembly = Assembly.Load("Microsoft.Passport.RPS, Version=6.1.6206.0, Culture=neutral, PublicKeyToken=283dd9fa4b2406c5, processorArchitecture=MSIL");
-
-            // Extract the types that will be needed to perform authentication
-            _rpsType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPS").Single();
-            _rpsTicketType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPSTicket").Single();
-            _rpsPropBagType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPSPropBag").Single();
-            _rpsAuthType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPSAuth").Single();
-            _rpsTicketPropertyType = _rpsTicketType.GetNestedTypes().ToList().Where(t => t.Name == "RPSTicketProperty").Single();
-
-            // Create instance of the RPS object
-            _rps = Activator.CreateInstance(_rpsType);
-        }
-
-        /// <summary>
-        /// Calling Initialize in the RPS real object created from the dynamically loaded RPS assembly
-        /// </summary>
-        public void Initialize(string s)
-        {
-            // Call initialize in the previously created rps object
-            _rpsType.GetMethod("Initialize").Invoke(_rps, new object[] { s });
-        }
-
-        /// <summary>
-        /// Given an encrypted ticket, calls RPS Authenticate and returns the decrypted ticket
-        /// </summary>
-        public object Authenticate(byte[] encryptedTicket, string siteName)
-        {
-            // Create instance of the rpsPropBag using the rps object
-            object rpsPropBag = Activator.CreateInstance(_rpsPropBagType, new object[] { _rps });
-
-            // Create instance of the rpsAuth Authenticator using the rps object
-            object authenticator = Activator.CreateInstance(_rpsAuthType, new object[] { _rps });
-
-            // Call Authenticate in the Authenticator object using the encrypted ticket and the site name provided
-            return _rpsAuthType.GetMethod("Authenticate").Invoke(authenticator, new object[] { siteName, System.Text.Encoding.Unicode.GetString(encryptedTicket), (uint)2 /*compact ticket*/, rpsPropBag });
-        }
-
-        /// <summary>
-        /// Given an rps decrypted ticket, get the session key
-        /// </summary>
-        public byte[] GetSessionKeyFromRpsDecryptedTicket(object rpsTicket)
-        {
-            // Take the Property field from the rpsTicket provided
-            object rpsTicketProperty = _rpsTicketType.GetFields().ToList().Where(p => p.Name == "Property").Single().GetValue(rpsTicket);
-
-            // Get the Property["SessionKey"] value from the rpsTicketProperty
-            object sessionkey = _rpsTicketPropertyType.GetMethod("get_Item").Invoke(rpsTicketProperty, new object[] { "SessionKey" });
-
-            // Return the Session Key as an array of bytes
-            return GetStringAsBytes((string)sessionkey);
-        }
-
-        /// <summary>
-        /// Convert a "string" that is actually a byte array into an actual byte array - needed for interop
-        /// with COM methods that are returning binary data as a BSTR.
-        /// </summary>
-        private static byte[] GetStringAsBytes(string toConvert)
-        {
-            byte[] convertedBytes = new byte[toConvert.Length * sizeof(char)];
-            for (int i = 0; i < toConvert.Length; i++)
-            {
-                byte[] charAsBytes = BitConverter.GetBytes(toConvert[i]);
-                convertedBytes[(2 * i)] = charAsBytes[0];
-                convertedBytes[(2 * i) + 1] = charAsBytes[1];
-            }
-
-            return convertedBytes;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/RpsTicket.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/FederatedAuthentication/RpsTicket.cs
deleted file mode 100644 (file)
index 466a959..0000000
+++ /dev/null
@@ -1,128 +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.Security.Cryptography;
-using System.Reflection;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.FederatedAuthentication
-{
-    /// <summary>
-    /// RPS implementation of federated authentication ticket
-    /// </summary>
-    public class RpsTicket : IFederatedAuthenticationTicket
-    {
-        /// <summary>
-        /// Singleton instance of an RPS class, which drives authentication at the RPS level.
-        /// </summary>
-        private const string siteNameInt = "dev.mscds.com";
-
-        /// <summary>
-        /// Singleton instance of an RPS class, which drives authentication at the RPS level.
-        /// </summary>
-        private static RPS s_rps = null;
-
-        /// <summary>
-        /// The short-lived session key associated with this authentication ticket
-        /// </summary>
-        public readonly byte[] sessionKey;
-
-        /// <summary>
-        /// The RPS representation of the ticket
-        /// </summary>
-        private object _rpsTicket = null;
-
-        /// <summary>
-        /// Constructor that takes the RPS representation of the ticket as an argument
-        /// </summary>
-        private RpsTicket(object _ticket, byte[] _sessionKey)
-        {
-            _rpsTicket = _ticket;
-            sessionKey = _sessionKey;
-        }
-
-        /// <summary>
-        /// Static constructor for the RpsTicket class.
-        /// </summary>
-        static RpsTicket()
-        {
-            // Initialize the rps object
-            s_rps = new RPS();
-            s_rps.Initialize(null);
-        }
-
-        /// <summary>
-        /// Computes and returns the HMACSHA256 of the provided buffer using the Session Key associated with the auth
-        /// ticket.
-        /// </summary>
-        public byte[] GetSignature(byte[] bufferToSign)
-        {
-            // Argument check to avoid throwing exceptions in this part
-            if (bufferToSign == null)
-            {
-                return null;
-            }
-
-            using (HMACSHA256 shaHash = new HMACSHA256(sessionKey))
-            {
-                return shaHash.ComputeHash(bufferToSign);
-            }
-        }
-
-        /// <summary>
-        /// Takes the encrypted wire format of the ticket and, on successful authentication, returns
-        /// the resulting ticket.
-        /// </summary>
-        public static IFederatedAuthenticationTicket DecryptTicket(byte[] encryptedTicket)
-        {
-            // Get the decrypted RPS ticket by calling Authenticate with the encrypted ticket
-            object tempTicket = s_rps.Authenticate(encryptedTicket, siteNameInt);
-
-            // Instantiate the RpsTicket using the decrypted ticket and its session key
-            return new RpsTicket(tempTicket, s_rps.GetSessionKeyFromRpsDecryptedTicket(tempTicket));
-        }
-    }
-
-    /// <summary>
-    /// JWT implementation of federated authentication ticket
-    /// Move this class to a different file once msbuild conversion is completed.
-    /// </summary>
-    public class JwtTicket : IFederatedAuthenticationTicket
-    {
-        /// <summary>
-        /// the ticket
-        /// </summary>
-        private readonly byte[] _ticket;
-
-        /// <summary>
-        /// Computes and returns the HMACSHA256 of the provided buffer using the Session Key associated with the auth
-        /// ticket.
-        /// </summary>
-        public byte[] GetSignature(byte[] bufferToSign)
-        {
-            return null;
-        }
-
-        /// <summary>
-        /// Constructor that takes the RPS representation of the ticket as an argument
-        /// </summary>
-        private JwtTicket(byte[] ticket)
-        {
-            _ticket = ticket;
-        }
-
-        /// <summary>
-        /// Takes the encrypted wire format of the ticket and, on successful authentication, returns
-        /// the resulting ticket.
-        /// </summary>
-        public static IFederatedAuthenticationTicket DecryptTicket(byte[] encryptedTicket)
-        {
-            // Instantiate the RpsTicket using the decrypted ticket and its session key
-            return new JwtTicket(encryptedTicket);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSClient.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSClient.cs
deleted file mode 100644 (file)
index f14cb4d..0000000
+++ /dev/null
@@ -1,82 +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.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Interface that TDS parser calls into to process TDS stream
-    /// </summary>
-    public interface ITDSClient
-    {
-        /// <summary>
-        /// Indicates the state of the TDS client
-        /// </summary>
-        TDSClientState State { get; }
-
-        /// <summary>
-        /// Run time context of the client
-        /// </summary>
-        ITDSClientContext Context { get; }
-
-        /// <summary>
-        /// Notification that is fired before the parser establishes a connection to the server. This method should be used to initialize context.
-        /// </summary>
-        void OnPreConnect();
-
-        /// <summary>
-        /// It is called when transport was established with TDS server and client parser is ready to start conversation
-        /// </summary>
-        /// <returns>TDS message to initiate conversation with TDS Server</returns>
-        TDSMessage OnPreLogin();
-
-        /// <summary>
-        /// It is called when pre-login response arrives
-        /// </summary>
-        /// <param name="message">TDS message received</param>
-        /// <returns>TDS message to send to the server</returns>
-        TDSMessage OnPreLoginResponse(TDSMessage message);
-
-        /// <summary>
-        /// It is called when SPNEGO response arrives
-        /// </summary>
-        /// <param name="packet">TDS message received</param>
-        TDSMessage OnSSPIResponse(TDSMessage message);
-
-        /// <summary>
-        /// It is called when FedAuthInfoToken response arrives
-        /// </summary>
-        /// <param name="packet">TDS message received</param>
-        TDSMessage OnFedAuthInfoTokenResponse(TDSMessage message);
-
-        /// <summary>
-        /// It is called when login acknowledgement arrives.
-        /// </summary>
-        /// <param name="packet">TDS message received</param>
-        void OnLoginResponse(TDSMessage message);
-
-        /// <summary>
-        /// Create a request to SQL Server after authentication
-        /// </summary>
-        /// <returns>TDS message to send to the server</returns>
-        TDSMessage OnRequest();
-
-        /// <summary>
-        /// Process response to the request
-        /// </summary>
-        /// <param name="message">TDS message received</param>
-        void OnResponse(TDSMessage message);
-
-        /// <summary>
-        /// Create a request to SQL Server to logout
-        /// </summary>
-        /// <returns>TDS message to send to the server</returns>
-        TDSMessage OnLogout();
-
-        /// <summary>
-        /// Process response to the logout request
-        /// </summary>
-        /// <param name="message">TDS message received</param>
-        void OnLogoutResponse(TDSMessage message);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSClientContext.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSClientContext.cs
deleted file mode 100644 (file)
index 6ec9f83..0000000
+++ /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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Run time context of the TDS client
-    /// </summary>
-    public interface ITDSClientContext
-    {
-        /// <summary>
-        /// Host or IP address on which SQL Server is running
-        /// </summary>
-        string ServerHost { get; set; }
-
-        /// <summary>
-        /// Port number of the SQL Server
-        /// </summary>
-        uint ServerPort { get; set; }
-
-        /// <summary>
-        /// Pipe at which SQL Server is listening
-        /// </summary>
-        string ServerPipe { get; set; }
-
-        /// <summary>
-        /// Name of the server client connected to.
-        /// Information is coming from INFO and ERROR tokens
-        /// </summary>
-        string ServerName { get; }
-
-        /// <summary>
-        /// Description of the server the client connected to.
-        /// Information originates in LOGINACK token
-        /// </summary>
-        string ServerDescription { get; }
-
-        /// <summary>
-        /// Server build version
-        /// </summary>
-        Version ServerVersion { get; }
-
-        /// <summary>
-        /// TDS version of the conversation
-        /// </summary>
-        Version TDSVersion { get; }
-
-        /// <summary>
-        /// Current database
-        /// </summary>
-        string Database { get; }
-
-        /// <summary>
-        /// Current language
-        /// </summary>
-        string Language { get; }
-
-        /// <summary>
-        /// Database collation
-        /// </summary>
-        byte[] Collation { get; }
-
-        /// <summary>
-        /// Size of the TDS packet
-        /// </summary>
-        uint PacketSize { get; set; }
-
-        /// <summary>
-        /// Failover partner for connected SQL Server
-        /// </summary>
-        string FailoverPartner { get; }
-
-        /// <summary>
-        /// Encryption used on the session
-        /// </summary>
-        TDSEncryptionType Encryption { get; set; }
-
-        /// <summary>
-        /// Query text to be sent to the TDS server
-        /// </summary>
-        string Query { get; set; }
-
-        /// <summary>
-        /// Response to the query
-        /// </summary>
-        IList<object[]> QueryResponse { get; set; }
-
-        /// <summary>
-        /// Connection identifier
-        /// </summary>
-        Guid ConnectionID { get; }
-
-        /// <summary>
-        /// State of the virtual session
-        /// </summary>
-        object SessionState { get; }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSServer.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSServer.cs
deleted file mode 100644 (file)
index 96c222e..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Interface that TDS parser calls into to process TDS stream
-    /// </summary>
-    public interface ITDSServer
-    {
-        /// <summary>
-        /// Create a new TDS server session
-        /// </summary>
-        /// <returns>A new instance of the TDS server session</returns>
-        ITDSServerSession OpenSession();
-
-        /// <summary>
-        /// Close TDS server session
-        /// </summary>
-        /// <param name="session">An instance of the TDS server session to close</param>
-        void CloseSession(ITDSServerSession session);
-
-        /// <summary>
-        /// It is called when pre-login request arrives
-        /// </summary>
-        /// <param name="message">TDS message recieved</param>
-        /// <returns>TDS messages to be respond with</returns>
-        TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage message);
-
-        /// <summary>
-        /// It is called when login request arrives
-        /// </summary>
-        /// <param name="message">TDS message recieved</param>
-        /// <returns>TDS message to respond with</returns>
-        TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage message);
-
-        /// <summary>
-        /// It is called when federated authentication token message arrives. Called only when
-        /// such a message arrives in response to federated authentication info, not when the
-        /// token is part of a login request.
-        /// </summary>
-        /// <param name="message">TDS message received</param>
-        /// <returns>TDS message to respond with</returns>
-        TDSMessageCollection OnFederatedAuthenticationTokenMessage(ITDSServerSession session, TDSMessage message);
-
-        /// <summary>
-        /// It is called when SSPI payload arrives
-        /// </summary>
-        /// <param name="message">TDS message recieved</param>
-        /// <returns>TDS message to respond with</returns>
-        TDSMessageCollection OnSSPIRequest(ITDSServerSession session, TDSMessage message);
-
-        /// <summary>
-        /// It is called when SQL batch request arrives
-        /// </summary>
-        /// <param name="message">TDS message recieved</param>
-        /// <returns>TDS message to respond with</returns>
-        TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session, TDSMessage message);
-
-        /// <summary>
-        /// It is called when attention arrives
-        /// </summary>
-        /// <param name="message">TDS message recieved</param>
-        /// <returns>TDS message to respond with</returns>
-        TDSMessageCollection OnAttention(ITDSServerSession session, TDSMessage message);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSServerSession.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/ITDSServerSession.cs
deleted file mode 100644 (file)
index ca2373f..0000000
+++ /dev/null
@@ -1,82 +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.Security.Cryptography.X509Certificates;
-
-using Microsoft.SqlServer.TDS.EndPoint.SSPI;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Session of the TDS Server
-    /// </summary>
-    public interface ITDSServerSession
-    {
-        /// <summary>
-        /// Server that created the session
-        /// </summary>
-        ITDSServer Server { get; }
-
-        /// <summary>
-        /// Session identifier
-        /// </summary>
-        uint SessionID { get; }
-
-        /// <summary>
-        /// Size of the TDS packet
-        /// </summary>
-        uint PacketSize { get; set; }
-
-        /// <summary>
-        /// User name if SQL authentication is used
-        /// </summary>
-        string SQLUserID { get; set; }
-
-        /// <summary>
-        /// Context that indicates the stage of SSPI authentication
-        /// </summary>
-        SSPIContext NTUserAuthenticationContext { get; set; }
-
-        /// <summary>
-        /// Database to which connection is established
-        /// </summary>
-        string Database { get; set; }
-
-        /// <summary>
-        /// TDS version of the communication
-        /// </summary>
-        Version TDSVersion { get; set; }
-
-        /// <summary>
-        /// Local connection end-point information
-        /// </summary>
-        TDSEndPointInfo ServerEndPointInfo { get; set; }
-
-        /// <summary>
-        /// Remote connection end-point information
-        /// </summary>
-        TDSEndPointInfo ClientEndPointInfo { get; set; }
-
-        /// <summary>
-        /// Transport encryption
-        /// </summary>
-        TDSEncryptionType Encryption { get; set; }
-
-        /// <summary>
-        /// Certificate to use for encryption
-        /// </summary>
-        X509Certificate EncryptionCertificate { get; }
-
-        /// <summary>
-        /// Counter of connection reset requests for this session
-        /// </summary>
-        int ConnectionResetRequestCount { get; set; }
-
-        /// <summary>
-        /// Indicates whether this session supports transport-level recovery
-        /// </summary>
-        bool IsSessionRecoveryEnabled { get; set; }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/PlaceholderStream.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/PlaceholderStream.cs
deleted file mode 100644 (file)
index 2158fa9..0000000
+++ /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.IO;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// A simple pass-through implementation of stream that allows dynamically switching the underlying stream
-    /// </summary>
-    public class PlaceholderStream : Stream
-    {
-        /// <summary>
-        /// Indicates whether inner stream should be closed when TDS stream is closed
-        /// </summary>
-        private bool _leaveInnerStreamOpen = false;
-
-        /// <summary>
-        /// Transport stream used to deliver TDS protocol
-        /// </summary>
-        public Stream InnerStream { get; set; }
-
-        /// <summary>
-        /// Indicates whether stream can be read
-        /// </summary>
-        public override bool CanRead
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.CanRead; }
-        }
-
-        /// <summary>
-        /// Indicates whether the stream can be positioned
-        /// </summary>
-        public override bool CanSeek
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.CanSeek; }
-        }
-
-        /// <summary>
-        /// Indicates whether the stream can be written
-        /// </summary>
-        public override bool CanWrite
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.CanWrite; }
-        }
-
-        /// <summary>
-        /// Return the length of the stream
-        /// </summary>
-        public override long Length
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.Length; }
-        }
-
-        /// <summary>
-        /// Return position in the stream
-        /// </summary>
-        public override long Position
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.Position; }
-            set { InnerStream.Position = value; }
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public PlaceholderStream(Stream innerStream) :
-            this(innerStream, true)
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public PlaceholderStream(Stream innerStream, bool leaveInnerStreamOpen)
-        {
-            // Check if inner stream is valid
-            if (innerStream == null)
-            {
-                // We can't proceed without underlying stream
-                throw new ArgumentNullException(nameof(innerStream), "Underlying stream is required");
-            }
-
-            // Save transport stream
-            InnerStream = innerStream;
-
-            // Save whether inner stream is to be closed as well
-            _leaveInnerStreamOpen = leaveInnerStreamOpen;
-        }
-
-        /// <summary>
-        /// Close the stream
-        /// </summary>
-        public override void Close()
-        {
-            // Check if inner stream needs to be closed
-            if (!_leaveInnerStreamOpen)
-            {
-                // Close inner stream
-                InnerStream.Close();
-            }
-
-            // Delegate to the base class
-            base.Close();
-        }
-
-        /// <summary>
-        /// Flush the data into the underlying stream
-        /// </summary>
-        public override void Flush()
-        {
-            // Delegate to the inner stream
-            InnerStream.Flush();
-        }
-
-        /// <summary>
-        /// Read the data from the stream
-        /// </summary>
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            // Delegate to the underlying stream
-            return InnerStream.Read(buffer, offset, count);
-        }
-
-        /// <summary>
-        /// Seek position in the stream
-        /// </summary>
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            // Delegate to the inner stream
-            return InnerStream.Seek(offset, origin);
-        }
-
-        /// <summary>
-        /// Set stream length
-        /// </summary>
-        public override void SetLength(long value)
-        {
-            // Delegate to the inner stream
-            InnerStream.SetLength(value);
-        }
-
-        /// <summary>
-        /// Write data into the stream
-        /// </summary>
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            // Delegate to underlying stream
-            InnerStream.Write(buffer, offset, count);
-        }
-
-        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
-        {
-            return InnerStream.WriteAsync(buffer, offset, count, cancellationToken);
-        }
-
-        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
-        {
-            return InnerStream.ReadAsync(buffer, offset, count, cancellationToken);
-        }
-
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIContext.Unix.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIContext.Unix.cs
deleted file mode 100644 (file)
index 3d05c88..0000000
+++ /dev/null
@@ -1,109 +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.ComponentModel;
-using System.Runtime.InteropServices;
-using System.Security.Principal;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// SSPI context
-    /// </summary>
-    public class SSPIContext : IDisposable
-    {
-        /// <summary>
-        /// FInalizer
-        /// </summary>
-        ~SSPIContext()
-        {
-            // Indicate that we're being destructed
-            Dispose(false);
-        }
-
-        /// <summary>
-        /// Create SSPI context for server
-        /// </summary>
-        public static SSPIContext CreateServer()
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Create SSPI context for client
-        /// </summary>
-        public static SSPIContext CreateClient()
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Initialize authentication sequence for the server
-        /// </summary>
-        /// <param name="clientToken">Token received from the client</param>
-        /// <returns>Token to be sent to the client in response</returns>
-        public SSPIResponse StartServerAuthentication(byte[] clientToken)
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Continue authentication sequence for the server
-        /// </summary>
-        /// <param name="clientToken">Token received from the client</param>
-        /// <returns>Token to be sent to the client in response</returns>
-        public SSPIResponse ContinueServerAuthentication(byte[] clientToken)
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Initialize authentication sequence for the client
-        /// </summary>
-        /// <returns>Token to be sent to the server</returns>
-        public SSPIResponse StartClientAuthentication(string targetMachine, uint targetPort)
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Initialize authentication sequence for the client
-        /// </summary>
-        /// <param name="clientToken">Payload received from the server</param>
-        /// <returns>Token to be sent to the server</returns>
-        public SSPIResponse ContinueClientAuthentication(byte[] clientToken)
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Return identity of the party on the other end
-        /// </summary>
-        /// <returns></returns>
-        public IIdentity GetRemoteIdentity()
-        {
-            throw new PlatformNotSupportedException();
-        }
-
-        /// <summary>
-        /// Dispose
-        /// </summary>
-        public void Dispose()
-        {
-            // Indicate that we're disposing
-            Dispose(true);
-        }
-
-        /// <summary>
-        /// Dispose the instance
-        /// </summary>
-        /// <param name="bIsDisposing"></param>
-        protected void Dispose(bool bIsDisposing)
-        {
-
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIContext.Windows.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIContext.Windows.cs
deleted file mode 100644 (file)
index 37f93d9..0000000
+++ /dev/null
@@ -1,476 +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.ComponentModel;
-using System.Runtime.InteropServices;
-using System.Security.Principal;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// SSPI context
-    /// </summary>
-    public class SSPIContext : IDisposable
-    {
-        /// <summary>
-        /// Security credential for server operation
-        /// </summary>
-        private SecurityHandle _inboundCredential = new SecurityHandle();
-
-        /// <summary>
-        /// Security credential for client operation
-        /// </summary>
-        private SecurityHandle _outboundCredential = new SecurityHandle();
-
-        /// <summary>
-        /// Server context
-        /// </summary>
-        private SecurityHandle _serverContext = new SecurityHandle();
-
-        /// <summary>
-        /// Client context
-        /// </summary>
-        private SecurityHandle _clientContext = new SecurityHandle();
-
-        /// <summary>
-        /// Target server we're authenticating against
-        /// </summary>
-        private string _targetMachineSPN;
-
-        /// <summary>
-        /// Maximum size of the token buffer
-        /// </summary>
-        private int _maxTokenBufferSize;
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        private SSPIContext()
-        {
-            // Prepare a list of packages
-            IList<string> packages = new List<string>();
-
-            packages.Add(SecConstants.Negotiate);
-            packages.Add(SecConstants.Kerberos);
-            packages.Add(SecConstants.NTLM);
-
-            // Try each package
-            foreach (string package in packages)
-            {
-                IntPtr packagePtr = IntPtr.Zero;
-
-                // Query security package
-                int secReturnCode = SecurityWrapper.QuerySecurityPackageInfo(package, ref packagePtr);
-
-                // Check if package was found
-                if (secReturnCode == unchecked((int)SecResult.PackageNotFound))
-                {
-                    // Move to the next package
-                    continue;
-                }
-
-                // Check if we succeeded
-                if (secReturnCode != (int)SecResult.Ok)
-                {
-                    // Security package qury failed
-                    throw new Win32Exception(secReturnCode, "Failed to query security package");
-                }
-
-                try
-                {
-                    // Map unmanaged structure pointer to managed
-                    SecPkgInfo info = (SecPkgInfo)Marshal.PtrToStructure(packagePtr, typeof(SecPkgInfo));
-
-                    // Check if buffer size is larger than what we have
-                    if (info.MaxToken > _maxTokenBufferSize)
-                    {
-                        // Use the token size
-                        _maxTokenBufferSize = info.MaxToken;
-                    }
-                }
-                finally
-                {
-                    // Release security package
-                    secReturnCode = SecurityWrapper.FreeContextBuffer(packagePtr);
-
-                    // Check if we succeeded
-                    if (secReturnCode != (int)SecResult.Ok)
-                    {
-                        // Security package qury failed
-                        throw new Win32Exception(secReturnCode, "Failed to free security package");
-                    }
-                }
-            }
-
-            // Check if buffer size is valid
-            if (_maxTokenBufferSize == 0)
-            {
-                throw new Exception("Either no security packages found or none of them reported a valid maximum token length");
-            }
-        }
-
-        /// <summary>
-        /// FInalizer
-        /// </summary>
-        ~SSPIContext()
-        {
-            // Indicate that we're being destructed
-            Dispose(false);
-        }
-
-        /// <summary>
-        /// Create SSPI context for server
-        /// </summary>
-        public static SSPIContext CreateServer()
-        {
-            // Create an instance of the context
-            SSPIContext context = new SSPIContext();
-
-            // Initialize token lifetime container
-            SecurityInteger lifeTime = new SecurityInteger();
-
-            // Delegate into security API
-            int secReturnCode = SecurityWrapper.AcquireCredentialsHandle(null, SecConstants.Negotiate, (int)SecPgkCredentials.Inbound, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, ref context._inboundCredential, ref lifeTime);
-
-            // Check if we succeeded
-            if (secReturnCode != (int)SecResult.Ok)
-            {
-                // We couldn't obtain server credentials handle
-                throw new Win32Exception(secReturnCode, "Failed to acquire server credentials handle");
-            }
-
-            return context;
-        }
-
-        /// <summary>
-        /// Create SSPI context for client
-        /// </summary>
-        public static SSPIContext CreateClient()
-        {
-            // Create an instance of the context
-            SSPIContext context = new SSPIContext();
-
-            // Initialize token lifetime container
-            SecurityInteger lifeTime = new SecurityInteger();
-
-            // Delegate into security API
-            int secReturnCode = SecurityWrapper.AcquireCredentialsHandle(null, SecConstants.Negotiate, (int)SecPgkCredentials.Outbound, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, ref context._outboundCredential, ref lifeTime);
-
-            // Check if we succeeded
-            if (secReturnCode != (int)SecResult.Ok)
-            {
-                // We couldn't obtain server credentials handle
-                throw new Win32Exception(secReturnCode, "Failed to acquire client credentials handle");
-            }
-
-            return context;
-        }
-
-        /// <summary>
-        /// Initialize authentication sequence for the server
-        /// </summary>
-        /// <param name="clientToken">Token received from the client</param>
-        /// <returns>Token to be sent to the client in response</returns>
-        public SSPIResponse StartServerAuthentication(byte[] clientToken)
-        {
-            // Wrap client token with the security buffer
-            SecBufferDesc clientSecBuffer = new SecBufferDesc(clientToken);
-
-            try
-            {
-                // Allocate a new instance of the server security buffer of the specified size
-                SecBufferDesc serverSecBuffer = new SecBufferDesc(_maxTokenBufferSize);
-
-                try
-                {
-                    // Return code from the security API call
-                    int secReturnCode = 0;
-
-                    // New context attribute
-                    uint contextAttribute = 0;
-
-                    // Initialize token lifetime container
-                    SecurityInteger lifeTime = new SecurityInteger();
-
-                    // Delegate into security API
-                    secReturnCode = SecurityWrapper.AcceptSecurityContext(ref _inboundCredential,
-                        IntPtr.Zero,
-                        ref clientSecBuffer,
-                        (int)SecContextRequirements.MutualAuthentication,
-                        (int)SecDataRepresentation.Native,
-                        out _serverContext,
-                        out serverSecBuffer,
-                        out contextAttribute,
-                        out lifeTime);
-
-                    // Check the return code
-                    if (secReturnCode != (int)SecResult.Ok && secReturnCode != (int)SecResult.ContinueNeeded)
-                    {
-                        // Operation failed
-                        throw new Win32Exception(secReturnCode, "Failed to accept security context");
-                    }
-
-                    // Convert to byte array and indication whether this is a last call
-                    return new SSPIResponse(serverSecBuffer.ToArray(), secReturnCode != (int)SecResult.ContinueNeeded);
-                }
-                finally
-                {
-                    // Dispose server security buffer
-                    serverSecBuffer.Dispose();
-                }
-            }
-            finally
-            {
-                // Dispose client security buffer
-                clientSecBuffer.Dispose();
-            }
-        }
-
-        /// <summary>
-        /// Continue authentication sequence for the server
-        /// </summary>
-        /// <param name="clientToken">Token received from the client</param>
-        /// <returns>Token to be sent to the client in response</returns>
-        public SSPIResponse ContinueServerAuthentication(byte[] clientToken)
-        {
-            // Wrap client token with the security buffer
-            SecBufferDesc clientSecBuffer = new SecBufferDesc(clientToken);
-
-            try
-            {
-                // Allocate a new instance of the server security buffer of the specified size
-                SecBufferDesc serverSecBuffer = new SecBufferDesc(_maxTokenBufferSize);
-
-                try
-                {
-                    // Return code from the security API call
-                    int secReturnCode = 0;
-
-                    // New context attribute
-                    uint contextAttribute = 0;
-
-                    // Initialize token lifetime container
-                    SecurityInteger lifeTime = new SecurityInteger();
-
-                    // Delegate into security API
-                    secReturnCode = SecurityWrapper.AcceptSecurityContext(ref _inboundCredential,
-                        ref _serverContext,
-                        ref clientSecBuffer,
-                        (int)SecContextRequirements.MutualAuthentication,
-                        (int)SecDataRepresentation.Native,
-                        out _serverContext,
-                        out serverSecBuffer,
-                        out contextAttribute,
-                        out lifeTime);
-
-                    // Check the return code
-                    if (secReturnCode != (int)SecResult.Ok && secReturnCode != (int)SecResult.ContinueNeeded)
-                    {
-                        // Operation failed
-                        throw new Win32Exception(secReturnCode, "Failed to accept security context");
-                    }
-
-                    // Convert to byte array and indication whether this is a last call
-                    return new SSPIResponse(serverSecBuffer.ToArray(), secReturnCode != (int)SecResult.ContinueNeeded);
-                }
-                finally
-                {
-                    // Dispose server security buffer
-                    serverSecBuffer.Dispose();
-                }
-            }
-            finally
-            {
-                // Dispose client security buffer
-                clientSecBuffer.Dispose();
-            }
-        }
-
-        /// <summary>
-        /// Initialize authentication sequence for the client
-        /// </summary>
-        /// <returns>Token to be sent to the server</returns>
-        public SSPIResponse StartClientAuthentication(string targetMachine, uint targetPort)
-        {
-            // Save the server we're authenticating against
-            _targetMachineSPN = string.Format("MSSQLSvc/{0}:{1}", targetMachine, targetPort);
-
-            // Allocate a new instance of the client security buffer of the specified size
-            SecBufferDesc clientSecBuffer = new SecBufferDesc(_maxTokenBufferSize);
-
-            try
-            {
-                // Return code from the security API call
-                int secReturnCode = 0;
-
-                // New context attribute
-                uint contextAttribute = 0;
-
-                // Initialize token lifetime container
-                SecurityInteger lifeTime = new SecurityInteger();
-
-                // Delegate into security API
-                secReturnCode = SecurityWrapper.InitializeSecurityContext(ref _outboundCredential,
-                    IntPtr.Zero,
-                    _targetMachineSPN,
-                    (int)(SecContextRequirements.MutualAuthentication | SecContextRequirements.Delegate | SecContextRequirements.ExtendedError),
-                    0,
-                    (int)SecDataRepresentation.Native,
-                    IntPtr.Zero,
-                    0,
-                    out _clientContext,
-                    out clientSecBuffer,
-                    out contextAttribute,
-                    out lifeTime);
-
-                // Check the return code
-                if (secReturnCode != (int)SecResult.Ok && secReturnCode != (int)SecResult.ContinueNeeded)
-                {
-                    // Operation failed
-                    throw new Win32Exception(secReturnCode, "Failed to generate initial security context");
-                }
-
-                // Convert to byte array and indication whether this is a last call
-                return new SSPIResponse(clientSecBuffer.ToArray(), secReturnCode != (int)SecResult.ContinueNeeded && secReturnCode != (int)SecResult.CompleteAndContinue);
-            }
-            finally
-            {
-                // Dispose server security buffer
-                clientSecBuffer.Dispose();
-            }
-        }
-
-        /// <summary>
-        /// Initialize authentication sequence for the client
-        /// </summary>
-        /// <param name="clientToken">Payload received from the server</param>
-        /// <returns>Token to be sent to the server</returns>
-        public SSPIResponse ContinueClientAuthentication(byte[] clientToken)
-        {
-            // Wrap client token with the security buffer
-            SecBufferDesc serverSecBuffer = new SecBufferDesc(clientToken);
-
-            try
-            {
-                // Allocate a new instance of the client security buffer of the specified size
-                SecBufferDesc clientSecBuffer = new SecBufferDesc(_maxTokenBufferSize);
-
-                try
-                {
-                    // Return code from the security API call
-                    int secReturnCode = 0;
-
-                    // New context attribute
-                    uint contextAttribute = 0;
-
-                    // Initialize token lifetime container
-                    SecurityInteger lifeTime = new SecurityInteger();
-
-                    // Delegate into security API
-                    secReturnCode = SecurityWrapper.InitializeSecurityContext(ref _outboundCredential,
-                        ref _clientContext,
-                        _targetMachineSPN,
-                        (int)(SecContextRequirements.MutualAuthentication | SecContextRequirements.Delegate | SecContextRequirements.ExtendedError),
-                        0,
-                        (int)SecDataRepresentation.Native,
-                        ref serverSecBuffer,
-                        0,
-                        out _clientContext,
-                        out clientSecBuffer,
-                        out contextAttribute,
-                        out lifeTime);
-
-                    // Check the return code
-                    if (secReturnCode != (int)SecResult.Ok && secReturnCode != (int)SecResult.ContinueNeeded && secReturnCode != (int)SecResult.CompleteAndContinue)
-                    {
-                        // Operation failed
-                        throw new Win32Exception(secReturnCode, "Failed to generate security context");
-                    }
-
-                    // NOTE: Digest SSP call to "CompleteAuthToken" is intentionally omitted because we don't support Digest today.
-
-                    // Convert to byte array and indication whether this is a last call
-                    return new SSPIResponse(clientSecBuffer.ToArray(), secReturnCode != (int)SecResult.ContinueNeeded && secReturnCode != (int)SecResult.CompleteAndContinue);
-                }
-                finally
-                {
-                    // Dispose client security buffer
-                    clientSecBuffer.Dispose();
-                }
-            }
-            finally
-            {
-                // Dispose server security buffer
-                serverSecBuffer.Dispose();
-            }
-        }
-
-        /// <summary>
-        /// Return identity of the party on the other end
-        /// </summary>
-        /// <returns></returns>
-        public IIdentity GetRemoteIdentity()
-        {
-            IntPtr token = IntPtr.Zero;
-
-            // Delegate into security API
-            int secReturnCode = SecurityWrapper.QuerySecurityContextToken(ref _serverContext, ref token);
-
-            // Check if we succeeded
-            if (secReturnCode != (int)SecResult.Ok)
-            {
-                // We couldn't obtain token identity
-                throw new Win32Exception(secReturnCode, "Failed to obtain security context token");
-            }
-
-            return new WindowsIdentity(token);
-        }
-
-        /// <summary>
-        /// Dispose
-        /// </summary>
-        public void Dispose()
-        {
-            // Indicate that we're disposing
-            Dispose(true);
-        }
-
-        /// <summary>
-        /// Dispose the instance
-        /// </summary>
-        /// <param name="bIsDisposing"></param>
-        protected void Dispose(bool bIsDisposing)
-        {
-            // Check if we have an inbound credential
-            if (_inboundCredential.IsValid())
-            {
-                // Call into security API to release the credentials
-                if (SecurityWrapper.FreeCredentialsHandle(ref _inboundCredential) != (int)SecResult.Ok)
-                {
-                    // Throw an exception
-                    throw new Exception("Failed to release inbound credentials handle");
-                }
-
-                // Reset inbound credential
-                _inboundCredential = new SecurityHandle();
-            }
-
-            // Check if we have an outbound credential
-            if (_outboundCredential.IsValid())
-            {
-                // Call into security API to release the credentials
-                if (SecurityWrapper.FreeCredentialsHandle(ref _outboundCredential) != (int)SecResult.Ok)
-                {
-                    // Throw an exception
-                    throw new Exception("Failed to release outbound credentials handle");
-                }
-
-                // Reset inbound credential
-                _outboundCredential = new SecurityHandle();
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIResponse.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SSPIResponse.cs
deleted file mode 100644 (file)
index 2f91619..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Container for the SSPI handshake response to be sent to the other party
-    /// </summary>
-    public class SSPIResponse
-    {
-        /// <summary>
-        /// Payload to proceed to the next step of authentication
-        /// </summary>
-        public byte[] Payload { get; set; }
-
-        /// <summary>
-        /// Indicates whether this is the last payload and no further processing is needed
-        /// </summary>
-        public bool IsFinal { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public SSPIResponse()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public SSPIResponse(byte[] payload)
-        {
-            Payload = payload;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public SSPIResponse(byte[] payload, bool isFinal) :
-            this(payload)
-        {
-            IsFinal = isFinal;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBuffer.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBuffer.cs
deleted file mode 100644 (file)
index c235aaf..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Security buffer
-    /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
-    internal struct SecBuffer : IDisposable
-    {
-        public int BufferSize;
-        public int BufferType;
-        public IntPtr BufferPtr;
-
-        /// <summary>
-        /// Initialization constructor that allocates a new security buffer
-        /// </summary>
-        /// <param name="bufferSize">Size of the buffer to allocate</param>
-        internal SecBuffer(int bufferSize)
-        {
-            // Save buffer size
-            BufferSize = bufferSize;
-
-            // Set buffer type
-            BufferType = (int)SecBufferType.Token;
-
-            // Allocate buffer
-            BufferPtr = Marshal.AllocHGlobal(bufferSize);
-        }
-
-        /// <summary>
-        /// Initialization constructor for existing buffer
-        /// </summary>
-        /// <param name="buffer">Data</param>
-        internal SecBuffer(byte[] buffer)
-        {
-            // Save buffer size
-            BufferSize = buffer.Length;
-
-            // Set buffer type
-            BufferType = (int)SecBufferType.Token;
-
-            // Allocate unmanaged memory for the buffer
-            BufferPtr = Marshal.AllocHGlobal(BufferSize);
-
-            try
-            {
-                // Copy data into the unmanaged memory
-                Marshal.Copy(buffer, 0, BufferPtr, BufferSize);
-            }
-            catch (Exception)
-            {
-                // Dispose object
-                Dispose();
-
-                // Re-throw exception
-                throw;
-            }
-        }
-
-        /// <summary>
-        /// Extract raw byte data from the security buffer
-        /// </summary>
-        internal byte[] ToArray()
-        {
-            // Check if we have a security buffer
-            if (BufferPtr == IntPtr.Zero)
-            {
-                return null;
-            }
-
-            // Allocate byte buffer
-            byte[] buffer = new byte[BufferSize];
-
-            // Copy data from the native space
-            Marshal.Copy(BufferPtr, buffer, 0, BufferSize);
-
-            return buffer;
-        }
-
-        /// <summary>
-        /// Dispose security buffer
-        /// </summary>
-        public void Dispose()
-        {
-            // Check buffer pointer validity
-            if (BufferPtr != IntPtr.Zero)
-            {
-                // Release memory associated with it
-                Marshal.FreeHGlobal(BufferPtr);
-
-                // Reset buffer pointer
-                BufferPtr = IntPtr.Zero;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferDesc.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferDesc.cs
deleted file mode 100644 (file)
index a41ba79..0000000
+++ /dev/null
@@ -1,157 +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;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Security buffer descriptor
-    /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
-    internal struct SecBufferDesc : IDisposable
-    {
-        public int Version;
-        public int BufferCount;
-        public IntPtr BuffersPtr;
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="size">Size of the buffer to allocate</param>
-        internal SecBufferDesc(int size)
-        {
-            // Set version to SECBUFFER_VERSION
-            Version = (int)SecBufferDescType.Version;
-
-            // Set the number of buffers
-            BufferCount = 1;
-
-            // Allocate a security buffer of the requested size
-            SecBuffer secBuffer = new SecBuffer(size);
-
-            // Allocate a native chunk of memory for security buffer
-            BuffersPtr = Marshal.AllocHGlobal(Marshal.SizeOf(secBuffer));
-
-            try
-            {
-                // Copy managed data into the native memory
-                Marshal.StructureToPtr(secBuffer, BuffersPtr, false);
-            }
-            catch (Exception)
-            {
-                // Delete native memory
-                Marshal.FreeHGlobal(BuffersPtr);
-
-                // Reset native buffer pointer
-                BuffersPtr = IntPtr.Zero;
-
-                // Re-throw exception
-                throw;
-            }
-        }
-
-        /// <summary>
-        /// Initialization constructor for byte array
-        /// </summary>
-        /// <param name="buffer">Data</param>
-        internal SecBufferDesc(byte[] buffer)
-        {
-            // Set version to SECBUFFER_VERSION
-            Version = (int)SecBufferDescType.Version;
-
-            // We have only one buffer
-            BufferCount = 1;
-
-            // Allocate security buffer
-            SecBuffer secBuffer = new SecBuffer(buffer);
-
-            // Allocate native memory for managed block
-            BuffersPtr = Marshal.AllocHGlobal(Marshal.SizeOf(secBuffer));
-
-            try
-            {
-                // Copy managed data into the native memory
-                Marshal.StructureToPtr(secBuffer, BuffersPtr, false);
-            }
-            catch (Exception)
-            {
-                // Delete native memory
-                Marshal.FreeHGlobal(BuffersPtr);
-
-                // Reset native buffer pointer
-                BuffersPtr = IntPtr.Zero;
-
-                // Re-throw exception
-                throw;
-            }
-        }
-
-        /// <summary>
-        /// Dispose security buffer descriptor
-        /// </summary>
-        public void Dispose()
-        {
-            // Check if we have a buffer
-            if (BuffersPtr != IntPtr.Zero)
-            {
-                // Iterate through each buffer than we manage
-                for (int index = 0; index < BufferCount; index++)
-                {
-                    // Calculate pointer to the buffer
-                    IntPtr currentBufferPtr = new IntPtr(BuffersPtr.ToInt64() + (index * Marshal.SizeOf(typeof(SecBuffer))));
-
-                    // Project the buffer into the managed world
-                    SecBuffer secBuffer = (SecBuffer)Marshal.PtrToStructure(currentBufferPtr, typeof(SecBuffer));
-
-                    // Dispose it
-                    secBuffer.Dispose();
-                }
-
-                // Release native memory block
-                Marshal.FreeHGlobal(BuffersPtr);
-
-                // Reset buffer pointer
-                BuffersPtr = IntPtr.Zero;
-            }
-        }
-
-        /// <summary>
-        /// Convert to byte array
-        /// </summary>
-        internal byte[] ToArray()
-        {
-            // Check if we have a buffer
-            if (BuffersPtr == IntPtr.Zero)
-            {
-                // We don'thave a buffer
-                return null;
-            }
-
-            // Prepare a memory stream to contain all the buffers
-            MemoryStream outputStream = new MemoryStream();
-
-            // Iterate through each buffer and write the data into the stream
-            for (int index = 0; index < BufferCount; index++)
-            {
-                // Calculate pointer to the buffer
-                IntPtr currentBufferPtr = new IntPtr(BuffersPtr.ToInt64() + (index * Marshal.SizeOf(typeof(SecBuffer))));
-
-                // Project the buffer into the managed world
-                SecBuffer secBuffer = (SecBuffer)Marshal.PtrToStructure(currentBufferPtr, typeof(SecBuffer));
-
-                // Get the byte buffer
-                byte[] secBufferBytes = secBuffer.ToArray();
-
-                // Write buffer to the stream
-                outputStream.Write(secBufferBytes, 0, secBufferBytes.Length);
-            }
-
-            // Convert to byte array
-            return outputStream.ToArray();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferDescType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferDescType.cs
deleted file mode 100644 (file)
index 591af59..0000000
+++ /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 Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Type of security buffer descriptor
-    /// </summary>
-    internal enum SecBufferDescType : int
-    {
-        Version = 0
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecBufferType.cs
deleted file mode 100644 (file)
index 9f178f0..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Type of security buffer
-    /// </summary>
-    internal enum SecBufferType : int
-    {
-        Empty = 0,
-        Data = 1,
-        Token = 2
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecConstants.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecConstants.cs
deleted file mode 100644 (file)
index a8080da..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Constants that are used across security API
-    /// </summary>
-    internal static class SecConstants
-    {
-        /// <summary>
-        /// Security packages used for SSPI authentication
-        /// </summary>
-        internal const string Negotiate = "negotiate";
-        internal const string Kerberos = "kerberos";
-        internal const string NTLM = "ntlm";
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecContextRequirements.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecContextRequirements.cs
deleted file mode 100644 (file)
index 78f8a9c..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Security context requirements
-    /// </summary>
-    internal enum SecContextRequirements : int
-    {
-        Delegate = 0x00000001,
-        MutualAuthentication = 0x00000002,
-        Integrity = 0x00010000,
-        ExtendedError = 0x00004000
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecDataRepresentation.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecDataRepresentation.cs
deleted file mode 100644 (file)
index d1b5fef..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Data representation requirements
-    /// </summary>
-    internal enum SecDataRepresentation : int
-    {
-        Network = 0x00000000,
-        Native = 0x00000010
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecPgkCredentials.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecPgkCredentials.cs
deleted file mode 100644 (file)
index e6df54e..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Security package credentials enumeration
-    /// </summary>
-    internal enum SecPgkCredentials : int
-    {
-        Inbound = 1,
-        Outbound = 2
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecPkgInfo.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecPkgInfo.cs
deleted file mode 100644 (file)
index a503d74..0000000
+++ /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.Runtime.InteropServices;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Security package info
-    /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
-    internal struct SecPkgInfo
-    {
-        /// <summary>
-        /// Set of bit flags that describes the capabilities of the security package
-        /// </summary>
-        public uint Capabilities;
-
-        /// <summary>
-        /// Specifies the version of the package protocol. Must be 1.
-        /// </summary>
-        public ushort Version;
-
-        /// <summary>
-        /// Specifies a DCE RPC identifier, if appropriate
-        /// </summary>
-        public ushort RPCID;
-
-        /// <summary>
-        /// Specifies the maximum size, in bytes, of the token.
-        /// </summary>
-        public int MaxToken;
-
-        /// <summary>
-        /// Pointer to a null-terminated string that contains the name of the security package.
-        /// </summary>
-        [MarshalAs(UnmanagedType.LPTStr)]
-        public string Name;
-
-        /// <summary>
-        /// Pointer to a null-terminated string. This can be any additional string passed back by the package.
-        /// </summary>
-        [MarshalAs(UnmanagedType.LPTStr)]
-        public string Comment;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecResult.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecResult.cs
deleted file mode 100644 (file)
index aef0d29..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Result of security operation
-    /// </summary>
-    internal enum SecResult : uint
-    {
-        Ok = 0,
-        ContinueNeeded = 0x90312,
-        PackageNotFound = 0x80090305,
-        CompleteAndContinue = 0x00090314,
-        CompleteNeeded = 0x00090313
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityHandle.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityHandle.cs
deleted file mode 100644 (file)
index 588581e..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Security handle
-    /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
-    internal struct SecurityHandle
-    {
-        public IntPtr LowPart;
-        public IntPtr HighPart;
-
-        /// <summary>
-        /// Check if instance of the security handle is valid
-        /// </summary>
-        internal bool IsValid()
-        {
-            return (LowPart != IntPtr.Zero) || (HighPart != IntPtr.Zero);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityInteger.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityInteger.cs
deleted file mode 100644 (file)
index 47b35f0..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Security integer
-    /// </summary>
-    [StructLayout(LayoutKind.Sequential)]
-    internal struct SecurityInteger
-    {
-        public uint LowPart;
-        public int HighPart;
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityWrapper.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/SSPI/SecurityWrapper.cs
deleted file mode 100644 (file)
index 03e27c5..0000000
+++ /dev/null
@@ -1,181 +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;
-
-namespace Microsoft.SqlServer.TDS.EndPoint.SSPI
-{
-    /// <summary>
-    /// Wrapper for security functions that implement SSPI
-    /// </summary>
-    internal class SecurityWrapper
-    {
-        /// <summary>
-        /// Acquires a handle to preexisting credentials of a security principal
-        /// </summary>
-        /// <param name="pszPrincipal">A pointer to a null-terminated string that specifies the name of the principal whose credentials the handle will reference</param>
-        /// <param name="pszPackage">A pointer to a null-terminated string that specifies the name of the security package with which these credentials will be used</param>
-        /// <param name="fCredentialUse">A flag that indicates how these credentials will be used</param>
-        /// <param name="pvLogonID">A pointer to a locally unique identifier (LUID) that identifies the user</param>
-        /// <param name="pAuthData">A pointer to package-specific data</param>
-        /// <param name="pGetKeyFn">This parameter is not used and should be set to NULL</param>
-        /// <param name="pvGetKeyArgument">This parameter is not used and should be set to NULL</param>
-        /// <param name="phCredential">A pointer to a CredHandle structure to receive the credential handle</param>
-        /// <param name="ptsExpiry">A pointer to a TimeStamp structure that receives the time at which the returned credentials expire</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Unicode, EntryPoint="AcquireCredentialsHandleW")]
-        internal static extern int AcquireCredentialsHandle(
-            string pszPrincipal,
-            string pszPackage,
-            int fCredentialUse,
-            IntPtr pvLogonID,
-            IntPtr pAuthData,
-            int pGetKeyFn,
-            IntPtr pvGetKeyArgument,
-            ref SecurityHandle phCredential,
-            ref SecurityInteger ptsExpiry);
-
-        /// <summary>
-        /// The InitializeSecurityContext (Schannel) function initiates the client side, outbound security context from a credential handle.
-        /// </summary>
-        /// <param name="phCredential">A handle to the credentials returned by AcquireCredentialsHandle</param>
-        /// <param name="phContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pszTargetName ">A pointer to a null-terminated string that uniquely identifies the target server</param>
-        /// <param name="fContextReq">Bit flags that indicate requests for the context</param>
-        /// <param name="Reserved1">This parameter is reserved and must be set to zero.</param>
-        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target</param>
-        /// <param name="pInput">A pointer to a SecBufferDesc structure that contains pointers to the buffers supplied as input to the package</param>
-        /// <param name="Reserved2">This parameter is reserved and must be set to zero.</param>
-        /// <param name="phNewContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the output buffer descriptor</param>
-        /// <param name="pfContextAttr">A pointer to a variable that receives a set of bit flags that indicate the attributes of the established context</param>
-        /// <param name="ptsTimeStamp">A pointer to a TimeStamp structure that receives the expiration time of the context</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Unicode, SetLastError = false, EntryPoint="InitializeSecurityContextW")]
-        internal static extern int InitializeSecurityContext(ref SecurityHandle phCredential,
-            IntPtr phContext,
-            string pszTargetName,
-            uint fContextReq,
-            int Reserved1,
-            uint TargetDataRep,
-            IntPtr pInput,
-            int Reserved2,
-            out SecurityHandle phNewContext,
-            out SecBufferDesc pOutput,
-            out uint pfContextAttr,
-            out SecurityInteger ptsTimeStamp);
-
-        /// <summary>
-        /// The InitializeSecurityContext (Schannel) function initiates the client side, outbound security context from a credential handle.
-        /// </summary>
-        /// <param name="phCredential">A handle to the credentials returned by AcquireCredentialsHandle</param>
-        /// <param name="phContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pszTargetName ">A pointer to a null-terminated string that uniquely identifies the target server</param>
-        /// <param name="fContextReq">Bit flags that indicate requests for the context</param>
-        /// <param name="Reserved1">This parameter is reserved and must be set to zero.</param>
-        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target</param>
-        /// <param name="pInput">A pointer to a SecBufferDesc structure that contains pointers to the buffers supplied as input to the package</param>
-        /// <param name="Reserved2">This parameter is reserved and must be set to zero.</param>
-        /// <param name="phNewContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the output buffer descriptor</param>
-        /// <param name="pfContextAttr">A pointer to a variable that receives a set of bit flags that indicate the attributes of the established context</param>
-        /// <param name="ptsTimeStamp">A pointer to a TimeStamp structure that receives the expiration time of the context</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Unicode, SetLastError = false, EntryPoint="InitializeSecurityContextW")]
-        internal static extern int InitializeSecurityContext(ref SecurityHandle phCredential,
-            ref SecurityHandle phContext,
-            string pszTargetName,
-            uint fContextReq,
-            int Reserved1,
-            uint TargetDataRep,
-            ref SecBufferDesc pInput,
-            int Reserved2,
-            out SecurityHandle phNewContext,
-            out SecBufferDesc pOutput,
-            out uint pfContextAttr,
-            out SecurityInteger ptsTimeStamp);
-
-        /// <summary>
-        /// The CompleteAuthToken function completes an authentication token
-        /// </summary>
-        /// <param name="phContext">A handle of the context that needs to be completed</param>
-        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the buffer descriptor for the entire message.</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Auto)]
-        internal static extern int CompleteAuthToken(ref SecurityHandle phContext, out SecBufferDesc pOutput);
-
-        /// <summary>
-        /// The AcceptSecurityContext (Negotiate) function enables the server component of a transport application to establish a security context between the server and a remote client
-        /// </summary>
-        /// <param name="phCredential">A handle to the credentials of the server</param>
-        /// <param name="phContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pInput">A pointer to a SecBufferDesc structure generated by a client call to InitializeSecurityContext (Negotiate) that contains the input buffer descriptor</param>
-        /// <param name="fContextReq">Bit flags that specify the attributes required by the server to establish the context</param>
-        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target</param>
-        /// <param name="phNewContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the output buffer descriptor</param>
-        /// <param name="pfContextAttr">A pointer to a variable that receives a set of bit flags that indicate the attributes of the established context</param>
-        /// <param name="ptsTimeStamp">A pointer to a TimeStamp structure that receives the expiration time of the context</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Auto, SetLastError = false)]
-        internal static extern int AcceptSecurityContext(ref SecurityHandle phCredential,
-            IntPtr phContext,
-            ref SecBufferDesc pInput,
-            uint fContextReq,
-            uint TargetDataRep,
-            out SecurityHandle phNewContext,
-            out SecBufferDesc pOutput,
-            out uint pfContextAttr,
-            out SecurityInteger ptsTimeStamp);
-
-        /// <summary>
-        /// The AcceptSecurityContext (Negotiate) function enables the server component of a transport application to establish a security context between the server and a remote client
-        /// </summary>
-        /// <param name="phCredential">A handle to the credentials of the server</param>
-        /// <param name="phContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pInput">A pointer to a SecBufferDesc structure generated by a client call to InitializeSecurityContext (Negotiate) that contains the input buffer descriptor</param>
-        /// <param name="fContextReq">Bit flags that specify the attributes required by the server to establish the context</param>
-        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target</param>
-        /// <param name="phNewContext">A pointer to a CtxtHandle structure</param>
-        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the output buffer descriptor</param>
-        /// <param name="pfContextAttr">A pointer to a variable that receives a set of bit flags that indicate the attributes of the established context</param>
-        /// <param name="ptsTimeStamp">A pointer to a TimeStamp structure that receives the expiration time of the context</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Auto, SetLastError = false)]
-        internal static extern int AcceptSecurityContext(ref SecurityHandle phCredential,
-            ref SecurityHandle phContext,
-            ref SecBufferDesc pInput,
-            uint fContextReq,
-            uint TargetDataRep,
-            out SecurityHandle phNewContext,
-            out SecBufferDesc pOutput,
-            out uint pfContextAttr,
-            out SecurityInteger ptsTimeStamp);
-
-        /// <summary>
-        /// The FreeCredentialsHandle function notifies the security system that the credentials are no longer needed
-        /// </summary>
-        /// <param name="phCredential">A pointer to the CredHandle handle obtained by using the AcquireCredentialsHandle (General) function</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Auto)]
-        internal static extern int FreeCredentialsHandle(ref SecurityHandle phCredential);
-
-        /// <summary>
-        /// The FreeCredentialsHandle function notifies the security system that the credentials are no longer needed
-        /// </summary>
-        /// <param name="phContext">Handle of the context to query</param>
-        /// <param name="phToken">Returned handle to the access token</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Auto)]
-        internal static extern int QuerySecurityContextToken(ref SecurityHandle phContext, ref IntPtr phToken);
-
-        /// <summary>
-        /// Retrieves information about a specified security package
-        /// </summary>
-        /// <param name="packageName">Pointer to a null-terminated string that specifies the name of the security package</param>
-        /// <param name="ppPackageInfo">Pointer to a variable that receives a pointer to a SecPkgInfo structure containing information about the specified security package</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Unicode, EntryPoint="QuerySecurityPackageInfoW")]
-        internal static extern int QuerySecurityPackageInfo([MarshalAs(UnmanagedType.LPTStr)] string packageName, ref IntPtr ppPackageInfo);
-
-        /// <summary>
-        /// The FreeContextBuffer function enables callers of security package functions to free memory buffers allocated by the security package.
-        /// </summary>
-        /// <param name="pvContextBuffer">A pointer to memory to be freed</param>
-        [DllImport(Interop.Libraries.SspiCli, CharSet = CharSet.Auto)]
-        internal static extern int FreeContextBuffer(IntPtr pvContextBuffer);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDS.EndPoint.csproj b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDS.EndPoint.csproj
deleted file mode 100644 (file)
index 003a40d..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <RootNamespace>Microsoft.SqlServer.TDS.EndPoint</RootNamespace>
-    <AssemblyName>Microsoft.SqlServer.TDS.EndPoint</AssemblyName>
-    <ClsCompliant>false</ClsCompliant>
-    <Configurations>netstandard2.0-Unix-Debug;netstandard2.0-Unix-Release;netstandard2.0-Windows_NT-Debug;netstandard2.0-Windows_NT-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="FederatedAuthentication\FederatedAuthenticationTicketService.cs" />
-    <Compile Include="FederatedAuthentication\IFederatedAuthenticationTicket.cs" />
-    <Compile Include="FederatedAuthentication\Rps.cs" />
-    <Compile Include="FederatedAuthentication\RpsTicket.cs" />
-    <Compile Include="ITDSClientContext.cs" />
-    <Compile Include="ITDSServerSession.cs" />
-    <Compile Include="SSPI\SecBuffer.cs" />
-    <Compile Include="SSPI\SecBufferDescType.cs" />
-    <Compile Include="SSPI\SecConstants.cs" />
-    <Compile Include="SSPI\SecBufferDesc.cs" />
-    <Compile Include="SSPI\SecBufferType.cs" />
-    <Compile Include="SSPI\SecContextRequirements.cs" />
-    <Compile Include="SSPI\SecDataRepresentation.cs" />
-    <Compile Include="SSPI\SecPgkCredentials.cs" />
-    <Compile Include="SSPI\SecPkgInfo.cs" />
-    <Compile Include="SSPI\SecResult.cs" />
-    <Compile Include="SSPI\SecurityHandle.cs" />
-    <Compile Include="SSPI\SecurityInteger.cs" />
-    <Compile Include="PlaceholderStream.cs" />
-    <Compile Include="SSPI\SSPIResponse.cs" />
-    <Compile Include="TDSClientEndPoint.cs" />
-    <Compile Include="ITDSClient.cs" />
-    <Compile Include="ITDSServer.cs" />
-    <Compile Include="TDSClientParser.cs" />
-    <Compile Include="TDSEndPointInfo.cs" />
-    <Compile Include="TDSEndPointTransportType.cs" />
-    <Compile Include="TDSParser.cs" />
-    <Compile Include="TDSServerEndPoint.cs" />
-    <Compile Include="TDSServerEndPointConnection.cs" />
-    <Compile Include="TDSServerParser.cs" />
-  </ItemGroup>
-  <ItemGroup Condition=" '$(TargetsWindows)' == 'true' ">
-    <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs">
-      <Link>Common\Interop\Windows\Interop.Libraries.cs</Link>
-    </Compile>
-    <Compile Include="SSPI\SSPIContext.Windows.cs" />
-    <Compile Include="SSPI\SecurityWrapper.cs" />
-  </ItemGroup>
-  <ItemGroup Condition=" '$(TargetsWindows)' != 'true' ">
-    <Compile Include="SSPI\SSPIContext.Unix.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\TDS\TDS.csproj" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSClientEndPoint.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSClientEndPoint.cs
deleted file mode 100644 (file)
index 54e34f7..0000000
+++ /dev/null
@@ -1,259 +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.Net.Sockets;
-using System.IO.Pipes;
-using System.Security.Principal;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Client that talks TDS
-    /// </summary>
-    public class TDSClientEndPoint
-    {
-        /// <summary>
-        /// Gets/Sets the event log for the proxy server
-        /// </summary>
-        public TextWriter EventLog { get; set; }
-
-        /// <summary>
-        /// Client
-        /// </summary>
-        public ITDSClient TDSClient { get; private set; }
-
-        /// <summary>
-        /// Socket that talks to TDS server
-        /// </summary>
-        private TcpClient ClientSocket { get; set; }
-
-        //
-        // Named pipes client
-        //
-        private NamedPipeClientStream ClientPipe { get; set; }
-
-        /// <summary>
-        /// TDS parser
-        /// </summary>
-        private TDSClientParser ClientParser { get; set; }
-
-        /// <summary>
-        /// TDSStream Prewrite call back
-        /// </summary>
-        private Func<byte[], int, int, ushort> _funcTDSStreamPreWriteCallBack;
-
-        /// <summary>
-        /// PostConnect call back for socket attributes setting
-        /// </summary>
-        private Action<TcpClient> _funcPostConnect;
-
-        /// <summary>
-        /// PostConnect call back for socket attributes setting
-        /// </summary>
-        private Action<TcpClient> _funcTCPClientDisconnect;
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="client">TDS client instance that will drive the communication with the TDS server</param>
-        public TDSClientEndPoint(ITDSClient client)
-            : this(client, null, null, null)
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSClientEndPoint(ITDSClient client, Func<byte[], int, int, ushort> funcTDSStreamPreWriteCallBack, Action<TcpClient> funcPostConnect, Action<TcpClient> funcTCPClientDisconnect)
-        {
-            // Save client instance
-            TDSClient = client;
-
-            _funcTDSStreamPreWriteCallBack = funcTDSStreamPreWriteCallBack;
-            _funcPostConnect = funcPostConnect;
-            _funcTCPClientDisconnect = funcTCPClientDisconnect;
-        }
-
-        /// <summary>
-        /// Establish connection and log into the SQL Server
-        /// </summary>
-        public void Connect()
-        {
-            // Initialize context
-            TDSClient.OnPreConnect();
-
-            // Loop while we reach logged-in state. This accounts for connection failures and routing.
-            while (TDSClient.State != TDSClientState.LoggedIn)
-            {
-                Log("Connecting to the server {0} port {1}...", TDSClient.Context.ServerHost, TDSClient.Context.ServerPort);
-
-                // Check if server pipe is specified
-                if (string.IsNullOrEmpty(TDSClient.Context.ServerPipe))
-                {
-                    try
-                    {
-                        // Establish transport to the TDS Server
-                        ClientSocket = new TcpClient(AddressFamily.InterNetwork);
-                        ClientSocket.Connect(TDSClient.Context.ServerHost, (int)TDSClient.Context.ServerPort);
-                    }
-                    catch (SocketException e)
-                    {
-                        // Check error code
-                        if (e.ErrorCode != 10057)
-                        {
-                            // We don't recognize it
-                            throw e;
-                        }
-
-                        // We are going to retry with IPv6 now because of won't fix bug
-                        // http://bugcheck/bugs/VSWhidbey/285220
-                        ClientSocket = new TcpClient(AddressFamily.InterNetworkV6);
-                        ClientSocket.Connect(TDSClient.Context.ServerHost, (int)TDSClient.Context.ServerPort);
-                    }
-
-                    // Callback of PostConnect
-                    if (_funcPostConnect != null)
-                    {
-                        _funcPostConnect(ClientSocket);
-                    }
-                }
-                else
-                {
-                    // Use named pipes transport
-                    ClientPipe = new NamedPipeClientStream(TDSClient.Context.ServerHost, TDSClient.Context.ServerPipe, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);
-                    ClientPipe.Connect();
-                }
-
-                Log("Connected");
-
-                try
-                {
-                    // Check if we have a client socket
-                    if (ClientSocket != null)
-                    {
-                        // Create a client TDS parser with TCP transport
-                        ClientParser = new TDSClientParser(TDSClient, ClientSocket.GetStream());
-                    }
-                    else
-                    {
-                        // Create a client TDS parser through named pipes transort
-                        ClientParser = new TDSClientParser(TDSClient, ClientPipe);
-                    }
-
-                    if (_funcTDSStreamPreWriteCallBack != null)
-                    {
-                        ClientParser.SetTDSStreamPreWriteCallback(_funcTDSStreamPreWriteCallBack);
-                    }
-
-                    // Assign event log
-                    ClientParser.EventLog = EventLog;
-
-                    // Run login sequence
-                    ClientParser.Login();
-
-                    // Check if connection is being re-routed
-                    if (TDSClient.State == TDSClientState.ReConnect)
-                    {
-                        Log("Client is being routed");
-
-                        // Close established connection
-                        Disconnect();
-                    }
-                }
-                catch (Exception)
-                {
-                    // Disconnect client
-                    Disconnect();
-
-                    // Bubble up the exception
-                    throw;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Dispatch a request to the server
-        /// </summary>
-        public void SendRequest()
-        {
-            // Check if we're connected
-            if (ClientParser == null || TDSClient.State != TDSClientState.LoggedIn)
-            {
-                throw new Exception("Client must be connected and logged in");
-            }
-
-            // Delegate to the parser
-            ClientParser.SendRequest();
-        }
-
-        /// <summary>
-        /// Log out and disconnect from SQL Server
-        /// </summary>
-        public void Disconnect()
-        {
-            // Check client state
-            if (TDSClient.State != TDSClientState.Final)
-            {
-                // Logout
-                ClientParser.Logout();
-            }
-
-            // Check if client socket is available
-            if (ClientSocket != null)
-            {
-                // Check if client is connected
-                if (ClientSocket.Connected)
-                {
-                    Log("Disconnecting...");
-
-                    // Close the connection
-                    if (_funcTCPClientDisconnect == null)
-                    {
-                        ClientSocket.Client.Disconnect(true);
-                    }
-                    else
-                    {
-                        _funcTCPClientDisconnect(ClientSocket);
-                    }
-
-                    Log("Disconnected");
-                }
-
-                // Reset client socket
-                ClientSocket = null;
-            }
-
-            // Check if client pipe is available
-            if (ClientPipe != null)
-            {
-                // Check if client is connected
-                if (ClientPipe.IsConnected)
-                {
-                    Log("Disconnecting...");
-
-                    // Close the connection
-                    ClientPipe.Close();
-
-                    Log("Disconnected");
-                }
-
-                // Reset client pipe
-                ClientPipe = null;
-            }
-        }
-
-        /// <summary>
-        /// Write a string to the log
-        /// </summary>
-        internal void Log(string text, params object[] args)
-        {
-            if (EventLog != null)
-            {
-                EventLog.WriteLine("[TDSClientEndPoint]: " + text, args);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSClientParser.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSClientParser.cs
deleted file mode 100644 (file)
index 4b620eb..0000000
+++ /dev/null
@@ -1,239 +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;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Parser of the TDS packets on the client
-    /// </summary>
-    public class TDSClientParser : TDSParser
-    {
-        /// <summary>
-        /// TDS client that generates data
-        /// </summary>
-        private ITDSClient Client { get; set; }
-
-        /// <summary>
-        /// Client TDS parser initialization constructor
-        /// </summary>
-        public TDSClientParser(ITDSClient client, Stream transport) :
-            base(transport)
-        {
-            // Save the client
-            Client = client;
-
-            // Initialize protocol stream
-            Transport.PacketSize = client.Context.PacketSize;
-        }
-
-        /// <summary>
-        /// Authenticate against TDS Server
-        /// </summary>
-        public void Login()
-        {
-            // Loop until parser enters logged-in state
-            while (Client.State != TDSClientState.LoggedIn && Client.State != TDSClientState.ReConnect)
-            {
-                // Prepare request response container
-                TDSMessage requestMessage = null;
-
-                // Check the state of the client
-                switch (Client.State)
-                {
-                    case TDSClientState.PreLoginSent:
-                        {
-                            // Read pre-login response
-                            TDSMessage responseMessage = _ReadResponse();
-
-                            // Call into the subscriber to process the server response and generate subsequent request
-                            requestMessage = Client.OnPreLoginResponse(responseMessage);
-
-                            // Check the client context for encryption state
-                            if (Client.Context.Encryption != TDSEncryptionType.Off)
-                            {
-                                // Turn on encryption before sending the response
-                                EnableClientTransportEncryption(Client.Context.ServerHost);
-                            }
-
-                            break;
-                        }
-
-                    case TDSClientState.Login7FederatedAuthenticationInformationRequestSent:
-                        {
-                            // Read FedAuthInfoToken response
-                            TDSMessage responseMessage = _ReadResponse();
-
-                            // Generate the FedAuthTokenMessage
-                            requestMessage = Client.OnFedAuthInfoTokenResponse(responseMessage);
-                            break;
-                        }
-
-                    case TDSClientState.CompleteLogin7Sent:
-                        {
-                            // Read login response
-                            TDSMessage responseMessage = _ReadResponse();
-
-                            // Call into the subscriber to process the server response and generate subsequent request
-                            Client.OnLoginResponse(responseMessage);
-                            break;
-                        }
-                    case TDSClientState.Login7SPNEGOSent:
-                        {
-                            // Read SPNEGO response
-                            TDSMessage responseMessage = _ReadResponse();
-
-                            // Call into the subscriber to process the server response and generate subsequent request
-                            requestMessage = Client.OnSSPIResponse(responseMessage);
-                            break;
-                        }
-
-                    case TDSClientState.LoggedIn:
-                    case TDSClientState.ReConnect:
-                        {
-                            // We reached the target state
-                            requestMessage = null;
-                            break;
-                        }
-                    default:
-                        {
-                            // Initiate conversation with TDS Server
-                            requestMessage = Client.OnPreLogin();
-                            break;
-                        }
-                }
-
-                // Send a request to the server
-                _WriteRequest(requestMessage);
-
-                // Check if we need to turn off encryption at this point
-                if (Client.Context.Encryption == TDSEncryptionType.LoginOnly)
-                {
-                    // Verify client state
-                    if (Client.State == TDSClientState.CompleteLogin7Sent || Client.State == TDSClientState.Login7SPNEGOSent)
-                    {
-                        // Turn off encryption before reading the response
-                        DisableTransportEncryption();
-                    }
-                }
-            }
-        }
-
-        /// <summary>
-        /// Dispatch a request to the server and process the response
-        /// </summary>
-        public void SendRequest()
-        {
-            // Obtain the request message from the client parser
-            TDSMessage requestMessage = Client.OnRequest();
-
-            // Send a request to the server
-            _WriteRequest(requestMessage);
-
-            // Check if request message is available
-            if (requestMessage != null)
-            {
-                // Read response
-                TDSMessage responseMessage = _ReadResponse();
-
-                // Process the response with the client parser
-                Client.OnResponse(responseMessage);
-
-                // Log event
-                Log("Client entered a state \"{0}\"", Client.State);
-            }
-        }
-
-        /// <summary>
-        /// Complete
-        /// </summary>
-        public void Logout()
-        {
-            // Loop until parser enters final state
-            while (Client.State != TDSClientState.Final)
-            {
-                // Prepare request response container
-                TDSMessage requestMessage = null;
-
-                // Check the state of the client
-                switch (Client.State)
-                {
-                    case TDSClientState.LogoutSent:
-                        {
-                            // Read logout response
-                            TDSMessage responseMessage = _ReadResponse();
-
-                            // Process logout response
-                            Client.OnLogoutResponse(responseMessage);
-                            break;
-                        }
-                    default:
-                        {
-                            // Request logout notification
-                            requestMessage = Client.OnLogout();
-                            break;
-                        }
-                }
-
-                // Send a request to the server
-                _WriteRequest(requestMessage);
-            }
-
-            // Turn off transport encryption in case it was turned on so that subsequent login can be handled properly
-            DisableTransportEncryption();
-        }
-
-        /// <summary>
-        /// Read data from TDS server
-        /// </summary>
-        /// <returns></returns>
-        private TDSMessage _ReadResponse()
-        {
-            // Prepare response container
-            TDSMessage responseMessage = new TDSMessage();
-
-            // Loop as long as it takes to receive the entire message
-            while (!responseMessage.InflateServerResponse(Client.State, Transport))
-            {
-                // Switch context to avoid CPU overloading
-                System.Threading.Thread.Sleep(1);
-            }
-
-            // Log event
-            Log("Recieved a response to \"{0}\"", Client.State);
-
-            // Return what we inflated
-            return responseMessage;
-        }
-
-        /// <summary>
-        /// Send a request to the TDS server
-        /// </summary>
-        private void _WriteRequest(TDSMessage requestMessage)
-        {
-            // Check if TDS packet size changed
-            if (Client.Context.PacketSize != Transport.PacketSize)
-            {
-                // Update packet size
-                Transport.PacketSize = Client.Context.PacketSize;
-            }
-
-            // Check if there is  request to send
-            if (requestMessage != null)
-            {
-                // Dispatch the request to the server
-                requestMessage.Deflate(Transport);
-
-                // Log event
-                Log("Sent a request and entered \"{0}\"", Client.State);
-            }
-            else
-            {
-                // Log event
-                Log("Client entered \"{0}\"", Client.State);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSEndPointInfo.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSEndPointInfo.cs
deleted file mode 100644 (file)
index c5ff508..0000000
+++ /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.Net;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Container of the connection end-point information
-    /// </summary>
-    public class TDSEndPointInfo
-    {
-        /// <summary>
-        /// IP address to/from which connection is established
-        /// </summary>
-        public IPAddress Address { get; internal set; }
-
-        /// <summary>
-        /// Port number
-        /// </summary>
-        public int Port { get; internal set; }
-
-        /// <summary>
-        /// Transport protocol for the end-point
-        /// </summary>
-        public TDSEndPointTransportType Transport { get; internal set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSEndPointInfo()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSEndPointInfo(IPAddress address)
-        {
-            Address = address;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSEndPointInfo(IPAddress address, int port) :
-            this(address)
-        {
-            Port = port;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSEndPointInfo(IPAddress address, int port, TDSEndPointTransportType transport) :
-            this(address, port)
-        {
-            Transport = transport;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSEndPointTransportType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSEndPointTransportType.cs
deleted file mode 100644 (file)
index dbde218..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Transport of the connection end-point
-    /// </summary>
-    public enum TDSEndPointTransportType
-    {
-        /// <summary>
-        /// TCP protocol
-        /// </summary>
-        TCP
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSParser.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSParser.cs
deleted file mode 100644 (file)
index 2027c7b..0000000
+++ /dev/null
@@ -1,184 +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.Net.Security;
-using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Generic TDS parser
-    /// </summary>
-    public class TDSParser
-    {
-        /// <summary>
-        /// Transport stream that was assigned to this parser prior to connection encryption
-        /// </summary>
-        private Stream _originalTransport;
-
-        /// <summary>
-        /// Writer to log events to
-        /// </summary>
-        public TextWriter EventLog { get; set; }
-
-        /// <summary>
-        /// Encryption protocol for server to use with AuthenticateAsServer
-        /// </summary>
-        public static SslProtocols ServerSslProtocol { get; set; }
-
-        /// <summary>
-        /// Protocol stream between the client and the server
-        /// </summary>
-        protected TDSStream Transport { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSParser(Stream transport)
-        {
-            // Save original transport
-            _originalTransport = transport;
-
-            ServerSslProtocol = SslProtocols.Tls12;
-
-            // Wrap transport layer with TDS
-            Transport = new TDSStream(transport, false);
-        }
-
-        /// <summary>
-        /// Set PreWriteCallback func in Transport (TDSStream)
-        /// </summary>
-        public void SetTDSStreamPreWriteCallback(Func<byte[], int, int, ushort> funcTDSStreamPreWriteCallBack)
-        {
-            Transport.PreWriteCallBack = funcTDSStreamPreWriteCallBack;
-        }
-
-        /// <summary>
-        /// Resets the targeted encryption protocol for the server.
-        /// </summary>
-        public static void ResetTargetProtocol()
-        {
-            ServerSslProtocol = SslProtocols.Tls12;
-        }
-
-        /// <summary>
-        /// Enable transport encryption
-        /// </summary>
-        protected void EnableClientTransportEncryption(string server)
-        {
-            // Check if transport encryption is applied
-            if (Transport.InnerStream is SslStream)
-            {
-                return;
-            }
-
-            Log("Enabling client transport encryption...");
-
-            // Wrap TDS stream with auto TDS stream
-            AutoTDSStream tds = new AutoTDSStream(Transport, false);
-
-            // We want to wrap each TLS message with PreLogin
-            tds.OutgoingMessageType = TDSMessageType.PreLogin;
-
-            // Create multiplexer stream to be able to remove TDS from under SSL
-            PlaceholderStream multiplexer = new PlaceholderStream(tds, false);
-
-            // Wrap multiplexer stream with SSL stream
-            SslStream ssl = new SslStream(multiplexer, true, new RemoteCertificateValidationCallback(_ValidateServerCertificate));
-
-            // Secure the channel
-            ssl.AuthenticateAsClient(server);
-
-            // Replace TDS stream with raw transport stream in multiplexer
-            multiplexer.InnerStream = Transport.InnerStream;
-
-            // Upgrade transport stream to SSL
-            Transport.InnerStream = ssl;
-
-            Log("Client transport encryption enabled");
-        }
-
-        /// <summary>
-        /// Enable transport encryption
-        /// </summary>
-        protected void EnableServerTransportEncryption(X509Certificate certificate)
-        {
-            // Check if transport encryption is applied
-            if (Transport.InnerStream is SslStream)
-            {
-                return;
-            }
-
-            Log("Enabling server transport encryption...");
-
-            // Wrap TDS stream with auto TDS stream
-            AutoTDSStream tds = new AutoTDSStream(Transport, false);
-
-            // We want to wrap each TLS message with PreLogin
-            tds.OutgoingMessageType = TDSMessageType.PreLogin;
-
-            // Create multiplexer stream to be able to remove TDS from under SSL
-            PlaceholderStream multiplexer = new PlaceholderStream(tds, false);
-
-            // Wrap multiplexer stream with SSL stream
-            SslStream ssl = new SslStream(multiplexer, true);
-
-            // Secure the channel
-            ssl.AuthenticateAsServer(certificate, false, ServerSslProtocol, false);
-
-            // Replace TDS stream with raw transport stream in multiplexer
-            multiplexer.InnerStream = Transport.InnerStream;
-
-            // Upgrade transport stream to SSL
-            Transport.InnerStream = ssl;
-
-            Log("Server transport encryption enabled");
-        }
-
-        /// <summary>
-        /// Disable transport encryption
-        /// </summary>
-        protected void DisableTransportEncryption()
-        {
-            // Check if transport stream is using SSL
-            if (!(Transport.InnerStream is SslStream))
-            {
-                return;
-            }
-
-            Log("Disabling transport encryption...");
-
-            // Close the SSL stream
-            Transport.InnerStream.Close();
-
-            // Use original transport stream
-            Transport.InnerStream = _originalTransport;
-
-            Log("Transport encryption disabled");
-        }
-
-        /// <summary>
-        /// Validate server certificate
-        /// </summary>
-        private bool _ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
-        {
-            // We always trust server certificate
-            return true;
-        }
-
-        /// <summary>
-        /// Write a string to the log
-        /// </summary>
-        protected void Log(string text, params object[] args)
-        {
-            if (EventLog != null)
-            {
-                EventLog.WriteLine("[TDSParser]: " + text, args);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerEndPoint.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerEndPoint.cs
deleted file mode 100644 (file)
index 550cbe3..0000000
+++ /dev/null
@@ -1,255 +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.IO;
-using System.Net;
-using System.Net.Sockets;
-using System.Threading;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Server that talks TDS
-    /// </summary>
-    public class TDSServerEndPoint : ServerEndPointHandler<TDSServerEndPointConnection>
-    {
-        public TDSServerEndPoint(ITDSServer server)
-            : base(server)
-        {
-        }
-
-        public override TDSServerEndPointConnection CreateConnection(TcpClient newConnection)
-        {
-            return new TDSServerEndPointConnection(TDSServer, newConnection);
-        }
-    }
-
-    /// <summary>
-    /// General server handler
-    /// </summary>
-    public abstract class ServerEndPointHandler<T> where T : ServerEndPointConnection
-    {
-        /// <summary>
-        /// Gets/Sets the event log for the proxy server
-        /// </summary>
-        public TextWriter EventLog { get; set; }
-
-        /// <summary>
-        /// Server
-        /// </summary>
-        public ITDSServer TDSServer { get; private set; }
-
-        /// <summary>
-        /// The list of connections spawned by the server
-        /// </summary>
-        internal IList<T> Connections { get; set; }
-
-        /// <summary>
-        /// End-point which TDS server is listening on
-        /// </summary>
-        public IPEndPoint ServerEndPoint { get; set; }
-
-        /// <summary>
-        /// Gets/Sets the listener
-        /// </summary>
-        private TcpListener ListenerSocket { get; set; }
-
-        /// <summary>
-        /// Gets/Sets the listener thread
-        /// </summary>
-        private Thread ListenerThread { get; set; }
-
-        /// <summary>
-        /// Gets/Sets the flag whether the stop is requested
-        /// </summary>
-        internal bool StopRequested { get; set; }
-
-
-        /// <summary>
-        /// Identifier to recognize the client of the Endpoint.
-        /// </summary>
-        public string EndpointName { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="server">TDS server instance that will process requests</param>
-        public ServerEndPointHandler(ITDSServer server)
-        {
-            // Prepare connections container
-            Connections = new List<T>();
-
-            // Save server instance
-            TDSServer = server;
-        }
-
-        /// <summary>
-        /// Start the listener thread
-        /// </summary>
-        public void Start()
-        {
-            StopRequested = false;
-
-            // Start the server synchronously to ensure that instantiation exception is thrown (if any)
-            ListenerSocket = new TcpListener(ServerEndPoint);
-            ListenerSocket.Start();
-
-            // Update ServerEndpoint with the actual address/port, e.g. if port=0 was given
-            ServerEndPoint = (IPEndPoint)ListenerSocket.LocalEndpoint;
-
-            Log($"{GetType().Name} {EndpointName} Is Server Socket Bound: {ListenerSocket.Server.IsBound} Testing connectivity to the endpoint created for the server.");
-            using (TcpClient client = new TcpClient())
-            {
-                try
-                {
-                    client.Connect("localhost", ServerEndPoint.Port);
-                }
-                catch (Exception e)
-                {
-                    Log($"{GetType().Name} {EndpointName} Error occured while testing server endpoint {e.Message}");
-                    throw;
-                }
-            }
-            Log($"{GetType().Name} {EndpointName} Endpoint test successful.");
-
-            // Initialize the listener
-            ListenerThread = new Thread(new ThreadStart(_RequestListener)) { IsBackground = true };
-            ListenerThread.Name = "TDS Server EndPoint Listener";
-            ListenerThread.Start();
-
-            Log($"{GetType().Name} {EndpointName} Listener Thread Started ");
-        }
-
-        /// <summary>
-        /// Stop the listener thread
-        /// </summary>
-        public void Stop()
-        {
-            // Request the listener thread to stop
-            StopRequested = true;
-
-            // A copy of the list of connections to avoid locking
-            IList<T> unlockedConnections = new List<T>();
-
-            // Synchronize access to connections collection
-            lock (Connections)
-            {
-                // Iterate over all connections and copy into the local list
-                foreach (T connection in Connections)
-                {
-                    unlockedConnections.Add(connection);
-                }
-            }
-
-            // Iterate over all connections and request each one to stop
-            foreach (T connection in unlockedConnections)
-            {
-                // Request to stop
-                connection.Stop();
-            }
-
-            // If server failed to start there is no thread to join
-            if (ListenerThread != null)
-            {
-                // Wait for termination
-                ListenerThread.Join();
-            }
-
-            // If server failed to start there is no listener associated with it
-            if (ListenerSocket != null)
-            {
-                // Stop the server
-                ListenerSocket.Stop();
-                ListenerSocket = null;
-            }
-        }
-
-        /// <summary>
-        /// Processes all incoming requests
-        /// </summary>
-        private void _RequestListener()
-        {
-            try
-            {
-                // Accept connection as long as stop request is not posted
-                while (!StopRequested)
-                {
-                    // Check if we have a connection request pending
-                    if (ListenerSocket.Pending())
-                    {
-                        try
-                        {
-                            // Accept the connection
-                            TcpClient newConnection = ListenerSocket.AcceptTcpClient();
-
-                            // Create a new connection
-                            T connection = CreateConnection(newConnection);
-
-                            // Assign a log
-                            connection.EventLog = EventLog;
-
-                            // Subscribe for notifications
-                            connection.OnConnectionClosed += new ConnectionClosedEventHandler(_OnConnectionClosed);
-
-                            // Start a connection
-                            connection.Start();
-
-                            // Synchronize access to connections collection
-                            lock (Connections)
-                            {
-                                // Register a new connection
-                                Connections.Add(connection);
-                            }
-                        }
-                        catch (Exception ex)
-                        {
-                            Log(ex.ToString());
-                        }
-                    }
-                    else
-                    {
-                        // Pause a bit
-                        Thread.Sleep(10);
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                Log(ex.ToString());
-            }
-        }
-
-        /// <summary>
-        /// Creates a new connection handler for the given TCP connection
-        /// </summary>
-        public abstract T CreateConnection(TcpClient newConnection);
-
-        /// <summary>
-        /// Event handler for client connection termination
-        /// </summary>
-        private void _OnConnectionClosed(object sender, EventArgs e)
-        {
-            // Synchronize access to connection collection
-            lock (Connections)
-            {
-                // Remove the existing connection from the list
-                Connections.Remove(sender as T);
-                Log($"{GetType().Name} {EndpointName} Connection Closed");
-            }
-        }
-
-        /// <summary>
-        /// Write a string to the log
-        /// </summary>
-        internal void Log(string text, params object[] args)
-        {
-            if (EventLog != null)
-            {
-                EventLog.WriteLine(text, args);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerEndPointConnection.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerEndPointConnection.cs
deleted file mode 100644 (file)
index a714360..0000000
+++ /dev/null
@@ -1,228 +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.Net;
-using System.Net.Sockets;
-using System.Threading;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// A delegate for client connection termination
-    /// </summary>
-    public delegate void ConnectionClosedEventHandler(object sender, EventArgs e);
-
-    /// <summary>
-    /// Connection to a single client that handles TDS data
-    /// </summary>
-    public class TDSServerEndPointConnection : ServerEndPointConnection
-    {
-        private TDSServerParser _parser;
-
-        public TDSServerEndPointConnection(ITDSServer server, TcpClient connection)
-            : base(server, connection)
-        {
-        }
-
-        public override void PrepareForProcessingData(Stream rawStream)
-        {
-            // Create a server TDS parser
-            Debug.Assert(_parser == null, "PrepareForProcessingData should not be called twice");
-            _parser = new TDSServerParser(Server, Session, rawStream);
-        }
-
-        public override void ProcessData(Stream rawStream)
-        {
-            _parser.Run();
-        }
-    }
-
-    /// <summary>
-    /// Connection to a single client
-    /// </summary>
-    public abstract class ServerEndPointConnection
-    {
-        /// <summary>
-        /// Worker thread
-        /// </summary>
-        protected Thread ProcessorThread { get; set; }
-
-        /// <summary>
-        /// Gets/Sets the event log for the proxy server
-        /// </summary>
-        public TextWriter EventLog { get; set; }
-
-        /// <summary>
-        /// TDS Server to which this connection is established
-        /// </summary>
-        public ITDSServer Server { get; protected set; }
-
-        /// <summary>
-        /// TDS Server session that is assigned to this physical connection
-        /// </summary>
-        public ITDSServerSession Session { get; protected set; }
-
-        /// <summary>
-        /// Event that is fired when connection is closed
-        /// </summary>
-        public event ConnectionClosedEventHandler OnConnectionClosed;
-
-        /// <summary>
-        /// Connection itself
-        /// </summary>
-        protected TcpClient Connection { get; set; }
-
-        /// <summary>
-        /// The flag indicates whether server is being stopped
-        /// </summary>
-        protected bool StopRequested { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public ServerEndPointConnection(ITDSServer server, TcpClient connection)
-        {
-            // Save server
-            Server = server;
-
-            // Save TCP connection
-            Connection = connection;
-
-            // Configure timeouts
-            Connection.ReceiveTimeout = 1000;
-
-            // Create a new TDS server session
-            Session = server.OpenSession();
-
-            // Check if local end-point is recognized
-            if (Connection.Client.LocalEndPoint is IPEndPoint)
-            {
-                // Cast to IP end-point
-                IPEndPoint endPoint = Connection.Client.LocalEndPoint as IPEndPoint;
-
-                // Update TDS session
-                Session.ServerEndPointInfo = new TDSEndPointInfo(endPoint.Address, endPoint.Port, TDSEndPointTransportType.TCP);
-            }
-
-            // Check if remote end-point is recognized
-            if (Connection.Client.RemoteEndPoint is IPEndPoint)
-            {
-                // Cast to IP end-point
-                IPEndPoint endPoint = Connection.Client.RemoteEndPoint as IPEndPoint;
-
-                // Update server context
-                Session.ClientEndPointInfo = new TDSEndPointInfo(endPoint.Address, endPoint.Port, TDSEndPointTransportType.TCP);
-            }
-        }
-
-        /// <summary>
-        /// Start the connection
-        /// </summary>
-        internal void Start()
-        {
-            // Start with active connection
-            StopRequested = false;
-
-            // Prepare and start a thread
-            ProcessorThread = new Thread(new ThreadStart(_ConnectionHandler)) { IsBackground = true };
-            ProcessorThread.Name = string.Format("TDS Server Connection {0} Thread", Connection.Client.RemoteEndPoint);
-            ProcessorThread.Start();
-        }
-
-        /// <summary>
-        /// Stop the connection
-        /// </summary>
-        internal void Stop()
-        {
-            // Request the listener thread to stop
-            StopRequested = true;
-
-            // If connection failed to start there's no processor thread
-            if (ProcessorThread != null)
-            {
-                // Wait for termination
-                ProcessorThread.Join();
-            }
-        }
-
-        /// <summary>
-        /// Called when the data processing thread is first started
-        /// </summary>
-        public abstract void PrepareForProcessingData(Stream rawStream);
-
-        /// <summary>
-        /// Called every time there is new data available
-        /// </summary>
-        public abstract void ProcessData(Stream rawStream);
-
-        /// <summary>
-        /// Worker thread
-        /// </summary>
-        private void _ConnectionHandler()
-        {
-            try
-            {
-                // Get network stream
-                NetworkStream rawStream = Connection.GetStream();
-                PrepareForProcessingData(rawStream);
-
-                // Process the packet sequence
-                while (Connection.Connected && !StopRequested)
-                {
-                    // Check incoming buffer
-                    if (rawStream.DataAvailable)
-                    {
-                        ProcessData(rawStream);
-                    }
-                    else
-                    {
-                        // Poll the socket for data
-                        if (Connection.Client.Poll(100, SelectMode.SelectRead) && !rawStream.DataAvailable)
-                        {
-                            break;
-                        }
-
-                        // Sleep a bit to reduce load on CPU
-                        Thread.Sleep(10);
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                // Log exception
-                Log(ex.ToString());
-            }
-
-            try
-            {
-                // Disconnect the client
-                Connection.Close();
-            }
-            catch (Exception)
-            {
-                // Do nothing there
-            }
-
-            // Notify subscribers that this connection is closed
-            if (OnConnectionClosed != null)
-            {
-                OnConnectionClosed(this, null);
-            }
-        }
-
-        /// <summary>
-        /// Write a string to the log
-        /// </summary>
-        internal void Log(string text, params object[] args)
-        {
-            if (EventLog != null)
-            {
-                EventLog.WriteLine(text, args);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerParser.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.EndPoint/TDSServerParser.cs
deleted file mode 100644 (file)
index a637e6b..0000000
+++ /dev/null
@@ -1,147 +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;
-
-namespace Microsoft.SqlServer.TDS.EndPoint
-{
-    /// <summary>
-    /// Parser of the TDS packets on the client
-    /// </summary>
-    public class TDSServerParser : TDSParser
-    {
-        /// <summary>
-        /// Implementation that provides data to be delivered over the protocol
-        /// </summary>
-        private ITDSServer Server { get; set; }
-
-        /// <summary>
-        /// TDS server session
-        /// </summary>
-        private ITDSServerSession Session { get; set; }
-
-        /// <summary>
-        /// Communication from the client being received incrementally
-        /// </summary>
-        private TDSMessage MessageBeingReceived { get; set; }
-
-        /// <summary>
-        /// Server TDS parser initialization constructor
-        /// </summary>
-        public TDSServerParser(ITDSServer server, ITDSServerSession session, Stream stream) :
-            base(stream)
-        {
-            // Save TDS server
-            Server = server;
-
-            // Save session
-            Session = session;
-
-            // Configure TDS server
-            Transport.PacketSize = session.PacketSize;
-            Transport.OutgoingSessionID = (ushort)session.SessionID;
-        }
-
-        /// <summary>
-        /// Run one cycle of the parser to process incoming stream of data or dispatch outgoing data
-        /// </summary>
-        public void Run()
-        {
-            // Check if there's a message being inflated
-            if (MessageBeingReceived == null)
-            {
-                // Create a new message
-                MessageBeingReceived = new TDSMessage();
-            }
-
-            // Inflate the message using incoming stream
-            // This call will use only as much data is it needs and leave everything else on the stream
-            if (MessageBeingReceived.InflateClientRequest(Transport))
-            {
-                // Call into the server logics to process the message and generate the response
-                TDSMessageCollection responseMessages = null;
-
-                // Check the type of the packet
-                switch (MessageBeingReceived.MessageType)
-                {
-                    case TDSMessageType.PreLogin:
-                        {
-                            // Call into the subscriber to process the packet
-                            responseMessages = Server.OnPreLoginRequest(Session, MessageBeingReceived);
-                            break;
-                        }
-                    case TDSMessageType.TDS7Login:
-                        {
-                            // Call into the subscriber to process the packet
-                            responseMessages = Server.OnLogin7Request(Session, MessageBeingReceived);
-
-                            // Check if encryption needs to be turned off
-                            if (Session.Encryption == TDSEncryptionType.LoginOnly)
-                            {
-                                // Disable transport encryption
-                                DisableTransportEncryption();
-                            }
-
-                            break;
-                        }
-                    case TDSMessageType.SSPI:
-                        {
-                            // Call into the subscriber to process the packet
-                            responseMessages = Server.OnSSPIRequest(Session, MessageBeingReceived);
-                            break;
-                        }
-                    case TDSMessageType.SQLBatch:
-                        {
-                            // Call into the subscriber to process the packet
-                            responseMessages = Server.OnSQLBatchRequest(Session, MessageBeingReceived);
-                            break;
-                        }
-                    case TDSMessageType.Attention:
-                        {
-                            // Call into the subscriber to process the packet
-                            responseMessages = Server.OnAttention(Session, MessageBeingReceived);
-                            break;
-                        }
-                    case TDSMessageType.FederatedAuthenticationToken:
-                        {
-                            // Call into the subscriber to process the packet
-                            responseMessages = Server.OnFederatedAuthenticationTokenMessage(Session, MessageBeingReceived);
-                            break;
-                        }
-                    default:
-                        {
-                            // New code is needed to process this message
-                            throw new NotImplementedException(string.Format("Handler of TDS message \"{0}\" is not implemented", MessageBeingReceived.MessageType));
-                        }
-                }
-
-                // Check if TDS packet size changed
-                if (Session.PacketSize != Transport.PacketSize)
-                {
-                    // Update packet size
-                    Transport.PacketSize = Session.PacketSize;
-                }
-
-                // Send all messages to the client
-                responseMessages.Deflate(Transport);
-
-                // Check the type of message just sent
-                if (MessageBeingReceived.MessageType == TDSMessageType.PreLogin)
-                {
-                    // Check encryption settings on the session
-                    if (Session.Encryption == TDSEncryptionType.LoginOnly || Session.Encryption == TDSEncryptionType.Full)
-                    {
-                        // Enable server side encryption
-                        EnableServerTransportEncryption(Session.EncryptionCertificate);
-                    }
-                }
-
-                // Reset the current message because it's complete
-                // It would also trigger creation of the next message during the next cycle
-                MessageBeingReceived = null;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/ApplicationIntentFilterType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/ApplicationIntentFilterType.cs
deleted file mode 100644 (file)
index 4383f33..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Type of application intent filter
-    /// </summary>
-    public enum ApplicationIntentFilterType
-    {
-        /// <summary>
-        /// Filter out all requests and don't let anyone connect
-        /// </summary>
-        None,
-
-        /// <summary>
-        /// Allow read connections only
-        /// </summary>
-        ReadOnly,
-
-        /// <summary>
-        /// Don't filter anything and let everyone connect
-        /// </summary>
-        All,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/AuthenticatingTDSServer.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/AuthenticatingTDSServer.cs
deleted file mode 100644 (file)
index 63ea639..0000000
+++ /dev/null
@@ -1,221 +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.SqlServer.TDS.Done;
-using Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.Error;
-using Microsoft.SqlServer.TDS.Login7;
-
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// TDS Server that authenticates clients according to the requested parameters
-    /// </summary>
-    public class AuthenticatingTDSServer : GenericTDSServer
-    {
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public AuthenticatingTDSServer() :
-            this(new AuthenticatingTDSServerArguments())
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public AuthenticatingTDSServer(AuthenticatingTDSServerArguments arguments) :
-            base(arguments)
-        {
-        }
-
-        /// <summary>
-        /// Handler for login request
-        /// </summary>
-        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
-        {
-            // Inflate login7 request from the message
-            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;
-
-            // Check if arguments are of the authenticating TDS server
-            if (Arguments is AuthenticatingTDSServerArguments)
-            {
-                // Cast to authenticating TDS server arguments
-                AuthenticatingTDSServerArguments ServerArguments = Arguments as AuthenticatingTDSServerArguments;
-
-                // Check if we're still processing normal login
-                if (ServerArguments.ApplicationIntentFilter != ApplicationIntentFilterType.All)
-                {
-                    // Check filter
-                    if ((ServerArguments.ApplicationIntentFilter == ApplicationIntentFilterType.ReadOnly && loginRequest.TypeFlags.ReadOnlyIntent != TDSLogin7TypeFlagsReadOnlyIntent.ReadOnly)
-                        || (ServerArguments.ApplicationIntentFilter == ApplicationIntentFilterType.None))
-                    {
-                        // Log request to which we're about to send a failure
-                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);
-
-                        // Prepare ERROR token with the denial details
-                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application intent: " + loginRequest.TypeFlags.ReadOnlyIntent.ToString(), Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the error token into the response packet
-                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);
-
-                        // Prepare ERROR token for the final decision
-                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by application intent filter", Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the error token into the response packet
-                        responseMessage.Add(errorToken);
-
-                        // Create DONE token
-                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                        // Serialize DONE token into the response packet
-                        responseMessage.Add(doneToken);
-
-                        // Put a single message into the collection and return it
-                        return new TDSMessageCollection(responseMessage);
-                    }
-                }
-
-                // Check if we're still processing normal login and there's a filter to check
-                if (ServerArguments.ServerNameFilterType != ServerNameFilterType.None)
-                {
-                    // Check each algorithm
-                    if ((ServerArguments.ServerNameFilterType == ServerNameFilterType.Equals && string.Compare(ServerArguments.ServerNameFilter, loginRequest.ServerName, true) != 0)
-                        || (ServerArguments.ServerNameFilterType == ServerNameFilterType.StartsWith && !loginRequest.ServerName.StartsWith(ServerArguments.ServerNameFilter))
-                        || (ServerArguments.ServerNameFilterType == ServerNameFilterType.EndsWith && !loginRequest.ServerName.EndsWith(ServerArguments.ServerNameFilter))
-                        || (ServerArguments.ServerNameFilterType == ServerNameFilterType.Contains && !loginRequest.ServerName.Contains(ServerArguments.ServerNameFilter)))
-                    {
-                        // Log request to which we're about to send a failure
-                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);
-
-                        // Prepare ERROR token with the reason
-                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, string.Format("Received server name \"{0}\", expected \"{1}\" using \"{2}\" algorithm", loginRequest.ServerName, ServerArguments.ServerNameFilter, ServerArguments.ServerNameFilterType), Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the errorToken token into the response packet
-                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);
-
-                        // Prepare ERROR token with the final errorToken
-                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by server name filter", Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the errorToken token into the response packet
-                        responseMessage.Add(errorToken);
-
-                        // Create DONE token
-                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                        // Serialize DONE token into the response packet
-                        responseMessage.Add(doneToken);
-
-                        // Return only a single message with the collection
-                        return new TDSMessageCollection(responseMessage);
-                    }
-                }
-
-                // Check if packet size filter is applied
-                if (ServerArguments.PacketSizeFilter != null)
-                {
-                    // Check if requested packet size is the same as the filter specified
-                    if (loginRequest.PacketSize != ServerArguments.PacketSizeFilter.Value)
-                    {
-                        // Log request to which we're about to send a failure
-                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);
-
-                        // Prepare ERROR token with the reason
-                        TDSErrorToken errorToken = new TDSErrorToken(1919, 1, 14, string.Format("Received packet size \"{0}\", expected \"{1}\"", loginRequest.PacketSize, ServerArguments.PacketSizeFilter.Value), Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the errorToken token into the response packet
-                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);
-
-                        // Prepare ERROR token with the final errorToken
-                        errorToken = new TDSErrorToken(1919, 1, 14, "Connection is denied by packet size filter", Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the errorToken token into the response packet
-                        responseMessage.Add(errorToken);
-
-                        // Create DONE token
-                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                        // Serialize DONE token into the response packet
-                        responseMessage.Add(doneToken);
-
-                        // Return only a single message with the collection
-                        return new TDSMessageCollection(responseMessage);
-                    }
-                }
-
-                // If we have an application name filter
-                if (ServerArguments.ApplicationNameFilter != null)
-                {
-                    // If we are supposed to block this connection attempt
-                    if (loginRequest.ApplicationName.Equals(ServerArguments.ApplicationNameFilter, System.StringComparison.OrdinalIgnoreCase))
-                    {
-                        // Log request to which we're about to send a failure
-                        TDSUtilities.Log(Arguments.Log, "Request", loginRequest);
-
-                        // Prepare ERROR token with the denial details
-                        TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application name: " + loginRequest.ApplicationName, Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the error token into the response packet
-                        TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);
-
-                        // Prepare ERROR token for the final decision
-                        errorToken = new TDSErrorToken(18456, 1, 14, "Connection is denied by application name filter", Arguments.ServerName);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                        // Serialize the error token into the response packet
-                        responseMessage.Add(errorToken);
-
-                        // Create DONE token
-                        TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                        // Log response
-                        TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                        // Serialize DONE token into the response packet
-                        responseMessage.Add(doneToken);
-
-                        // Put a single message into the collection and return it
-                        return new TDSMessageCollection(responseMessage);
-                    }
-                }
-            }
-
-            // Return login response from the base class
-            return base.OnLogin7Request(session, request);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/AuthenticatingTDSServerArguments.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/AuthenticatingTDSServerArguments.cs
deleted file mode 100644 (file)
index dcb812a..0000000
+++ /dev/null
@@ -1,49 +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.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Arguments for authenticating TDS Server
-    /// </summary>
-    public class AuthenticatingTDSServerArguments : TDSServerArguments
-    {
-        /// <summary>
-        /// Type of the application intent filter
-        /// </summary>
-        public ApplicationIntentFilterType ApplicationIntentFilter { get; set; }
-
-        /// <summary>
-        /// Filter for server name
-        /// </summary>
-        public string ServerNameFilter { get; set; }
-
-        /// <summary>
-        /// Type of the filtering algorithm to use
-        /// </summary>
-        public ServerNameFilterType ServerNameFilterType { get; set; }
-
-        /// <summary>
-        /// TDS packet size filtering
-        /// </summary>
-        public ushort? PacketSizeFilter { get; set; }
-
-        /// <summary>
-        /// Filter for application name
-        /// </summary>
-        public string ApplicationNameFilter { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public AuthenticatingTDSServerArguments()
-        {
-            // Allow everyone to connect
-            ApplicationIntentFilter = ApplicationIntentFilterType.All;
-
-            // By default we don't turn on server name filter
-            ServerNameFilterType = Servers.ServerNameFilterType.None;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/Configurations.props b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/Configurations.props
deleted file mode 100644 (file)
index 69f0b7d..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0-Unix;
-      netstandard2.0-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/DateFormatString.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/DateFormatString.cs
deleted file mode 100644 (file)
index ef461a0..0000000
+++ /dev/null
@@ -1,94 +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;
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Class that converts date format from string to enumeration
-    /// </summary>
-    public static class DateFormatString
-    {
-        private const string DayMonthYear = "dmy";
-        private const string DayYearMonth = "dym";
-        private const string MonthDayYear = "mdy";
-        private const string MonthYearDay = "myd";
-        private const string YearDayMonth = "ydm";
-        private const string YearMonthDay = "ymd";
-
-        /// <summary>
-        /// Convert a language to enumeration
-        /// </summary>
-        public static DateFormatType ToEnum(string value)
-        {
-            // Check every langauge
-            if (string.Compare(value, DayMonthYear, true) == 0)
-            {
-                return DateFormatType.DayMonthYear;
-            }
-            else if (string.Compare(value, DayYearMonth, true) == 0)
-            {
-                return DateFormatType.DayYearMonth;
-            }
-            else if (string.Compare(value, MonthDayYear, true) == 0)
-            {
-                return DateFormatType.MonthDayYear;
-            }
-            else if (string.Compare(value, MonthYearDay, true) == 0)
-            {
-                return DateFormatType.MonthYearDay;
-            }
-            else if (string.Compare(value, YearDayMonth, true) == 0)
-            {
-                return DateFormatType.YearDayMonth;
-            }
-            else if (string.Compare(value, YearMonthDay, true) == 0)
-            {
-                return DateFormatType.YearMonthDay;
-            }
-
-            // Unknown value
-            throw new Exception("Unrecognized date format string \"" + value + "\"");
-        }
-
-        /// <summary>
-        /// Convert enumeration to string
-        /// </summary>
-        public static string ToString(DateFormatType value)
-        {
-            // Switch through the langauges
-            switch (value)
-            {
-                case DateFormatType.DayMonthYear:
-                    {
-                        return DayMonthYear;
-                    }
-                case DateFormatType.DayYearMonth:
-                    {
-                        return DayYearMonth;
-                    }
-                case DateFormatType.MonthDayYear:
-                    {
-                        return MonthDayYear;
-                    }
-                case DateFormatType.MonthYearDay:
-                    {
-                        return MonthYearDay;
-                    }
-                case DateFormatType.YearDayMonth:
-                    {
-                        return YearDayMonth;
-                    }
-                case DateFormatType.YearMonthDay:
-                    {
-                        return YearMonthDay;
-                    }
-            }
-
-            // Unknown value
-            throw new Exception("Unrecognized date format type \"" + value.ToString() + "\"");
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSScenarioType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSScenarioType.cs
deleted file mode 100644 (file)
index 11baa17..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    public enum FederatedAuthenticationNegativeTDSScenarioType : int
-    {
-        /// <summary>
-        /// Valid Scenario. Do not perform negative activity.
-        /// </summary>
-        ValidScenario,
-
-        /// <summary>
-        /// Nonce is missing from LOGIN7 response in FedAuth's FEATUREEXTACK
-        /// </summary>
-        NonceMissingInFedAuthFEATUREXTACK,
-
-        /// <summary>
-        /// Nonce is missing from PRELOGIN response in FedAuth
-        /// </summary>
-        NonceMissingInFedAuthPreLogin,
-
-        /// <summary>
-        /// FedAuth is missing from FEATUREEXTACK Login response when it is expected
-        /// </summary>
-        FedAuthMissingInFEATUREEXTACK,
-
-        /// <summary>
-        /// Invalid B_FEDAUTHREQUIRED response
-        /// </summary>
-        InvalidB_FEDAUTHREQUIREDResponse,
-
-        /// <summary>
-        /// Signature is missing from LOGIN7 response in FedAuth's FEATUREEXTACK
-        /// </summary>
-        SignatureMissingInFedAuthFEATUREXTACK,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSServer.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSServer.cs
deleted file mode 100644 (file)
index 3cf144a..0000000
+++ /dev/null
@@ -1,148 +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.Linq;
-using Microsoft.SqlServer.TDS.PreLogin;
-using Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// TDS Server that generates invalid TDS scenarios according to the requested parameters
-    /// </summary>
-    public class FederatedAuthenticationNegativeTDSServer : GenericTDSServer
-    {
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public FederatedAuthenticationNegativeTDSServer() :
-            this(new FederatedAuthenticationNegativeTDSServerArguments())
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public FederatedAuthenticationNegativeTDSServer(FederatedAuthenticationNegativeTDSServerArguments arguments) :
-            base(arguments)
-        {
-        }
-
-        /// <summary>
-        /// Handler for login request
-        /// </summary>
-        public override TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
-        {
-            // Get the collection from a valid On PreLogin Request
-            TDSMessageCollection preLoginCollection = base.OnPreLoginRequest(session, request);
-
-            // Check if arguments are of the Federated Authentication server
-            if (Arguments is FederatedAuthenticationNegativeTDSServerArguments)
-            {
-                // Cast to federated authentication server arguments
-                FederatedAuthenticationNegativeTDSServerArguments ServerArguments = Arguments as FederatedAuthenticationNegativeTDSServerArguments;
-
-                // Find the is token carrying on TDSPreLoginToken
-                TDSPreLoginToken preLoginToken = preLoginCollection.Find(message => message.Exists(packetToken => packetToken is TDSPreLoginToken)).
-                    Find(packetToken => packetToken is TDSPreLoginToken) as TDSPreLoginToken;
-
-                switch (ServerArguments.Scenario)
-                {
-                    case FederatedAuthenticationNegativeTDSScenarioType.NonceMissingInFedAuthPreLogin:
-                        {
-                            // If we have the prelogin token
-                            if (preLoginToken != null && preLoginToken.Nonce != null)
-                            {
-                                // Nullify the nonce from the Token
-                                preLoginToken.Nonce = null;
-                            }
-
-                            break;
-                        }
-
-                    case FederatedAuthenticationNegativeTDSScenarioType.InvalidB_FEDAUTHREQUIREDResponse:
-                        {
-                            // If we have the prelogin token
-                            if (preLoginToken != null)
-                            {
-                                // Set an illegal value for B_FEDAUTHREQURED
-                                preLoginToken.FedAuthRequired = TdsPreLoginFedAuthRequiredOption.Illegal;
-                            }
-
-                            break;
-                        }
-                }
-            }
-
-            // Return the collection
-            return preLoginCollection;
-        }
-
-        /// <summary>
-        /// Handler for login request
-        /// </summary>
-        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
-        {
-            // Get the collection from the normal behavior On Login7 Request
-            TDSMessageCollection login7Collection = base.OnLogin7Request(session, request);
-
-            // Check if arguments are of the Federated Authentication server
-            if (Arguments is FederatedAuthenticationNegativeTDSServerArguments)
-            {
-                // Cast to federated authentication server arguments
-                FederatedAuthenticationNegativeTDSServerArguments ServerArguments = Arguments as FederatedAuthenticationNegativeTDSServerArguments;
-
-                // Get the Federated Authentication ExtAck from Login 7
-                TDSFeatureExtAckFederatedAuthenticationOption fedAutExtAct = GetFeatureExtAckFederatedAuthenticationOptionFromLogin7(login7Collection);
-
-                // If not found, return the base collection intact
-                if (fedAutExtAct != null)
-                {
-                    switch (ServerArguments.Scenario)
-                    {
-                        case FederatedAuthenticationNegativeTDSScenarioType.NonceMissingInFedAuthFEATUREXTACK:
-                            {
-                                // Delete the nonce from the Token
-                                fedAutExtAct.ClientNonce = null;
-
-                                break;
-                            }
-                        case FederatedAuthenticationNegativeTDSScenarioType.FedAuthMissingInFEATUREEXTACK:
-                            {
-                                // Remove the Fed Auth Ext Ack from the options list in the FeatureExtAckToken
-                                GetFeatureExtAckTokenFromLogin7(login7Collection).Options.Remove(fedAutExtAct);
-
-                                break;
-                            }
-                        case FederatedAuthenticationNegativeTDSScenarioType.SignatureMissingInFedAuthFEATUREXTACK:
-                            {
-                                // Delete the signature from the Token
-                                fedAutExtAct.Signature = null;
-
-                                break;
-                            }
-                    }
-                }
-            }
-
-            // Return the collection
-            return login7Collection;
-        }
-
-        private TDSFeatureExtAckToken GetFeatureExtAckTokenFromLogin7(TDSMessageCollection login7Collection)
-        {
-            // Find the is token carrying on TDSFeatureExtAckToken
-            return login7Collection.Find(m => m.Exists(p => p is TDSFeatureExtAckToken)).
-                Find(t => t is TDSFeatureExtAckToken) as TDSFeatureExtAckToken;
-        }
-
-        private TDSFeatureExtAckFederatedAuthenticationOption GetFeatureExtAckFederatedAuthenticationOptionFromLogin7(TDSMessageCollection login7Collection)
-        {
-            // Get the Fed Auth Ext Ack from the list of options in the feature ExtAck
-            return GetFeatureExtAckTokenFromLogin7(login7Collection).Options.
-                Where(o => o is TDSFeatureExtAckFederatedAuthenticationOption).FirstOrDefault() as TDSFeatureExtAckFederatedAuthenticationOption;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSServerArguments.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/FederatedAuthenticationNegativeTDSServerArguments.cs
deleted file mode 100644 (file)
index 67143d6..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Arguments for Fed Auth Negative TDS Server
-    /// </summary>
-    public class FederatedAuthenticationNegativeTDSServerArguments : TDSServerArguments
-    {
-        /// <summary>
-        /// Type of the Fed Auth Negative TDS Server
-        /// </summary>
-        public FederatedAuthenticationNegativeTDSScenarioType Scenario { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public FederatedAuthenticationNegativeTDSServerArguments()
-        {
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/GenericTDSServer.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/GenericTDSServer.cs
deleted file mode 100644 (file)
index fb97243..0000000
+++ /dev/null
@@ -1,772 +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;
-using System.Threading;
-using System.Security.Cryptography;
-
-using Microsoft.SqlServer.TDS.Done;
-using Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.EndPoint.SSPI;
-using Microsoft.SqlServer.TDS.EndPoint.FederatedAuthentication;
-using Microsoft.SqlServer.TDS.EnvChange;
-using Microsoft.SqlServer.TDS.Error;
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-using Microsoft.SqlServer.TDS.Info;
-using Microsoft.SqlServer.TDS.Login7;
-using Microsoft.SqlServer.TDS.LoginAck;
-using Microsoft.SqlServer.TDS.PreLogin;
-using Microsoft.SqlServer.TDS.SSPI;
-using Microsoft.SqlServer.TDS.Authentication;
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Generic TDS server without specialization
-    /// </summary>
-    public class GenericTDSServer : ITDSServer
-    {
-        /// <summary>
-        /// Session counter
-        /// </summary>
-        private int _sessionCount = 0;
-
-        /// <summary>
-        /// Server configuration
-        /// </summary>
-        protected TDSServerArguments Arguments { get; set; }
-
-        /// <summary>
-        /// Query engine instance
-        /// </summary>
-        protected QueryEngine Engine { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public GenericTDSServer() :
-            this(new TDSServerArguments())
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public GenericTDSServer(TDSServerArguments arguments) :
-            this(arguments, new QueryEngine(arguments))
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public GenericTDSServer(TDSServerArguments arguments, QueryEngine queryEngine)
-        {
-            // Save arguments
-            Arguments = arguments;
-
-            // Save "relational" query engine
-            Engine = queryEngine;
-
-            // Configure log for the query engine
-            Engine.Log = Arguments.Log;
-        }
-
-        /// <summary>
-        /// Create a new session on the server
-        /// </summary>
-        /// <returns>A new instance of the session</returns>
-        public virtual ITDSServerSession OpenSession()
-        {
-            // Atomically increment the session counter
-            Interlocked.Increment(ref _sessionCount);
-
-            // Create a new session
-            GenericTDSServerSession session = new GenericTDSServerSession(this, (uint)_sessionCount);
-
-            // Use configured encryption certificate
-            session.EncryptionCertificate = Arguments.EncryptionCertificate;
-
-            return session;
-        }
-
-        /// <summary>
-        /// Notify server of the session termination
-        /// </summary>
-        public virtual void CloseSession(ITDSServerSession session)
-        {
-            // Do nothing
-        }
-
-        /// <summary>
-        /// Handler for pre-login request
-        /// </summary>
-        public virtual TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
-        {
-            // Inflate pre-login request from the message
-            TDSPreLoginToken preLoginRequest = request[0] as TDSPreLoginToken;
-
-            // Log request
-            TDSUtilities.Log(Arguments.Log, "Request", preLoginRequest);
-
-            // Generate server response for encryption
-            TDSPreLoginTokenEncryptionType serverResponse = TDSUtilities.GetEncryptionResponse(preLoginRequest.Encryption, Arguments.Encryption);
-
-            // Update client state with encryption resolution
-            session.Encryption = TDSUtilities.ResolveEncryption(preLoginRequest.Encryption, serverResponse);
-
-            // Create TDS prelogin packet
-            TDSPreLoginToken preLoginToken = new TDSPreLoginToken(Arguments.ServerVersion, serverResponse, false); // TDS server doesn't support MARS
-
-            // Cache the recieved Nonce into the session
-            (session as GenericTDSServerSession).ClientNonce = preLoginRequest.Nonce;
-
-            // Check if the server has been started up as requiring FedAuth when choosing between SSPI and FedAuth
-            if (Arguments.FedAuthRequiredPreLoginOption == TdsPreLoginFedAuthRequiredOption.FedAuthRequired)
-            {
-                if (preLoginRequest.FedAuthRequired == TdsPreLoginFedAuthRequiredOption.FedAuthRequired)
-                {
-                    // Set the FedAuthRequired option
-                    preLoginToken.FedAuthRequired = TdsPreLoginFedAuthRequiredOption.FedAuthRequired;
-                }
-
-                // Keep the federated authentication required flag in the server session
-                (session as GenericTDSServerSession).FedAuthRequiredPreLoginServerResponse = preLoginToken.FedAuthRequired;
-
-                if (preLoginRequest.Nonce != null)
-                {
-                    // Generate Server Nonce
-                    preLoginToken.Nonce = _GenerateRandomBytes(32);
-                }
-            }
-
-            // Cache the server Nonce in a session
-            (session as GenericTDSServerSession).ServerNonce = preLoginToken.Nonce;
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", preLoginToken);
-
-            // Reset authentication information
-            session.SQLUserID = null;
-            session.NTUserAuthenticationContext = null;
-
-            // Respond with a single message that contains only one token
-            return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, preLoginToken));
-        }
-
-        /// <summary>
-        /// Handler for login request
-        /// </summary>
-        public virtual TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
-        {
-            // Inflate login7 request from the message
-            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;
-
-            // Log request
-            TDSUtilities.Log(Arguments.Log, "Request", loginRequest);
-
-            // Update server context
-            session.Database = string.IsNullOrEmpty(loginRequest.Database) ? "master" : loginRequest.Database;
-
-            // Resolve TDS version
-            session.TDSVersion = TDSVersion.Resolve(TDSVersion.GetTDSVersion(Arguments.ServerVersion), loginRequest.TDSVersion);
-
-            // Check for the TDS version
-            TDSMessageCollection collection = CheckTDSVersion(session);
-
-            // Check if any errors are posted
-            if (collection != null)
-            {
-                // Version check needs to send own message hence we can't proceed
-                return collection;
-            }
-
-            // Indicates federated authentication
-            bool bIsFedAuthConnection = false;
-
-            // Federated authentication option to be used later
-            TDSLogin7FedAuthOptionToken federatedAuthenticationOption = null;
-
-            // Check if feature extension block is available
-            if (loginRequest.FeatureExt != null)
-            {
-                // Go over the feature extension data
-                foreach (TDSLogin7FeatureOptionToken option in loginRequest.FeatureExt)
-                {
-                    // Check option type
-                    switch (option.FeatureID)
-                    {
-                        case TDSFeatureID.SessionRecovery:
-                            {
-                                // Enable session recovery
-                                session.IsSessionRecoveryEnabled = true;
-
-                                // Cast to session state options
-                                TDSLogin7SessionRecoveryOptionToken sessionStateOption = option as TDSLogin7SessionRecoveryOptionToken;
-
-                                // Inflate session state
-                                (session as GenericTDSServerSession).Inflate(sessionStateOption.Initial, sessionStateOption.Current);
-
-                                break;
-                            }
-                        case TDSFeatureID.FederatedAuthentication:
-                            {
-                                // Cast to federated authentication option
-                                federatedAuthenticationOption = option as TDSLogin7FedAuthOptionToken;
-
-                                // Mark authentication as federated
-                                bIsFedAuthConnection = true;
-
-                                // Validate federated authentication option
-                                collection = CheckFederatedAuthenticationOption(session, option as TDSLogin7FedAuthOptionToken);
-
-                                if (collection != null)
-                                {
-                                    // Version error happened.
-                                    return collection;
-                                }
-
-                                // Save the fed auth library to be used
-                                (session as GenericTDSServerSession).FederatedAuthenticationLibrary = federatedAuthenticationOption.Library;
-
-                                break;
-                            }
-                        default:
-                            {
-                                // Do nothing
-                                break;
-                            }
-                    }
-                }
-            }
-
-            // Check if SSPI authentication is requested
-            if (loginRequest.OptionalFlags2.IntegratedSecurity == TDSLogin7OptionalFlags2IntSecurity.On)
-            {
-                // Delegate to SSPI authentication
-                return ContinueSSPIAuthentication(session, loginRequest.SSPI);
-            }
-
-            // If it is not a FedAuth connection or the server has been started up as not supporting FedAuth, just ignore the FeatureExtension
-            // Yes unfortunately for the fake server, supporting FedAuth = Requiring FedAuth
-            if (!bIsFedAuthConnection
-                || Arguments.FedAuthRequiredPreLoginOption == TdsPreLoginFedAuthRequiredOption.FedAuthNotRequired)
-            {
-                // We use SQL authentication
-                session.SQLUserID = loginRequest.UserID;
-
-                // Process with the SQL login.
-                return OnSqlAuthenticationCompleted(session);
-            }
-            else
-            {
-                // Fedauth feature extension is present and server has been started up as Requiring (or Supporting) FedAuth
-                if (federatedAuthenticationOption.IsRequestingAuthenticationInfo)
-                {
-                    // Must provide client with more info before completing authentication
-                    return OnFederatedAuthenticationInfoRequest(session);
-                }
-                else
-                {
-                    return OnFederatedAuthenticationCompleted(session, federatedAuthenticationOption.Token);
-                }
-            }
-        }
-
-        public virtual TDSMessageCollection OnFederatedAuthenticationTokenMessage(ITDSServerSession session, TDSMessage message)
-        {
-            // Get the FedAuthToken
-            TDSFedAuthToken fedauthToken = message[0] as TDSFedAuthToken;
-
-            // Log
-            TDSUtilities.Log(Arguments.Log, "Request", fedauthToken);
-
-            return OnFederatedAuthenticationCompleted(session, fedauthToken.Token);
-        }
-
-        /// <summary>
-        /// Handler for SSPI request
-        /// </summary>
-        public virtual TDSMessageCollection OnSSPIRequest(ITDSServerSession session, TDSMessage request)
-        {
-            // Get the SSPI token
-            TDSSSPIClientToken sspiRequest = request[0] as TDSSSPIClientToken;
-
-            // Log request
-            TDSUtilities.Log(Arguments.Log, "Request", sspiRequest.Payload);
-
-            // Delegate to SSPI routine
-            return ContinueSSPIAuthentication(session, sspiRequest.Payload);
-        }
-
-        /// <summary>
-        /// It is called when SQL batch request arrives
-        /// </summary>
-        public virtual TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session, TDSMessage message)
-        {
-            // Delegate to the query engine
-            TDSMessageCollection responseMessage = Engine.ExecuteBatch(session, message);
-
-            // Check if session packet size is different than the engine packet size
-            if (session.PacketSize != Arguments.PacketSize)
-            {
-                // Get the first message
-                TDSMessage firstMessage = responseMessage[0];
-
-                // Find DONE token in it
-                int indexOfDone = firstMessage.IndexOf(firstMessage.Where(t => t is TDSDoneToken).First());
-
-                // Create new packet size environment change token
-                TDSEnvChangeToken envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.PacketSize, Arguments.PacketSize.ToString(), session.PacketSize.ToString());
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", envChange);
-
-                // Insert env change before done token
-                firstMessage.Insert(indexOfDone, envChange);
-
-                // Update session with the new packet size
-                session.PacketSize = (uint)Arguments.PacketSize;
-            }
-
-            return responseMessage;
-        }
-
-        /// <summary>
-        /// It is called when attention arrives
-        /// </summary>
-        public virtual TDSMessageCollection OnAttention(ITDSServerSession session, TDSMessage message)
-        {
-            // Delegate into the query engine
-            return Engine.ExecuteAttention(session, message);
-        }
-
-        /// <summary>
-        /// Advances one step in SSPI authentication sequence
-        /// </summary>
-        protected virtual TDSMessageCollection ContinueSSPIAuthentication(ITDSServerSession session, byte[] payload)
-        {
-            // Response to send to the client
-            SSPIResponse response;
-
-            try
-            {
-                // Check if we have an SSPI context
-                if (session.NTUserAuthenticationContext == null)
-                {
-                    // This is the first step so we need to create a server context and initialize it
-                    session.NTUserAuthenticationContext = SSPIContext.CreateServer();
-
-                    // Run the first step of authentication
-                    response = session.NTUserAuthenticationContext.StartServerAuthentication(payload);
-                }
-                else
-                {
-                    // Process SSPI request from the client
-                    response = session.NTUserAuthenticationContext.ContinueServerAuthentication(payload);
-                }
-            }
-            catch (Exception e)
-            {
-                // Prepare ERROR token with the reason
-                TDSErrorToken errorToken = new TDSErrorToken(12345, 1, 15, "Failed to accept security SSPI context", Arguments.ServerName);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                // Serialize the error token into the response packet
-                TDSMessage responseErrorMessage = new TDSMessage(TDSMessageType.Response, errorToken);
-
-                // Prepare ERROR token with the final errorToken
-                errorToken = new TDSErrorToken(12345, 1, 15, e.Message, Arguments.ServerName);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                // Serialize the error token into the response packet
-                responseErrorMessage.Add(errorToken);
-
-                // Create DONE token
-                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                // Serialize DONE token into the response packet
-                responseErrorMessage.Add(doneToken);
-
-                // Respond with a single message
-                return new TDSMessageCollection(responseErrorMessage);
-            }
-
-            // Message collection to respond with
-            TDSMessageCollection responseMessages = new TDSMessageCollection();
-
-            // Check if there's a response
-            if (response != null)
-            {
-                // Check if there's a payload
-                if (response.Payload != null)
-                {
-                    // Create SSPI token
-                    TDSSSPIToken sspiToken = new TDSSSPIToken(response.Payload);
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", sspiToken);
-
-                    // Prepare response message with a single response token
-                    responseMessages.Add(new TDSMessage(TDSMessageType.Response, sspiToken));
-
-                    // Check if we can complete login
-                    if (!response.IsFinal)
-                    {
-                        // Send the message to the client
-                        return responseMessages;
-                    }
-                }
-            }
-
-            // Reset SQL user identifier since we're using NT authentication
-            session.SQLUserID = null;
-
-            // Append successfully authentication response
-            responseMessages.AddRange(OnAuthenticationCompleted(session));
-
-            // Return the message with SSPI token
-            return responseMessages;
-        }
-
-        protected virtual TDSMessageCollection OnFederatedAuthenticationInfoRequest(ITDSServerSession session)
-        {
-            TDSFedAuthInfoToken infoToken = new TDSFedAuthInfoToken();
-
-            // Make fake info options
-            TDSFedAuthInfoOptionSPN spn = new TDSFedAuthInfoOptionSPN(Arguments.ServerPrincipalName);
-            TDSFedAuthInfoOptionSTSURL stsurl = new TDSFedAuthInfoOptionSTSURL(Arguments.StsUrl);
-            infoToken.Options.Add(0, spn);
-            infoToken.Options.Add(1, stsurl);
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", spn);
-            TDSUtilities.Log(Arguments.Log, "Response", stsurl);
-
-            TDSMessage infoMessage = new TDSMessage(TDSMessageType.FederatedAuthenticationInfo, infoToken);
-            return new TDSMessageCollection(infoMessage);
-        }
-
-        /// <summary>
-        /// Called by OnLogin7Request when client is using SQL auth. Overridden by subclasses to easily detect when SQL auth is used.
-        /// </summary>
-        protected virtual TDSMessageCollection OnSqlAuthenticationCompleted(ITDSServerSession session)
-        {
-            return OnAuthenticationCompleted(session);
-        }
-
-        protected virtual TDSMessageCollection OnAuthenticationCompleted(ITDSServerSession session)
-        {
-            // Create new database environment change token
-            TDSEnvChangeToken envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.Database, session.Database, "master");
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", envChange);
-
-            // Serialize the login token into the response packet
-            TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, envChange);
-
-            // Create information token on the change
-            TDSInfoToken infoToken = new TDSInfoToken(5701, 2, 0, string.Format("Changed database context to '{0}'", envChange.NewValue), Arguments.ServerName);
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", infoToken);
-
-            // Serialize the login token into the response packet
-            responseMessage.Add(infoToken);
-
-            // Create new collation change token
-            envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.SQLCollation, (session as GenericTDSServerSession).Collation);
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", envChange);
-
-            // Serialize the login token into the response packet
-            responseMessage.Add(envChange);
-
-            // Create new language change token
-            envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.Language, LanguageString.ToString((session as GenericTDSServerSession).Language));
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", envChange);
-
-            // Serialize the login token into the response packet
-            responseMessage.Add(envChange);
-
-            // Create information token on the change
-            infoToken = new TDSInfoToken(5703, 1, 0, string.Format("Changed language setting to {0}", envChange.NewValue), Arguments.ServerName);
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", infoToken);
-
-            // Serialize the login token into the response packet
-            responseMessage.Add(infoToken);
-
-            // Create new packet size environment change token
-            envChange = new TDSEnvChangeToken(TDSEnvChangeTokenType.PacketSize, Arguments.PacketSize.ToString(), Arguments.PacketSize.ToString());
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", envChange);
-
-            // Serialize the login token into the response packet
-            responseMessage.Add(envChange);
-
-            // Update session packet size
-            session.PacketSize = (uint)Arguments.PacketSize;
-
-            // Create login acknowledgement packet
-            TDSLoginAckToken loginResponseToken = new TDSLoginAckToken(Arguments.ServerVersion, session.TDSVersion, TDSLogin7TypeFlagsSQL.SQL, "Microsoft SQL Server");  // Otherwise SNAC yields E_FAIL
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", loginResponseToken);
-
-            // Serialize the login token into the response packet
-            responseMessage.Add(loginResponseToken);
-
-            // Check if session recovery is enabled
-            if (session.IsSessionRecoveryEnabled)
-            {
-                // Create Feature extension Ack token
-                TDSFeatureExtAckToken featureExtActToken = new TDSFeatureExtAckToken(new TDSFeatureExtAckSessionStateOption((session as GenericTDSServerSession).Deflate()));
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", featureExtActToken);
-
-                // Serialize feature extnesion token into the response
-                responseMessage.Add(featureExtActToken);
-            }
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final);
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-            // Serialize DONE token into the response packet
-            responseMessage.Add(doneToken);
-
-            // Wrap a single message in a collection
-            return new TDSMessageCollection(responseMessage);
-        }
-
-        /// <summary>
-        /// Complete the Federated Login
-        /// </summary>
-        /// <param name="session">Server session</param>
-        /// <returns>Federated Login message collection</returns>
-        protected virtual TDSMessageCollection OnFederatedAuthenticationCompleted(ITDSServerSession session, byte[] ticket)
-        {
-            // Delegate to successful authentication routine
-            TDSMessageCollection responseMessageCollection = OnAuthenticationCompleted(session);
-
-            // Get the last message
-            TDSMessage targetMessage = responseMessageCollection.Last();
-
-            IFederatedAuthenticationTicket decryptedTicket = null;
-
-            try
-            {
-                // Get the Federated Authentication ticket using RPS
-                decryptedTicket = FederatedAuthenticationTicketService.DecryptTicket((session as GenericTDSServerSession).FederatedAuthenticationLibrary, ticket);
-
-                if (decryptedTicket is RpsTicket)
-                {
-                    TDSUtilities.Log(Arguments.Log, "RPS ticket session key: ", (decryptedTicket as RpsTicket).sessionKey);
-                }
-                else if (decryptedTicket is JwtTicket)
-                {
-                    TDSUtilities.Log(Arguments.Log, "JWT Ticket Received", null);
-                }
-            }
-            catch (Exception ex)
-            {
-                // Prepare ERROR token
-                TDSErrorToken errorToken = new TDSErrorToken(54879, 1, 20, "Authentication error in Federated Authentication Ticket Service: " + ex.Message, Arguments.ServerName);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                // Create DONE token
-                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                // Return the message and stop processing request
-                return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, errorToken, doneToken));
-            }
-
-            // Create federated authentication extension option
-            TDSFeatureExtAckFederatedAuthenticationOption federatedAuthenticationOption;
-            if ((session as GenericTDSServerSession).FederatedAuthenticationLibrary == TDSFedAuthLibraryType.ADAL)
-            {
-                // For the time being, fake fedauth tokens are used for ADAL, so decryptedTicket is null.
-                federatedAuthenticationOption =
-                    new TDSFeatureExtAckFederatedAuthenticationOption((session as GenericTDSServerSession).ClientNonce, null);
-            }
-            else
-            {
-                federatedAuthenticationOption =
-                    new TDSFeatureExtAckFederatedAuthenticationOption((session as GenericTDSServerSession).ClientNonce,
-                                                                       decryptedTicket.GetSignature((session as GenericTDSServerSession).ClientNonce));
-            }
-
-            // Look for feature extension token
-            TDSFeatureExtAckToken featureExtActToken = (TDSFeatureExtAckToken)targetMessage.Where(t => t is TDSFeatureExtAckToken).FirstOrDefault();
-
-            // Check if response already contains federated authentication
-            if (featureExtActToken == null)
-            {
-                // Create Feature extension Ack token
-                featureExtActToken = new TDSFeatureExtAckToken(federatedAuthenticationOption);
-
-                // Serialize feature extension token into the response
-                // The last token is Done token, so we should put feautureextack token before done token
-                targetMessage.Insert(targetMessage.Count - 1, featureExtActToken);
-            }
-            else
-            {
-                // Update
-                featureExtActToken.Options.Add(federatedAuthenticationOption);
-            }
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", federatedAuthenticationOption);
-
-            // Wrap a message with a collection
-            return responseMessageCollection;
-        }
-
-        /// <summary>
-        /// Ensure that federated authentication option is valid
-        /// </summary>
-        protected virtual TDSMessageCollection CheckFederatedAuthenticationOption(ITDSServerSession session, TDSLogin7FedAuthOptionToken federatedAuthenticationOption)
-        {
-            // Check if server's prelogin response for FedAuthRequired prelogin option is echoed back correctly in FedAuth Feature Extenion Echo
-            if (federatedAuthenticationOption.Echo != (session as GenericTDSServerSession).FedAuthRequiredPreLoginServerResponse)
-            {
-                // Create Error message
-                string message =
-                    string.Format("FEDAUTHREQUIRED option in the prelogin response is not echoed back correctly: in prelogin response, it is {0} and in login, it is {1}: ",
-                    (session as GenericTDSServerSession).FedAuthRequiredPreLoginServerResponse,
-                    federatedAuthenticationOption.Echo);
-
-                // Create errorToken token
-                TDSErrorToken errorToken = new TDSErrorToken(3456, 34, 23, message);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                // Create DONE token
-                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                // Build a collection with a single message of two tokens
-                return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, errorToken, doneToken));
-            }
-
-            // Check if the nonce exists
-            if ((federatedAuthenticationOption.Nonce == null && federatedAuthenticationOption.Library == TDSFedAuthLibraryType.IDCRL)
-                || !AreEqual((session as GenericTDSServerSession).ServerNonce, federatedAuthenticationOption.Nonce))
-            {
-                // Error message
-                string message = string.Format("Unexpected NONCEOPT specified in the Federated authentication feature extension");
-
-                // Create errorToken token
-                TDSErrorToken errorToken = new TDSErrorToken(5672, 32, 87, message);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                // Create DONE token
-                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                // Log response
-                TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                // Build a collection with a single message of two tokens
-                return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, errorToken, doneToken));
-            }
-
-            // We're good
-            return null;
-        }
-
-        /// <summary>
-        /// Checks the TDS version
-        /// </summary>
-        /// <param name="session">Server session</param>
-        /// <returns>Null if the TDS version is supported, errorToken message otherwise</returns>
-        protected virtual TDSMessageCollection CheckTDSVersion(ITDSServerSession session)
-        {
-            // Check if version is supported
-            if (TDSVersion.IsSupported(session.TDSVersion))
-            {
-                return null;
-            }
-
-            // Prepare ERROR token
-            TDSErrorToken errorToken = new TDSErrorToken(12345, 1, 16, "Unsupported TDS client version", Arguments.ServerName);
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-            // Log response
-            TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-            // Wrap with message collection
-            return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, errorToken, doneToken));
-        }
-
-        /// <summary>
-        /// Generates random bytes
-        /// </summary>
-        /// <param name="count">The number of bytes to be generated.</param>
-        /// <returns>Generated random bytes.</returns>
-        private byte[] _GenerateRandomBytes(int count)
-        {
-            byte[] randomBytes = new byte[count];
-
-            RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
-            // Generate bytes
-            gen.GetBytes(randomBytes);
-
-            return randomBytes;
-        }
-
-        /// <summary>
-        /// Check if two byte arrays are equal
-        /// </summary>
-        /// <param name="left"></param>
-        /// <param name="right"></param>
-        /// <returns></returns>
-        private bool AreEqual(byte[] left, byte[] right)
-        {
-            if (object.ReferenceEquals(left, right))
-            {
-                return true;
-            }
-
-            if (left == null || right == null || left.Length != right.Length)
-            {
-                return false;
-            }
-
-            return left.SequenceEqual<byte>(right);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/GenericTDSServerSession.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/GenericTDSServerSession.cs
deleted file mode 100644 (file)
index cfe2814..0000000
+++ /dev/null
@@ -1,501 +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.Security.Cryptography.X509Certificates;
-using System.Collections.Generic;
-
-using Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.EndPoint.SSPI;
-using Microsoft.SqlServer.TDS.PreLogin;
-using Microsoft.SqlServer.TDS.Login7;
-using Microsoft.SqlServer.TDS.SessionState;
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Generic session for TDS Server
-    /// </summary>
-    public class GenericTDSServerSession : ITDSServerSession
-    {
-        /// <summary>
-        /// Server that created the session
-        /// </summary>
-        public ITDSServer Server { get; private set; }
-
-        /// <summary>
-        /// Session identifier
-        /// </summary>
-        public uint SessionID { get; private set; }
-
-        /// <summary>
-        /// Size of the TDS packet
-        /// </summary>
-        public uint PacketSize { get; set; }
-
-        /// <summary>
-        /// User name if SQL authentication is used
-        /// </summary>
-        public string SQLUserID { get; set; }
-
-        /// <summary>
-        /// Context that indicates the stage of SSPI authentication
-        /// </summary>
-        public SSPIContext NTUserAuthenticationContext { get; set; }
-
-        /// <summary>
-        /// Database to which connection is established
-        /// </summary>
-        public string Database { get; set; }
-
-        /// <summary>
-        /// Collation
-        /// </summary>
-        public byte[] Collation { get; set; }
-
-        /// <summary>
-        /// TDS version of the communication
-        /// </summary>
-        public Version TDSVersion { get; set; }
-
-        /// <summary>
-        /// Local connection end-point information
-        /// </summary>
-        public TDSEndPointInfo ServerEndPointInfo { get; set; }
-
-        /// <summary>
-        /// Remote connection end-point information
-        /// </summary>
-        public TDSEndPointInfo ClientEndPointInfo { get; set; }
-
-        /// <summary>
-        /// Transport encryption
-        /// </summary>
-        public TDSEncryptionType Encryption { get; set; }
-
-        /// <summary>
-        /// Certificate to use for encryption
-        /// </summary>
-        public X509Certificate EncryptionCertificate { get; set; }
-
-        /// <summary>
-        /// Nonce option sent by client
-        /// </summary>
-        public byte[] ClientNonce { get; set; }
-
-        /// <summary>
-        /// Nonce option sent by server
-        /// </summary>
-        public byte[] ServerNonce { get; set; }
-
-        /// <summary>
-        /// FedAuthRequired Response sent by server
-        /// </summary>
-        public TdsPreLoginFedAuthRequiredOption FedAuthRequiredPreLoginServerResponse { get; set; }
-
-        /// <summary>
-        /// Federated authentication set of libraries to be used
-        /// </summary>
-        public TDSFedAuthLibraryType FederatedAuthenticationLibrary { get; set; }
-
-        /// <summary>
-        /// Counter of connection reset requests for this session
-        /// </summary>
-        public int ConnectionResetRequestCount { get; set; }
-
-        /// <summary>
-        /// Indicates whether this session supports transport-level recovery
-        /// </summary>
-        public bool IsSessionRecoveryEnabled { get; set; }
-
-        #region Session Options
-
-        /// <summary>
-        /// Controls a group of SQL Server settings that collectively specify ISO standard behavior
-        /// </summary>
-        public bool AnsiDefaults
-        {
-            get
-            {
-                // See ...\sql\ntdbms\include\typesystem\setopts.h, SetAnsiDefaults()
-                return AnsiNullDefaultOn && AnsiNulls && AnsiPadding && AnsiWarnings && CursorCloseOnCommit && ImplicitTransactions && QuotedIdentifier;
-            }
-            set
-            {
-                // Populate ansi defaults
-                AnsiNullDefaultOn = value;
-                AnsiNulls = value;
-                AnsiPadding = value;
-                AnsiWarnings = value;
-                CursorCloseOnCommit = value;
-                ImplicitTransactions = value;
-                QuotedIdentifier = value;
-            }
-        }
-
-        /// <summary>
-        /// Affects the nullability of new columns when the nullability of the column is not specified in the CREATE TABLE and ALTER TABLE statements.
-        /// </summary>
-        public bool AnsiNullDefaultOn { get; set; }
-
-        /// <summary>
-        /// Controls null behavior in T-SQL
-        /// </summary>
-        public bool AnsiNulls { get; set; }
-
-        /// <summary>
-        /// Impacts character column behavior (char, varchar, binary, and varbinary)
-        /// </summary>
-        public bool AnsiPadding { get; set; }
-
-        /// <summary>
-        /// Controls certain warning messages required for ansi compliance
-        /// </summary>
-        public bool AnsiWarnings { get; set; }
-
-        /// <summary>
-        /// Terminates a query when an overflow or divide-by-zero error occurs during query execution
-        /// </summary>
-        public bool ArithAbort { get; set; }
-
-        /// <summary>
-        /// Controls whether error messages are returned from overflow or divide-by-zero errors during a query
-        /// </summary>
-        public bool ArithIgnore { get; set; }
-
-        /// <summary>
-        /// Controls whether concatenation results are treated as null or empty string values
-        /// </summary>
-        public bool ConcatNullYieldsNull { get; set; }
-
-        /// <summary>
-        /// Associates up to 128 bytes of binary information with the current session or connection
-        /// </summary>
-        public byte[] ContextInfo { get; set; }
-
-        /// <summary>
-        /// Controls whether the server will close cursors when you commit a transaction
-        /// </summary>
-        public bool CursorCloseOnCommit { get; set; }
-
-        /// <summary>
-        /// Sets the first day of the week to a number from 1 through 7
-        /// </summary>
-        public byte DateFirst { get; set; }
-
-        /// <summary>
-        /// Sets the order of the month, day, and year date parts for interpreting date character strings
-        /// </summary>
-        public DateFormatType DateFormat { get; set; }
-
-        /// <summary>
-        /// Specifies the relative importance that the current session continue processing if it is deadlocked with another session.
-        /// </summary>
-        public int DeadlockPriority { get; set; }
-
-        /// <summary>
-        /// Sets implicit transaction mode for the connection
-        /// </summary>
-        public bool ImplicitTransactions { get; set; }
-
-        /// <summary>
-        /// Specifies the language environment for the session (language name from sys.syslanguages). The session language determines the datetime formats and system messages.
-        /// </summary>
-        public LanguageType Language { get; set; }
-
-        /// <summary>
-        /// Specifies the number of milliseconds a statement waits for a lock to be released
-        /// </summary>
-        public int LockTimeout { get; set; }
-
-        /// <summary>
-        /// Controls the emitting of Done w/count tokens from Transact-SQL.
-        /// </summary>
-        public bool NoCount { get; set; }
-
-        /// <summary>
-        /// Generates an error when a loss of precision occurs in an expression
-        /// </summary>
-        public bool NumericRoundAbort { get; set; }
-
-        /// <summary>
-        /// Causes SQL Server to follow the ISO rules regarding quotation mark delimiting identifiers and literal strings
-        /// </summary>
-        public bool QuotedIdentifier { get; set; }
-
-        /// <summary>
-        /// Specifies the size of varchar(max), nvarchar(max), varbinary(max), text, ntext, and image data returned by a SELECT statement
-        /// </summary>
-        public int TextSize { get; set; }
-
-        /// <summary>
-        /// Controls the locking and row versioning behavior of Transact-SQL statements issued by a connection to SQL Server.
-        /// </summary>
-        public TransactionIsolationLevelType TransactionIsolationLevel { get; set; }
-
-        /// <summary>
-        /// Specifies whether SQL Server automatically rolls back the current transaction when a Transact-SQL statement raises a run-time error
-        /// </summary>
-        public bool TransactionAbortOnError { get; set; }
-
-        #endregion
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public GenericTDSServerSession(ITDSServer server, uint sessionID) :
-            this(server, sessionID, 4096)
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public GenericTDSServerSession(ITDSServer server, uint sessionID, uint packetSize)
-        {
-            // Save the server
-            Server = server;
-
-            // Save session identifier
-            SessionID = sessionID;
-
-            // Save packet size
-            PacketSize = packetSize;
-
-            // By default encryption is disabled
-            Encryption = TDSEncryptionType.Off;
-
-            // First day of the week
-            DateFirst = 7;
-
-            // Transaction isolation level
-            TransactionIsolationLevel = TransactionIsolationLevelType.ReadCommited;
-
-            // Language
-            Language = LanguageType.English;
-
-            // Date format
-            DateFormat = DateFormatType.MonthDayYear;
-
-            // Default collation
-            Collation = new byte[] { 0x09, 0x04, 0xD0, 0x00, 0x34 };
-
-            // Infinite text size
-            TextSize = -1;
-        }
-
-        /// <summary>
-        /// Inflate the session state using options
-        /// </summary>
-        public virtual void Inflate(TDSSessionRecoveryData initial, TDSSessionRecoveryData current)
-        {
-            // Check if we have an initial state
-            if (initial != null)
-            {
-                // Save initial values
-                _InflateRecoveryData(initial);
-            }
-
-            // Check if we have a current value
-            if (current != null)
-            {
-                // Update values with current
-                _InflateRecoveryData(current);
-            }
-        }
-
-        /// <summary>
-        /// Serialize session state into a collection of options
-        /// </summary>
-        /// <returns></returns>
-        public virtual IList<TDSSessionStateOption> Deflate()
-        {
-            // Prepare options list
-            IList<TDSSessionStateOption> options = new List<TDSSessionStateOption>();
-
-            // Create user options option
-            TDSSessionStateUserOptionsOption userOptionsOption = new TDSSessionStateUserOptionsOption();
-
-            // Transfer properties from the session onto the session state
-            userOptionsOption.AnsiWarnings = AnsiWarnings;
-            userOptionsOption.AnsiNulls = AnsiNulls;
-            userOptionsOption.CursorCloseOnCommit = CursorCloseOnCommit;
-            userOptionsOption.QuotedIdentifier = QuotedIdentifier;
-            userOptionsOption.ConcatNullYieldsNull = ConcatNullYieldsNull;
-            userOptionsOption.AnsiNullDefaultOn = AnsiNullDefaultOn;
-            userOptionsOption.AnsiPadding = AnsiPadding;
-            userOptionsOption.ArithAbort = ArithAbort;
-            userOptionsOption.TransactionAbortOnError = TransactionAbortOnError;
-            userOptionsOption.NoCount = NoCount;
-            userOptionsOption.ArithIgnore = ArithIgnore;
-            userOptionsOption.ImplicitTransactions = ImplicitTransactions;
-            userOptionsOption.NumericRoundAbort = ImplicitTransactions;
-
-            // Register option with the collection
-            options.Add(userOptionsOption);
-
-            // Create date first/date format option
-            TDSSessionStateDateFirstDateFormatOption dateFirstDateFormatOption = new TDSSessionStateDateFirstDateFormatOption();
-
-            // Transfer properties from the session onto the session state
-            dateFirstDateFormatOption.DateFirst = DateFirst;
-            dateFirstDateFormatOption.DateFormat = DateFormat;
-
-            // Register option with the collection
-            options.Add(dateFirstDateFormatOption);
-
-            // Allocate deadlock priority option
-            TDSSessionStateDeadlockPriorityOption deadlockPriorityOption = new TDSSessionStateDeadlockPriorityOption();
-
-            // Transfer properties from the session onto the session state
-            deadlockPriorityOption.Value = (sbyte)DeadlockPriority;
-
-            // Register option with the collection
-            options.Add(deadlockPriorityOption);
-
-            // Allocate lock timeout option
-            TDSSessionStateLockTimeoutOption lockTimeoutOption = new TDSSessionStateLockTimeoutOption();
-
-            // Transfer properties from the session onto the session state
-            lockTimeoutOption.Value = LockTimeout;
-
-            // Register option with the collection
-            options.Add(lockTimeoutOption);
-
-            // Allocate ISO fips option
-            TDSSessionStateISOFipsOption isoFipsOption = new TDSSessionStateISOFipsOption();
-
-            // Transfer properties from the session onto the session state
-            isoFipsOption.TransactionIsolationLevel = TransactionIsolationLevel;
-
-            // Register option with the collection
-            options.Add(isoFipsOption);
-
-            // Allocate text size option
-            TDSSessionStateTextSizeOption textSizeOption = new TDSSessionStateTextSizeOption();
-
-            // Transfer properties from the session onto the session state
-            textSizeOption.Value = TextSize;
-
-            // Register option with the collection
-            options.Add(textSizeOption);
-
-            // Check if context info is specified
-            if (ContextInfo != null)
-            {
-                // Allocate context info option
-                TDSSessionStateContextInfoOption contextInfoOption = new TDSSessionStateContextInfoOption();
-
-                // Transfer properties from the session onto the session state
-                contextInfoOption.Value = ContextInfo;
-
-                // Register option with the collection
-                options.Add(isoFipsOption);
-            }
-
-            return options;
-        }
-
-        /// <summary>
-        /// Inflate recovery data
-        /// </summary>
-        private void _InflateRecoveryData(TDSSessionRecoveryData data)
-        {
-            // Check if database is available
-            if (data.Database != null)
-            {
-                // Apply database
-                Database = data.Database;
-            }
-
-            // Check if language is available
-            if (data.Language != null)
-            {
-                // Apply language
-                Language = LanguageString.ToEnum(data.Language);
-            }
-
-            // Check if collation is available
-            if (data.Collation != null)
-            {
-                Collation = data.Collation;
-            }
-
-            // Traverse all session states and inflate each separately
-            foreach (TDSSessionStateOption option in data.Options)
-            {
-                // Check on the options
-                if (option is TDSSessionStateUserOptionsOption)
-                {
-                    // Cast to specific option
-                    TDSSessionStateUserOptionsOption specificOption = option as TDSSessionStateUserOptionsOption;
-
-                    // Transfer properties from the session state onto the session
-                    AnsiWarnings = specificOption.AnsiWarnings;
-                    AnsiNulls = specificOption.AnsiNulls;
-                    CursorCloseOnCommit = specificOption.CursorCloseOnCommit;
-                    QuotedIdentifier = specificOption.QuotedIdentifier;
-                    ConcatNullYieldsNull = specificOption.ConcatNullYieldsNull;
-                    AnsiNullDefaultOn = specificOption.AnsiNullDefaultOn;
-                    AnsiPadding = specificOption.AnsiPadding;
-                    ArithAbort = specificOption.ArithAbort;
-                    TransactionAbortOnError = specificOption.TransactionAbortOnError;
-                    NoCount = specificOption.NoCount;
-                    ArithIgnore = specificOption.ArithIgnore;
-                    ImplicitTransactions = specificOption.ImplicitTransactions;
-                    NumericRoundAbort = specificOption.NumericRoundAbort;
-                }
-                else if (option is TDSSessionStateDateFirstDateFormatOption)
-                {
-                    // Cast to specific option
-                    TDSSessionStateDateFirstDateFormatOption specificOption = option as TDSSessionStateDateFirstDateFormatOption;
-
-                    // Transfer properties from the session state onto the session
-                    DateFirst = specificOption.DateFirst;
-                    DateFormat = specificOption.DateFormat;
-                }
-                else if (option is TDSSessionStateDeadlockPriorityOption)
-                {
-                    // Cast to specific option
-                    TDSSessionStateDeadlockPriorityOption specificOption = option as TDSSessionStateDeadlockPriorityOption;
-
-                    // Transfer properties from the session state onto the session
-                    DeadlockPriority = specificOption.Value;
-                }
-                else if (option is TDSSessionStateLockTimeoutOption)
-                {
-                    // Cast to specific option
-                    TDSSessionStateLockTimeoutOption specificOption = option as TDSSessionStateLockTimeoutOption;
-
-                    // Transfer properties from the session state onto the session
-                    LockTimeout = specificOption.Value;
-                }
-                else if (option is TDSSessionStateISOFipsOption)
-                {
-                    // Cast to specific option
-                    TDSSessionStateISOFipsOption specificOption = option as TDSSessionStateISOFipsOption;
-
-                    // Transfer properties from the session state onto the session
-                    TransactionIsolationLevel = specificOption.TransactionIsolationLevel;
-                }
-                else if (option is TDSSessionStateTextSizeOption)
-                {
-                    // Cast to specific option
-                    TDSSessionStateTextSizeOption specificOption = option as TDSSessionStateTextSizeOption;
-
-                    // Transfer properties from the session state onto the session
-                    TextSize = specificOption.Value;
-                }
-                else if (option is TDSSessionStateContextInfoOption)
-                {
-                    // Cast to specific option
-                    TDSSessionStateContextInfoOption specificOption = option as TDSSessionStateContextInfoOption;
-
-                    // Transfer properties from the session state onto the session
-                    ContextInfo = specificOption.Value;
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/QueryEngine.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/QueryEngine.cs
deleted file mode 100644 (file)
index 53fba4d..0000000
+++ /dev/null
@@ -1,2058 +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 Microsoft.SqlServer.TDS.ColMetadata;
-using Microsoft.SqlServer.TDS.Done;
-using Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.Row;
-using Microsoft.SqlServer.TDS.SQLBatch;
-using Microsoft.SqlServer.TDS.Info;
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Class that pretends to be a full featured relational engine and returns predefined responses to well-known queries that Topology framework issues
-    /// </summary>
-    public class QueryEngine
-    {
-        /// <summary>
-        /// Log to which send TDS conversation
-        /// </summary>
-        public TextWriter Log { get; set; }
-
-        /// <summary>
-        /// Server configuration
-        /// </summary>
-        public TDSServerArguments ServerArguments { get; private set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public QueryEngine(TDSServerArguments arguments)
-        {
-            ServerArguments = arguments;
-        }
-
-        /// <summary>
-        /// Execute the query and produce a response
-        /// </summary>
-        public TDSMessageCollection ExecuteBatch(ITDSServerSession session, TDSMessage request)
-        {
-            // Get the batch from the tokens
-            TDSSQLBatchToken batchRequest = request[0] as TDSSQLBatchToken;
-
-            // Log request
-            TDSUtilities.Log(Log, "Request", batchRequest);
-
-            // Increase the counter of connection reset requests if the message contains the proper flags
-            if (request.IsResetConnectionRequestSet || request.IsResetConnectionSkipTransactionRequestSet)
-            {
-                session.ConnectionResetRequestCount++;
-            }
-
-            // Prepare response message
-            return CreateQueryResponse(session, batchRequest);
-        }
-
-        /// <summary>
-        /// Create a response for the query
-        /// </summary>
-        /// <param name="session"></param>
-        /// <param name="batchRequest"></param>
-        /// <returns></returns>
-        protected virtual TDSMessageCollection CreateQueryResponse(ITDSServerSession session, TDSSQLBatchToken batchRequest)
-        {
-            TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response);
-
-            // Prepare query text
-            string lowerBatchText = batchRequest.Text.ToLowerInvariant();
-
-            // Check query
-            if (lowerBatchText.Contains("serverproperty('servername')"))  // SELECT convert(nvarchar(256), ServerProperty('ServerName'))
-            {
-                // Delegate to server name query
-                responseMessage = _PrepareServerNameResponse(session);
-            }
-            if (lowerBatchText.Contains("serverproperty('machinename')"))  // SELECT convert(nvarchar(256), ServerProperty('MachineName'))
-            {
-                // Delegate to server name query
-                responseMessage = _PrepareMachineNameResponse(session);
-            }
-            else if (lowerBatchText.Contains("serverproperty('instancename')"))  // SELECT convert(nvarchar(256), ServerProperty('InstanceName'))
-            {
-                // Delegate to instance name query
-                responseMessage = _PrepareInstanceNameResponse(session);
-            }
-            else if (lowerBatchText.Contains("serverproperty('ishadrenabled')"))  // SELECT convert(bit, ServerProperty('IsHADREnabled'))
-            {
-                // Delegate to HADRon query
-                responseMessage = _PrepareIsHADRResponse(session);
-            }
-            else if (lowerBatchText.Contains("serverproperty('engineedition')"))  // SELECT convert(int, ServerProperty('EngineEdition'))
-            {
-                // Delegate to Azure query
-                responseMessage = _PrepareIsAzure(session);
-            }
-            else if (lowerBatchText.Contains("serverproperty('islocaldb')"))  // SELECT convert(bit, ServerProperty('IsLocalDB'))
-            {
-                // Delegate to Local DB query
-                responseMessage = _PrepareIsLocalDB(session);
-            }
-            else if (lowerBatchText.Contains("serverproperty('istestsqlserver')"))  // SELECT convert(bit, ServerProperty('IsTestSQLServer'))
-            {
-                // Delegate to test SQL Server query response
-                responseMessage = _PrepareIsTestSQLServerResponse(session);
-            }
-            else if (lowerBatchText.Contains("serverproperty('testsqlserverclass')"))  // SELECT convert(nvarchar(256), ServerProperty('TestSQLServerClass'))
-            {
-                // Delegate to test SQL Server class response
-                responseMessage = _PrepareTestSQLServerClassResponse(session);
-            }
-            else if (lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("login_name")
-                && lowerBatchText.Contains("nt_domain")
-                && lowerBatchText.Contains("nt_user_name")
-                && lowerBatchText.Contains("session_id"))  // SELECT login_name, nt_domain, nt_user_name FROM sys.dm_exec_sessions WHERE session_id = @@spid
-            {
-                // Delegate to session user query
-                responseMessage = _PrepareSessionUserResponse(session);
-            }
-            else if (lowerBatchText.Contains("sp_oledb_ro_usrname"))  // exec [sys].sp_oledb_ro_usrname
-            {
-                // Delegate to OLE DB query
-                responseMessage = _PrepareOleDbReadOnlyUserName(session);
-            }
-            else if (lowerBatchText.Contains("physical_net_transport")
-                && lowerBatchText.Contains("local_net_address")
-                && lowerBatchText.Contains("local_tcp_port"))  // SELECT convert(nvarchar(40), ConnectionProperty('physical_net_transport')), convert(varchar(48), ConnectionProperty('local_net_address')), convert(int, ConnectionProperty('local_tcp_port'))
-            {
-                // Delegate to connection information query
-                responseMessage = _PrepareConnectionInfoResponse(session);
-            }
-            else if (lowerBatchText.Contains("dm_exec_connections")
-                && lowerBatchText.Contains("encrypt_option")
-                && lowerBatchText.Contains("session_id"))  // SELECT TOP (1) [encrypt_option] FROM [sys].[dm_exec_connections] WHERE [session_id] = @@SPID
-            {
-                // Delegate to encryption information query
-                responseMessage = _PrepareEncryptionInfoResponse(session);
-            }
-            else if (lowerBatchText.Contains("select 1"))  // SELECT 1
-            {
-                // Delegate to server ping response
-                responseMessage = _PreparePingResponse(session);
-            }
-            else if (lowerBatchText.Contains("name")
-                && lowerBatchText.Contains("state")
-                && lowerBatchText.Contains("databases")
-                && lowerBatchText.Contains("db_name"))  // SELECT [name], [state] FROM [sys].[databases] WHERE [name] = db_name()
-            {
-                // Delegate to current database response
-                responseMessage = _PrepareDatabaseResponse(session);
-            }
-            else if (lowerBatchText.Contains("dbcc")
-                && lowerBatchText.Contains("tracestatus"))   // dbcc tracestatus()
-            {
-                // Delegate to current configuration response
-                responseMessage = _PrepareConfigurationResponse(session);
-            }
-            else if (lowerBatchText.Contains("connectionproperty('sp_reset_connection_count')"))  // select CONNECTIONPROPERTY('sp_reset_connection_count')
-            {
-                // Delegate to reset connection request response
-                responseMessage = _PrepareConnectionResetRequestCountResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("convert")
-                && lowerBatchText.Contains("nvarchar(128)")
-                && lowerBatchText.Contains("@@spid"))  // SELECT convert(nvarchar(128), @@SPID)
-            {
-                // Delegate to reset connection request response
-                responseMessage = _PrepareSPIDResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("auth_scheme")
-                && lowerBatchText.Contains("dm_exec_connections")) //select top (1) [auth_scheme] from [sys].[dm_exec_connections] where [session_id] = @@spid
-            {
-                // Delegate to reset connection request response
-                responseMessage = _PrepareAuthSchemeResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("ansi_defaults")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_defaults] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareAnsiDefaultsResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("ansi_null_dflt_on")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_null_dflt_on] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareAnsiNullDefaultOnResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("ansi_nulls")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_nulls] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareAnsiNullsResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("ansi_padding")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_padding] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareAnsiPaddingResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("ansi_warnings")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [ansi_warnings] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareAnsiWarningsResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("arithabort")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [arithabort] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareArithAbortResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("concat_null_yields_null")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [concat_null_yields_null] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareConcatNullYieldsNullResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("date_first")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [date_first] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareDateFirstResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("date_format")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [date_format] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareDateFormatResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("deadlock_priority")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [deadlock_priority] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareDeadlockPriorityResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("language")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [language] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareLanguageResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("lock_timeout")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [lock_timeout] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareLockTimeoutResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("quoted_identifier")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [quoted_identifier] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareQuotedIdentifierResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("text_size")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [text_size] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareTextSizeResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("transaction_isolation_level")
-                && lowerBatchText.Contains("dm_exec_sessions")
-                && lowerBatchText.Contains("session_id")
-                && lowerBatchText.Contains("@@spid"))  // SELECT TOP (1) [transaction_isolation_level] FROM [sys].[dm_exec_sessions] WHERE [session_id] = @@SPID
-            {
-                // Delegate session property query
-                responseMessage = _PrepareTransactionIsolationLevelResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("@@options"))  // SELECT @@OPTIONS
-            {
-                // Delegate session property query
-                responseMessage = _PrepareOptionsResponse(session);
-            }
-            else if (lowerBatchText.Contains("select")
-                && lowerBatchText.Contains("context_info()"))  // SELECT CONTEXT_INFO()
-            {
-                // Delegate session property query
-                responseMessage = _PrepareContextInfoResponse(session);
-            }
-            else
-            {
-                // Create an info token that contains the query received
-                TDSInfoToken infoToken = new TDSInfoToken(2012, 2, 0, lowerBatchText);
-
-                // Log response
-                TDSUtilities.Log(Log, "Response", infoToken);
-
-                // Serialize DONE token into the response packet
-                responseMessage.Add(infoToken);
-
-                // Create an info token to let client know that we don't recognize this query
-                infoToken = new TDSInfoToken(2012, 2, 0, "Received query is not recognized by the query engine. Please ask a very specific question.");
-
-                // Log response
-                TDSUtilities.Log(Log, "Response", infoToken);
-
-                // Serialize DONE token into the response packet
-                responseMessage.Add(infoToken);
-
-                // Create generic DONE token
-                TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final);
-
-                // Log response
-                TDSUtilities.Log(Log, "Response", doneToken);
-
-                // Serialize DONE token into the response packet
-                responseMessage.Add(doneToken);
-            }
-
-            // Response collection will contain only one message
-            return new TDSMessageCollection(responseMessage);
-        }
-
-
-        /// <summary>
-        /// Handle attention from the client
-        /// </summary>
-        public TDSMessageCollection ExecuteAttention(ITDSServerSession session, TDSMessage request)
-        {
-            // Create attention DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Attention);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Return a single message with DONE token only
-            return new TDSMessageCollection(new TDSMessage(TDSMessageType.Response, doneToken));
-        }
-
-        /// <summary>
-        /// Prepare response for server name query
-        /// </summary>
-        private TDSMessage _PrepareServerNameResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(256, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row
-            rowToken.Data.Add(ServerArguments.ServerName);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for machine name query
-        /// </summary>
-        private TDSMessage _PrepareMachineNameResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(256, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row
-            rowToken.Data.Add(Environment.MachineName.ToUpper());
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for server instance name query
-        /// </summary>
-        private TDSMessage _PrepareInstanceNameResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(256, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Start with server name
-            string value = ServerArguments.ServerName;
-
-            // Check if server name contains a slash
-            if (value.Contains("\\"))
-            {
-                // Take everything after the slash
-                value = value.Substring(value.IndexOf('\\') + 1);
-            }
-            else
-            {
-                // Instance is unnamed
-                value = null;
-            }
-
-            // Add row
-            rowToken.Data.Add(value);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for user nane query that OLE DB stack dispatches upon connection
-        /// </summary>
-        private TDSMessage _PrepareOleDbReadOnlyUserName(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.BigVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(1, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Start second column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(128, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row
-            rowToken.Data.Add("N");
-            rowToken.Data.Add("dbo");
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for query whether this is a HADRon instance
-        /// </summary>
-        private TDSMessage _PrepareIsHADRResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.BitN;
-            column.DataTypeSpecific = (byte)1;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsComputed = true;
-            column.Flags.IsNullable = true;  // TODO: Must be nullable, otherwise something is wrong with SqlClient
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add a data row that indicates that this is not a HADRon server
-            rowToken.Data.Add(false);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for query whether this is a SQL Azure instance
-        /// </summary>
-        private TDSMessage _PrepareIsAzure(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)4;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsComputed = true;
-            column.Flags.IsNullable = true;  // TODO: Must be nullable, otherwise something is wrong with SqlClient
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Per https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql
-            // 4 = Express (This is returned for Express, Express with Advanced Services, and Windows Embedded SQL.)
-            rowToken.Data.Add(4);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for query whether this is a Local DB instance
-        /// </summary>
-        private TDSMessage _PrepareIsLocalDB(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.BitN;
-            column.DataTypeSpecific = (byte)1;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsComputed = true;
-            column.Flags.IsNullable = true;  // TODO: Must be nullable, otherwise something is wrong with SqlClient
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add a data row that indicates that this is not a Local DB server
-            rowToken.Data.Add(false);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for query whether this is a test SQL Server instance
-        /// </summary>
-        private TDSMessage _PrepareIsTestSQLServerResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.BitN;
-            column.DataTypeSpecific = (byte)1;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsComputed = true;
-            column.Flags.IsNullable = true;  // TODO: Must be nullable, otherwise something is wrong with SqlClient
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add a data row that indicates that this is a test SQL Server
-            rowToken.Data.Add(true);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for query of class of the SQL Server instance
-        /// </summary>
-        private TDSMessage _PrepareTestSQLServerClassResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(256, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Get the server class
-            rowToken.Data.Add(session.Server.GetType().FullName);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for session user name query
-        /// </summary>
-        private TDSMessage _PrepareSessionUserResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Prepare column type-specific data
-            TDSShilohVarCharColumnSpecific nVarChar = new TDSShilohVarCharColumnSpecific(256, new TDSColumnDataCollation(13632521, 52));
-
-            // Prepare the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.Unknown;
-            column.Flags.IsNullable = true;
-            column.DataTypeSpecific = nVarChar;
-            column.Name = "nt_user_name";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Prepare the second column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.Unknown;
-            column.Flags.IsNullable = true;
-            column.DataTypeSpecific = nVarChar;
-            column.Name = "nt_domain";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Prepare the third column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.Unknown;
-            column.DataTypeSpecific = nVarChar;
-            column.Name = "login_name";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Check user type
-            if (session.SQLUserID != null)
-            {
-                // Add row
-                rowToken.Data.Add(null);  // nt_user_name
-                rowToken.Data.Add(null);  // nt_domain
-                rowToken.Data.Add(session.SQLUserID);  // login_name
-            }
-            else if (session.NTUserAuthenticationContext != null)
-            {
-                // Get user identifier
-                string userID = session.NTUserAuthenticationContext.GetRemoteIdentity().Name;
-
-                // Look for traditional separator for form "<domain>\<user>"
-                int indexOfSeparator = userID.IndexOf('\\');
-
-                string domain = null;
-                string user = null;
-
-                // Parse domain and user out of the entry
-                if (indexOfSeparator != -1)
-                {
-                    // Extract parts
-                    domain = userID.Substring(0, indexOfSeparator);
-                    user = userID.Substring(indexOfSeparator + 1);
-                }
-                else
-                {
-                    // Look for a different type of separator for form "<user>@<domain>"
-                    indexOfSeparator = userID.IndexOf('@');
-
-                    // Check if found
-                    if (indexOfSeparator != -1)
-                    {
-                        // Extract parts
-                        domain = userID.Substring(indexOfSeparator + 1);
-                        user = userID.Substring(0, indexOfSeparator);
-                    }
-                    else
-                    {
-                        // We don't recognize this user so don't parse it
-                        domain = null;
-                        user = userID;
-                    }
-                }
-
-                // Add row
-                rowToken.Data.Add(user);  // nt_user_name
-                rowToken.Data.Add(domain);  // nt_domain
-                rowToken.Data.Add(userID);  // login_name
-            }
-            else
-            {
-                // We don't have a user, which is very strange since we're in query engine already
-                rowToken.Data.Add(null);  // nt_user_name
-                rowToken.Data.Add(null);  // nt_domain
-                rowToken.Data.Add(null);  // login_name
-            }
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response to the query about connection end-point
-        /// </summary>
-        private TDSMessage _PrepareConnectionInfoResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(40, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "net_transport";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Start the second column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.BigVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(48, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.IsNullable = true;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "local_net_address";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Start the third column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)4;
-            column.Flags.IsNullable = true;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "local_tcp_port";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row
-            rowToken.Data.Add(session.ServerEndPointInfo.Transport.ToString());
-            rowToken.Data.Add(session.ServerEndPointInfo.Address.ToString());
-            rowToken.Data.Add(session.ServerEndPointInfo.Port);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response to the query about connection encryption
-        /// </summary>
-        private TDSMessage _PrepareEncryptionInfoResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(40, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "encrypt_option";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Check if encryption is enabled
-            if (session.Encryption == TDSEncryptionType.Full)
-            {
-                // Add row
-                rowToken.Data.Add("TRUE");
-            }
-            else
-            {
-                // Add row
-                rowToken.Data.Add("FALSE");
-            }
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response to server ping
-        /// </summary>
-        private TDSMessage _PreparePingResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)4;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsNullable = true;  // TODO: Must be nullable, otherwise something is wrong with SqlClient
-            column.Flags.IsComputed = true;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row
-            rowToken.Data.Add((int)1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare current database response
-        /// </summary>
-        private TDSMessage _PrepareDatabaseResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(256, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "name";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Start the second column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)1;
-            column.Flags.IsNullable = true;
-            column.Name = "state";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row
-            rowToken.Data.Add(session.Database);
-            rowToken.Data.Add((byte)0);  // Online
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare configuration response
-        /// </summary>
-        private TDSMessage _PrepareConfigurationResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)2;
-            column.Flags.IsNullable = true;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "TraceFlag";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Start the second column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)2;
-            column.Flags.IsNullable = true;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "Status";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Start the third column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)2;
-            column.Flags.IsNullable = true;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "Global";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Start the fourth column
-            column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)2;
-            column.Flags.IsNullable = true;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "Session";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 0);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response to connection reset request count
-        /// </summary>
-        private TDSMessage _PrepareConnectionResetRequestCountResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the second column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.IntN;
-            column.DataTypeSpecific = (byte)4;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsComputed = true;
-            column.Flags.IsNullable = true;  // TODO: Must be nullable, otherwise something is wrong with SqlClient
-            column.Name = "ConnectionResetRequestCount";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row data
-            rowToken.Data.Add(session.ConnectionResetRequestCount);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response to connection reset request count
-        /// </summary>
-        private TDSMessage _PrepareSPIDResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(128, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsNullable = true;
-            column.Flags.IsComputed = true;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Add row
-            rowToken.Data.Add(session.SessionID.ToString());
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response to connection reset request count
-        /// </summary>
-        private TDSMessage _PrepareAuthSchemeResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start the first column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(40, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "auth_scheme";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Check which authentication method are we using
-            // @TODO add Federated Authentication once VSTS 1072394 is resolved
-            if (session.SQLUserID != null)
-            {
-                // Add row
-                rowToken.Data.Add("SQL");
-            }
-            else
-            {
-                // Add row
-                rowToken.Data.Add("NTML");
-            }
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for ANSI defaults
-        /// </summary>
-        private TDSMessage _PrepareAnsiDefaultsResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "ansi_defaults";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).AnsiDefaults);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for ANSI null default on
-        /// </summary>
-        private TDSMessage _PrepareAnsiNullDefaultOnResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "ansi_null_dflt_on";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).AnsiNullDefaultOn);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for ANSI nulls
-        /// </summary>
-        private TDSMessage _PrepareAnsiNullsResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "ansi_nulls";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).AnsiNulls);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for ANSI padding
-        /// </summary>
-        private TDSMessage _PrepareAnsiPaddingResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "ansi_padding";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).AnsiPadding);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for ANSI warnings
-        /// </summary>
-        private TDSMessage _PrepareAnsiWarningsResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "ansi_warnings";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).AnsiWarnings);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for arithmetic abort
-        /// </summary>
-        private TDSMessage _PrepareArithAbortResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "arithabort";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).ArithAbort);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for concatenation of nulls yields null
-        /// </summary>
-        private TDSMessage _PrepareConcatNullYieldsNullResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "concat_null_yields_null";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).ConcatNullYieldsNull);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for date first
-        /// </summary>
-        private TDSMessage _PrepareDateFirstResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Int2;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "date_first";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((short)(session as GenericTDSServerSession).DateFirst);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for date format
-        /// </summary>
-        private TDSMessage _PrepareDateFormatResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(6, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsNullable = true;
-            column.Name = "date_format";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Generate a date format string
-            rowToken.Data.Add(DateFormatString.ToString((session as GenericTDSServerSession).DateFormat));
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for deadlock priority
-        /// </summary>
-        private TDSMessage _PrepareDeadlockPriorityResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Int4;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "deadlock_priority";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Serialize the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).DeadlockPriority);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for language
-        /// </summary>
-        private TDSMessage _PrepareLanguageResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.NVarChar;
-            column.DataTypeSpecific = new TDSShilohVarCharColumnSpecific(256, new TDSColumnDataCollation(13632521, 52));
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsNullable = true;
-            column.Name = "language";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Generate a date format string
-            rowToken.Data.Add(LanguageString.ToString((session as GenericTDSServerSession).Language));
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for lock timeout
-        /// </summary>
-        private TDSMessage _PrepareLockTimeoutResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Int4;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "lock_timeout";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Serialize the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).LockTimeout);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for quoted identifier
-        /// </summary>
-        private TDSMessage _PrepareQuotedIdentifierResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Bit;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "quoted_identifier";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).QuotedIdentifier);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for text size
-        /// </summary>
-        private TDSMessage _PrepareTextSizeResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Int4;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "text_size";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((session as GenericTDSServerSession).TextSize);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for transaction isolation level
-        /// </summary>
-        private TDSMessage _PrepareTransactionIsolationLevelResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Int2;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Name = "transaction_isolation_level";
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Read the value from the session
-            rowToken.Data.Add((short)(session as GenericTDSServerSession).TransactionIsolationLevel);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for options
-        /// </summary>
-        private TDSMessage _PrepareOptionsResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.Int4;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-            column.Flags.IsComputed = true;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Convert to generic session
-            GenericTDSServerSession genericSession = session as GenericTDSServerSession;
-
-            // Serialize the options into the bit mask
-            int options = 0;
-
-            // Check transaction abort on error
-            if (genericSession.TransactionAbortOnError)
-            {
-                options |= 0x4000;
-            }
-
-            // Check numeric round abort
-            if (genericSession.NumericRoundAbort)
-            {
-                options |= 0x2000;
-            }
-
-            // Check concatenation of nulls yields null
-            if (genericSession.ConcatNullYieldsNull)
-            {
-                options |= 0x1000;
-            }
-
-            // Check ansi null default OFF
-            if (!genericSession.AnsiNullDefaultOn)
-            {
-                options |= 0x800;
-            }
-
-            // Check ansi null default ON
-            if (genericSession.AnsiNullDefaultOn)
-            {
-                options |= 0x400;
-            }
-
-            // Check no count
-            if (genericSession.NoCount)
-            {
-                options |= 0x200;
-            }
-
-            // Check quoted identifier
-            if (genericSession.QuotedIdentifier)
-            {
-                options |= 0x100;
-            }
-
-            // Check arithmetic ignore
-            if (genericSession.ArithIgnore)
-            {
-                options |= 0x80;
-            }
-
-            // Check arithmetic abort
-            if (genericSession.ArithAbort)
-            {
-                options |= 0x40;
-            }
-
-            // Check ansi nulls
-            if (genericSession.AnsiNulls)
-            {
-                options |= 0x20;
-            }
-
-            // Check ansi padding
-            if (genericSession.AnsiPadding)
-            {
-                options |= 0x10;
-            }
-
-            // Check ansi warnings
-            if (genericSession.AnsiWarnings)
-            {
-                options |= 0x8;
-            }
-
-            // Check cursor close on commit
-            if (genericSession.CursorCloseOnCommit)
-            {
-                options |= 0x4;
-            }
-
-            // Check implicit transactions
-            if (genericSession.ImplicitTransactions)
-            {
-                options |= 0x2;
-            }
-
-            // Read the value from the session
-            rowToken.Data.Add(options);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-
-        /// <summary>
-        /// Prepare response for context info
-        /// </summary>
-        private TDSMessage _PrepareContextInfoResponse(ITDSServerSession session)
-        {
-            // Prepare result metadata
-            TDSColMetadataToken metadataToken = new TDSColMetadataToken();
-
-            // Start a new column
-            TDSColumnData column = new TDSColumnData();
-            column.DataType = TDSDataType.BigVarBinary;
-            column.DataTypeSpecific = (ushort)128;
-            column.Flags.Updatable = TDSColumnDataUpdatableFlag.ReadOnly;
-
-            // Add a column to the response
-            metadataToken.Columns.Add(column);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", metadataToken);
-
-            // Prepare result data
-            TDSRowToken rowToken = new TDSRowToken(metadataToken);
-
-            // Prepare context info container
-            byte[] contextInfo = null;
-
-            // Check if session has a context info
-            if ((session as GenericTDSServerSession).ContextInfo != null)
-            {
-                // Allocate a container
-                contextInfo = new byte[128];
-
-                // Copy context info into the container
-                Array.Copy((session as GenericTDSServerSession).ContextInfo, contextInfo, (session as GenericTDSServerSession).ContextInfo.Length);
-            }
-
-            // Set context info
-            rowToken.Data.Add(contextInfo);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", rowToken);
-
-            // Create DONE token
-            TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Count, TDSDoneTokenCommandType.Select, 1);
-
-            // Log response
-            TDSUtilities.Log(Log, "Response", doneToken);
-
-            // Serialize tokens into the message
-            return new TDSMessage(TDSMessageType.Response, metadataToken, rowToken, doneToken);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/RoutingTDSServer.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/RoutingTDSServer.cs
deleted file mode 100644 (file)
index 7ede3dd..0000000
+++ /dev/null
@@ -1,251 +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.Linq;
-
-using Microsoft.SqlServer.TDS.Done;
-using Microsoft.SqlServer.TDS.EndPoint;
-using Microsoft.SqlServer.TDS.EnvChange;
-using Microsoft.SqlServer.TDS.Error;
-using Microsoft.SqlServer.TDS.PreLogin;
-using Microsoft.SqlServer.TDS.Login7;
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// TDS Server that routes clients to the configured destination
-    /// </summary>
-    public class RoutingTDSServer : GenericTDSServer
-    {
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public RoutingTDSServer() :
-            this(new RoutingTDSServerArguments())
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public RoutingTDSServer(RoutingTDSServerArguments arguments) :
-            base(arguments)
-        {
-        }
-
-        /// <summary>
-        /// Handler for pre-login request
-        /// </summary>
-        public override TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request)
-        {
-            // Delegate to the base class
-            TDSMessageCollection response = base.OnPreLoginRequest(session, request);
-
-            // Check if arguments are of the routing server
-            if (Arguments is RoutingTDSServerArguments)
-            {
-                // Cast to routing server arguments
-                RoutingTDSServerArguments serverArguments = Arguments as RoutingTDSServerArguments;
-
-                // Check if routing is configured during login
-                if (serverArguments.RouteOnPacket == TDSMessageType.TDS7Login)
-                {
-                    // Check if pre-login response is contained inside the first message
-                    if (response.Count > 0 && response[0].Any(t => t is TDSPreLoginToken))
-                    {
-                        // Find the first prelogin token
-                        TDSPreLoginToken preLoginResponse = (TDSPreLoginToken)response[0].Where(t => t is TDSPreLoginToken).First();
-
-                        // Inflate pre-login request from the message
-                        TDSPreLoginToken preLoginRequest = request[0] as TDSPreLoginToken;
-
-                        // Update MARS with the requested value
-                        preLoginResponse.IsMARS = preLoginRequest.IsMARS;
-                    }
-                }
-            }
-
-            return response;
-        }
-
-        /// <summary>
-        /// Handler for login request
-        /// </summary>
-        public override TDSMessageCollection OnLogin7Request(ITDSServerSession session, TDSMessage request)
-        {
-            // Inflate login7 request from the message
-            TDSLogin7Token loginRequest = request[0] as TDSLogin7Token;
-
-            // Check if arguments are of the routing server
-            if (Arguments is RoutingTDSServerArguments)
-            {
-                // Cast to routing server arguments
-                RoutingTDSServerArguments ServerArguments = Arguments as RoutingTDSServerArguments;
-
-                // Check filter
-                if (ServerArguments.RequireReadOnly && (loginRequest.TypeFlags.ReadOnlyIntent != TDSLogin7TypeFlagsReadOnlyIntent.ReadOnly))
-                {
-                    // Log request
-                    TDSUtilities.Log(Arguments.Log, "Request", loginRequest);
-
-                    // Prepare ERROR token with the denial details
-                    TDSErrorToken errorToken = new TDSErrorToken(18456, 1, 14, "Received application intent: " + loginRequest.TypeFlags.ReadOnlyIntent.ToString(), Arguments.ServerName);
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                    // Serialize the error token into the response packet
-                    TDSMessage responseMessage = new TDSMessage(TDSMessageType.Response, errorToken);
-
-                    // Prepare ERROR token for the final decision
-                    errorToken = new TDSErrorToken(18456, 1, 14, "Read-Only application intent is required for routing", Arguments.ServerName);
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", errorToken);
-
-                    // Serialize the error token into the response packet
-                    responseMessage.Add(errorToken);
-
-                    // Create DONE token
-                    TDSDoneToken doneToken = new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error);
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", doneToken);
-
-                    // Serialize DONE token into the response packet
-                    responseMessage.Add(doneToken);
-
-                    // Return a single message in the collection
-                    return new TDSMessageCollection(responseMessage);
-                }
-            }
-
-            // Delegate to the base class
-            return base.OnLogin7Request(session, request);
-        }
-
-        /// <summary>
-        /// It is called when SQL batch request arrives
-        /// </summary>
-        /// <param name="message">TDS message recieved</param>
-        /// <returns>TDS message to respond with</returns>
-        public override TDSMessageCollection OnSQLBatchRequest(ITDSServerSession session, TDSMessage request)
-        {
-            // Delegate to the base class to produce the response first
-            TDSMessageCollection batchResponse = base.OnSQLBatchRequest(session, request);
-
-            // Check if arguments are of routing server
-            if (Arguments is RoutingTDSServerArguments)
-            {
-                // Cast to routing server arguments
-                RoutingTDSServerArguments ServerArguments = Arguments as RoutingTDSServerArguments;
-
-                // Check routing condition
-                if (ServerArguments.RouteOnPacket == TDSMessageType.SQLBatch)
-                {
-                    // Construct routing token
-                    TDSPacketToken routingToken = CreateRoutingToken();
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", routingToken);
-
-                    // Insert the routing token at the beginning of the response
-                    batchResponse[0].Insert(0, routingToken);
-                }
-                else
-                {
-                    // Get the first response message
-                    TDSMessage responseMessage = batchResponse[0];
-
-                    // Reset the content of the first message
-                    responseMessage.Clear();
-
-                    // Prepare ERROR token with the denial details
-                    responseMessage.Add(new TDSErrorToken(11111, 1, 14, "Client should have been routed by now", Arguments.ServerName));
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", responseMessage[0]);
-
-                    // Prepare DONE token
-                    responseMessage.Add(new TDSDoneToken(TDSDoneTokenStatusType.Final | TDSDoneTokenStatusType.Error));
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", responseMessage[1]);
-                }
-            }
-
-            // Register only one message with the collection
-            return batchResponse;
-        }
-
-        /// <summary>
-        /// Complete login sequence
-        /// </summary>
-        protected override TDSMessageCollection OnAuthenticationCompleted(ITDSServerSession session)
-        {
-            // Delegate to the base class
-            TDSMessageCollection responseMessageCollection = base.OnAuthenticationCompleted(session);
-
-            // Check if arguments are of routing server
-            if (Arguments is RoutingTDSServerArguments)
-            {
-                // Cast to routing server arguments
-                RoutingTDSServerArguments serverArguments = Arguments as RoutingTDSServerArguments;
-
-                // Check routing condition
-                if (serverArguments.RouteOnPacket == TDSMessageType.TDS7Login)
-                {
-                    // Construct routing token
-                    TDSPacketToken routingToken = CreateRoutingToken();
-
-                    // Log response
-                    TDSUtilities.Log(Arguments.Log, "Response", routingToken);
-
-                    // Get the first message
-                    TDSMessage targetMessage = responseMessageCollection[0];
-
-                    // Index at which to insert the routing token
-                    int insertIndex = targetMessage.Count - 1;
-
-                    // VSTS# 1021027 - Read-Only Routing yields TDS protocol error
-                    // Resolution: Send TDS FeatureExtAct token before TDS ENVCHANGE token with routing information
-                    TDSPacketToken featureExtAckToken = targetMessage.Find(t => t is TDSFeatureExtAckToken);
-
-                    // Check if found
-                    if (featureExtAckToken != null)
-                    {
-                        // Find token position
-                        insertIndex = targetMessage.IndexOf(featureExtAckToken);
-                    }
-
-                    // Insert right before the done token
-                    targetMessage.Insert(insertIndex, routingToken);
-                }
-            }
-
-            return responseMessageCollection;
-        }
-
-        /// <summary>
-        /// Create a new instance of the routing token that instructs client according to the routing destination URL
-        /// </summary>
-        protected TDSPacketToken CreateRoutingToken()
-        {
-            // Cast to routing server arguments
-            RoutingTDSServerArguments ServerArguments = Arguments as RoutingTDSServerArguments;
-
-            // Construct routing token value
-            TDSRoutingEnvChangeTokenValue routingInfo = new TDSRoutingEnvChangeTokenValue();
-
-            // Read the values and populate routing info
-            routingInfo.Protocol = (TDSRoutingEnvChangeTokenValueType)ServerArguments.RoutingProtocol;
-            routingInfo.ProtocolProperty = ServerArguments.RoutingTCPPort;
-            routingInfo.AlternateServer = ServerArguments.RoutingTCPHost;
-
-            // Construct routing token
-            return new TDSEnvChangeToken(TDSEnvChangeTokenType.Routing, routingInfo);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/RoutingTDSServerArguments.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/RoutingTDSServerArguments.cs
deleted file mode 100644 (file)
index 99cbd3b..0000000
+++ /dev/null
@@ -1,49 +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.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Arguments for routing TDS Server
-    /// </summary>
-    public class RoutingTDSServerArguments : TDSServerArguments
-    {
-        /// <summary>
-        /// Routing destination protocol
-        /// </summary>
-        public int RoutingProtocol { get; set; }
-
-        /// <summary>
-        /// Routing TCP port
-        /// </summary>
-        public ushort RoutingTCPPort { get; set; }
-
-        /// <summary>
-        /// Routing TCP host name
-        /// </summary>
-        public string RoutingTCPHost { get; set; }
-
-        /// <summary>
-        /// Packet on which routing should occur
-        /// </summary>
-        public TDSMessageType RouteOnPacket { get; set; }
-
-        /// <summary>
-        /// Indicates that routing should only occur on read-only connections
-        /// </summary>
-        public bool RequireReadOnly { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public RoutingTDSServerArguments()
-        {
-            // By default we route on login
-            RouteOnPacket = TDSMessageType.TDS7Login;
-
-            // By default we reject non-read-only connections
-            RequireReadOnly = true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/ServerNameFilterType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/ServerNameFilterType.cs
deleted file mode 100644 (file)
index 944b4be..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Type of the filter to apply to server name
-    /// </summary>
-    public enum ServerNameFilterType
-    {
-        /// <summary>
-        /// Do not perform any filtering
-        /// </summary>
-        None,
-
-        /// <summary>
-        /// Values must strictly match
-        /// </summary>
-        Equals,
-
-        /// <summary>
-        /// Value in the login packet starts with the filtering value
-        /// </summary>
-        StartsWith,
-
-        /// <summary>
-        /// Value in the login packet ends with the filtering value
-        /// </summary>
-        EndsWith,
-
-        /// <summary>
-        /// Value in the login packet contains filtering value
-        /// </summary>
-        Contains,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TDS.Servers.csproj b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TDS.Servers.csproj
deleted file mode 100644 (file)
index 75b1eb6..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <RootNamespace>Microsoft.SqlServer.TDS.Servers</RootNamespace>
-    <AssemblyName>Microsoft.SqlServer.TDS.Servers</AssemblyName>
-    <ClsCompliant>false</ClsCompliant>
-    <Configurations>netstandard2.0-Unix-Debug;netstandard2.0-Unix-Release;netstandard2.0-Windows_NT-Debug;netstandard2.0-Windows_NT-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="ApplicationIntentFilterType.cs" />
-    <Compile Include="AuthenticatingTDSServer.cs" />
-    <Compile Include="AuthenticatingTDSServerArguments.cs" />
-    <Compile Include="DateFormatString.cs" />
-    <Compile Include="FederatedAuthenticationNegativeTDSServer.cs" />
-    <Compile Include="FederatedAuthenticationNegativeTDSServerArguments.cs" />
-    <Compile Include="FederatedAuthenticationNegativeTDSScenarioType.cs" />
-    <Compile Include="GenericTDSServer.cs" />
-    <Compile Include="GenericTDSServerSession.cs" />
-    <Compile Include="QueryEngine.cs" />
-    <Compile Include="RoutingTDSServer.cs" />
-    <Compile Include="RoutingTDSServerArguments.cs" />
-    <Compile Include="ServerNameFilterType.cs" />
-    <Compile Include="TDSServerArguments.cs" />
-    <None Include="TdsServerCertificate.pfx">
-      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
-    </None>
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\TDS.EndPoint\TDS.EndPoint.csproj" />
-    <ProjectReference Include="..\TDS\TDS.csproj" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TDSServerArguments.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TDSServerArguments.cs
deleted file mode 100644 (file)
index d47f45a..0000000
+++ /dev/null
@@ -1,97 +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.Security.Cryptography.X509Certificates;
-
-using Microsoft.SqlServer.TDS.PreLogin;
-
-namespace Microsoft.SqlServer.TDS.Servers
-{
-    /// <summary>
-    /// Common arguments for TDS Server
-    /// </summary>
-    public class TDSServerArguments
-    {
-        /// <summary>
-        /// Service Principal Name, representing Azure SQL Database in Azure Active Directory.
-        /// </summary>
-        public const string AzureADServicePrincipalName = @"https://database.windows.net/";
-
-        /// <summary>
-        /// The Azure Active Directory production token endpoint to re-direct the client to fetch a token from.
-        /// </summary>
-        public const string AzureADProductionTokenEndpoint = @"https://login.windows.net/common";
-
-        /// <summary>
-        /// Log to which send TDS conversation
-        /// </summary>
-        public TextWriter Log { get; set; }
-
-        /// <summary>
-        /// Server name
-        /// </summary>
-        public string ServerName { get; set; }
-
-        /// <summary>
-        /// Server version
-        /// </summary>
-        public Version ServerVersion { get; set; }
-
-        /// <summary>
-        /// Server principal name
-        /// </summary>
-        public string ServerPrincipalName { get; set; }
-
-        /// <summary>
-        /// Sts Url
-        /// </summary>
-        public string StsUrl { get; set; }
-
-        /// <summary>
-        /// Size of the TDS packet server should operate with
-        /// </summary>
-        public int PacketSize { get; set; }
-
-        /// <summary>
-        /// Transport encryption
-        /// </summary>
-        public TDSPreLoginTokenEncryptionType Encryption { get; set; }
-
-        /// <summary>
-        /// Specifies the FedAuthRequired option
-        /// </summary>
-        public TdsPreLoginFedAuthRequiredOption FedAuthRequiredPreLoginOption { get; set; }
-
-        /// <summary>
-        /// Certificate to use for transport encryption
-        /// </summary>
-        public X509Certificate EncryptionCertificate { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSServerArguments()
-        {
-            // Assign default server version
-            ServerName = Environment.MachineName;
-            ServerVersion = new Version(11, 0, 1083);
-
-            // Default packet size
-            PacketSize = 4096;
-
-            // By default we don't support encryption
-            Encryption = TDSPreLoginTokenEncryptionType.NotSupported;
-
-            // By Default SQL authentication will be used.
-            FedAuthRequiredPreLoginOption = TdsPreLoginFedAuthRequiredOption.FedAuthNotRequired;
-
-            EncryptionCertificate = new X509Certificate2("TdsServerCertificate.pfx", "SecretPassword123456");
-
-            ServerPrincipalName = AzureADServicePrincipalName;
-            StsUrl = AzureADProductionTokenEndpoint;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TdsServerCertificate.pfx b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TdsServerCertificate.pfx
deleted file mode 100644 (file)
index a5c48e2..0000000
Binary files a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS.Servers/TdsServerCertificate.pfx and /dev/null differ
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSAllHeaders.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSAllHeaders.cs
deleted file mode 100644 (file)
index b093312..0000000
+++ /dev/null
@@ -1,135 +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.IO;
-using System.Linq;
-
-namespace Microsoft.SqlServer.TDS.AllHeaders
-{
-    /// <summary>
-    /// Token that handles ALL_HEADERS rule
-    /// </summary>
-    public class TDSAllHeadersToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Collection of individual headers
-        /// </summary>
-        public IList<TDSPacketToken> Headers { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSAllHeadersToken()
-        {
-            Headers = new List<TDSPacketToken>();
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        public override bool Inflate(Stream source)
-        {
-            // Allocate headers
-            Headers = new List<TDSPacketToken>();
-
-            // Read total length
-            uint totalLength = TDSUtilities.ReadUInt(source);
-
-            // Take total length DWORD into account
-            totalLength -= 4;
-
-            // Keep reading the stream until we inflate all headers
-            while (totalLength > 0)
-            {
-                // Read header length
-                uint headerLength = TDSUtilities.ReadUInt(source);
-
-                // Update total length before we start modifying it
-                totalLength -= headerLength;
-
-                // Take header length DWORD into account
-                headerLength -= 4;
-
-                // Check if header length allows header type
-                if (headerLength >= 2)
-                {
-                    // Read header type
-                    TDSHeaderType type = (TDSHeaderType)TDSUtilities.ReadUShort(source);
-
-                    // Take header type into account
-                    headerLength -= 2;
-
-                    // Based on the header type inflate the header
-                    switch (type)
-                    {
-                        case TDSHeaderType.QueryNotifications:
-                            {
-                                // Create instance
-                                Headers.Add(new TDSQueryNotificationsHeader());
-                                break;
-                            }
-                        case TDSHeaderType.TransactionDescriptor:
-                            {
-                                // Create instance
-                                Headers.Add(new TDSTransactionDescriptorHeader());
-                                break;
-                            }
-                        case TDSHeaderType.Trace:
-                            {
-                                // Create instance
-                                Headers.Add(new TDSTraceHeader());
-                                break;
-                            }
-                        default:
-                            {
-                                // We don't know this token
-                                throw new ArgumentException("Unrecognized header type", "Header Type");
-                            }
-                    }
-
-                    // Inflate the last header
-                    if (!Headers.Last().Inflate(source))
-                    {
-                        // We failed to inflate this token so we can't proceed
-                        throw new Exception(string.Format("Failed to inflate header \"{0}\"", type));
-                    }
-                }
-            }
-
-            // We're done inflating
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Allocate temporary cache
-            MemoryStream cache = new MemoryStream();
-
-            // Check if headers are available
-            if (Headers != null)
-            {
-                // Iterate through all headers
-                foreach (TDSPacketToken header in Headers)
-                {
-                    // Deflate header into the cache
-                    header.Deflate(cache);
-                }
-            }
-
-            // Write the total length of cache including self into the destination
-            TDSUtilities.WriteUInt(destination, (uint)(cache.Length + 4));
-
-            // Seriaize the cache
-            cache.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSHeaderType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSHeaderType.cs
deleted file mode 100644 (file)
index 6203c07..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.AllHeaders
-{
-    /// <summary>
-    /// Type of the individual header
-    /// </summary>
-    public enum TDSHeaderType : ushort
-    {
-        QueryNotifications = 0x0001,
-        TransactionDescriptor = 0x0002,
-        Trace = 0x0003
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSQueryNotificationsHeader.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSQueryNotificationsHeader.cs
deleted file mode 100644 (file)
index 5b8e81a..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.AllHeaders
-{
-    /// <summary>
-    /// Represents Query Notifications header of ALL_HEADERS token
-    /// </summary>
-    public class TDSQueryNotificationsHeader : TDSPacketToken
-    {
-        /// <summary>
-        /// User specified value when subscribing to the query notification
-        /// </summary>
-        public string NotifyID { get; set; }
-
-        /// <summary>
-        /// Service Broker Deployment
-        /// </summary>
-        public string SerciceBrokerDeployment { get; set; }
-
-        /// <summary>
-        /// Notification timeout
-        /// </summary>
-        public uint Timeout { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSQueryNotificationsHeader()
-        {
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        public override bool Inflate(Stream source)
-        {
-            // Read the length of the notification ID
-            ushort length = TDSUtilities.ReadUShort(source);
-
-            // Read notification ID string
-            NotifyID = TDSUtilities.ReadString(source, length);
-
-            // Read the length of the service broker deployment
-            length = TDSUtilities.ReadUShort(source);
-
-            // Read service broker deployment string
-            SerciceBrokerDeployment = TDSUtilities.ReadString(source, length);
-
-            // Read query notification timeout
-            Timeout = TDSUtilities.ReadUInt(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Allocate temporary cache
-            MemoryStream cache = new MemoryStream();
-
-            // Write header type
-            TDSUtilities.WriteUShort(cache, (ushort)TDSHeaderType.QueryNotifications);
-
-            // Write notification ID string
-            TDSUtilities.WriteUShort(cache, (ushort)(string.IsNullOrEmpty(NotifyID) ? 0 : NotifyID.Length));
-            TDSUtilities.WriteString(cache, NotifyID);
-
-            // Write service broker deployment
-            TDSUtilities.WriteUShort(cache, (ushort)(string.IsNullOrEmpty(SerciceBrokerDeployment) ? 0 : SerciceBrokerDeployment.Length));
-            TDSUtilities.WriteString(cache, SerciceBrokerDeployment);
-
-            // Write timeout
-            TDSUtilities.WriteUInt(cache, Timeout);
-
-            // Write the header length including self into the destination
-            TDSUtilities.WriteUInt(destination, (uint)(cache.Length + 4));
-
-            // Write cached header data
-            cache.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSTraceHeader.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSTraceHeader.cs
deleted file mode 100644 (file)
index 3688e04..0000000
+++ /dev/null
@@ -1,89 +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;
-
-namespace Microsoft.SqlServer.TDS.AllHeaders
-{
-    /// <summary>
-    /// Represents correlate activity ID trace header of ALL_HEADERS token
-    /// </summary>
-    public class TDSTraceHeader : TDSPacketToken
-    {
-        /// <summary>
-        /// Identifier of the client activity
-        /// </summary>
-        public Guid ActivityID { get; set; }
-
-        /// <summary>
-        /// Sequential number of the operation
-        /// </summary>
-        public uint SequenceNumber { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSTraceHeader()
-        {
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        public override bool Inflate(Stream source)
-        {
-            byte[] guidBytes = new byte[16];
-
-            // Read exactly the size of GUID bytes
-            if (source.Read(guidBytes, 0, guidBytes.Length) != guidBytes.Length)
-            {
-                throw new Exception("Failed to read trace GUID");
-            }
-
-            // Inflate trace identifier
-            ActivityID = new Guid(guidBytes);
-
-            // Read activity identifier
-            SequenceNumber = TDSUtilities.ReadUInt(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Allocate temporary cache
-            MemoryStream cache = new MemoryStream();
-
-            // Write header type
-            TDSUtilities.WriteUShort(cache, (ushort)TDSHeaderType.Trace);
-
-            byte[] guidBytes = new byte[16];
-
-            // Check if activity ID is available
-            if (ActivityID != Guid.Empty)
-            {
-                guidBytes = ActivityID.ToByteArray();
-            }
-
-            // Write trace identifier
-            cache.Write(guidBytes, 0, guidBytes.Length);
-
-            // Write activity identifier
-            TDSUtilities.WriteUInt(cache, SequenceNumber);
-
-            // Write the header length including self into the destination
-            TDSUtilities.WriteUInt(destination, (uint)(cache.Length + 4));
-
-            // Write cached header data
-            cache.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSTransactionDescriptorHeader.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AllHeaders/TDSTransactionDescriptorHeader.cs
deleted file mode 100644 (file)
index b51b1ac..0000000
+++ /dev/null
@@ -1,89 +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;
-
-namespace Microsoft.SqlServer.TDS.AllHeaders
-{
-    /// <summary>
-    /// Represents Transaction Descriptor header of ALL_HEADERS token
-    /// </summary>
-    public class TDSTransactionDescriptorHeader : TDSPacketToken
-    {
-        /// <summary>
-        /// Identifier of the transaction
-        /// </summary>
-        public ulong TransactionDescriptor { get; set; }
-
-        /// <summary>
-        /// Outstanding request count
-        /// </summary>
-        public uint OutstandingRequestCount { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSTransactionDescriptorHeader()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSTransactionDescriptorHeader(ulong transactionDescriptor)
-        {
-            TransactionDescriptor = transactionDescriptor;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSTransactionDescriptorHeader(ulong transactionDescriptor, uint outstandingRequestCount)
-        {
-            TransactionDescriptor = transactionDescriptor;
-            OutstandingRequestCount = outstandingRequestCount;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        public override bool Inflate(Stream source)
-        {
-            // Read transaction descriptor
-            TransactionDescriptor = TDSUtilities.ReadULong(source);
-
-            // Read outstanding request count
-            OutstandingRequestCount = TDSUtilities.ReadUInt(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Allocate temporary cache
-            MemoryStream cache = new MemoryStream();
-
-            // Write header type
-            TDSUtilities.WriteUShort(cache, (ushort)TDSHeaderType.TransactionDescriptor);
-
-            // Write transaction descriptor
-            TDSUtilities.WriteULong(cache, TransactionDescriptor);
-
-            // Write outstanding request count
-            TDSUtilities.WriteUInt(cache, OutstandingRequestCount);
-
-            // Write the header length including self into the destination
-            TDSUtilities.WriteUInt(destination, (uint)(cache.Length + 4));
-
-            // Write cached header data
-            cache.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AutoTDSStream.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/AutoTDSStream.cs
deleted file mode 100644 (file)
index 7a1f2c8..0000000
+++ /dev/null
@@ -1,171 +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.Text;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Stream that wraps TDS stream with automatic dispatch
-    /// </summary>
-    public class AutoTDSStream : Stream
-    {
-        /// <summary>
-        /// Indicates whether inner stream should be closed when TDS stream is closed
-        /// </summary>
-        private bool _closeInnerStream = false;
-
-        /// <summary>
-        /// Inner TDS stream
-        /// </summary>
-        public TDSStream InnerTDSStream { get; set; }
-
-        /// <summary>
-        /// Type of the message being sent to the other party
-        /// </summary>
-        public TDSMessageType OutgoingMessageType { get; set; }
-
-        /// <summary>
-        /// Indicates whether stream can be read
-        /// </summary>
-        public override bool CanRead
-        {
-            // Delegate to the inner stream
-            get { return InnerTDSStream.CanRead; }
-        }
-
-        /// <summary>
-        /// Indicates whether the stream can be positioned
-        /// </summary>
-        public override bool CanSeek
-        {
-            // Delegate to the inner stream
-            get { return InnerTDSStream.CanSeek; }
-        }
-
-        /// <summary>
-        /// Indicates whether the stream can be written
-        /// </summary>
-        public override bool CanWrite
-        {
-            // Delegate to the inner stream
-            get { return InnerTDSStream.CanWrite; }
-        }
-
-        /// <summary>
-        /// Return the length of the stream
-        /// </summary>
-        public override long Length
-        {
-            // Delegate to the inner stream
-            get { return InnerTDSStream.Length; }
-        }
-
-        /// <summary>
-        /// Return position in the stream
-        /// </summary>
-        public override long Position
-        {
-            // Delegate to the inner stream
-            get { return InnerTDSStream.Position; }
-            set { InnerTDSStream.Position = value; }
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public AutoTDSStream(TDSStream innerTDSStream) :
-            this(innerTDSStream, true)
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public AutoTDSStream(TDSStream innerTDSStream, bool closeInnerStream)
-        {
-            // Check if inner stream is valid
-            if (innerTDSStream == null)
-            {
-                // We can't proceed without underlying stream
-                throw new ArgumentNullException(nameof(innerTDSStream), "Underlying TDS stream is required");
-            }
-
-            // Save transport stream
-            InnerTDSStream = innerTDSStream;
-
-            // Save whether inner stream is to be closed as well
-            _closeInnerStream = closeInnerStream;
-        }
-
-        /// <summary>
-        /// Close the stream
-        /// </summary>
-        public override void Close()
-        {
-            // Check if inner stream needs to be closed
-            if (_closeInnerStream)
-            {
-                // Close inner stream
-                InnerTDSStream.Close();
-            }
-
-            // Delegate to the base class
-            base.Close();
-        }
-
-        /// <summary>
-        /// Flush the data into the underlying stream
-        /// </summary>
-        public override void Flush()
-        {
-            // Delegate to the inner stream
-            InnerTDSStream.Flush();
-        }
-
-        /// <summary>
-        /// Read the data from the stream
-        /// </summary>
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            // Delegate to the underlying stream
-            return InnerTDSStream.Read(buffer, offset, count);
-        }
-
-        /// <summary>
-        /// Seek position in the stream
-        /// </summary>
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            // Delegate to the inner stream
-            return InnerTDSStream.Seek(offset, origin);
-        }
-
-        /// <summary>
-        /// Set stream length
-        /// </summary>
-        public override void SetLength(long value)
-        {
-            // Delegate to the inner stream
-            InnerTDSStream.SetLength(value);
-        }
-
-        /// <summary>
-        /// Write data into the stream
-        /// </summary>
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            // Start a new TDS message
-            InnerTDSStream.StartMessage(OutgoingMessageType);
-
-            // Delegate to the inner TDS stream
-            InnerTDSStream.Write(buffer, offset, count);
-
-            // Complete this message
-            InnerTDSStream.EndMessage();
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColInfoToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColInfoToken.cs
deleted file mode 100644 (file)
index ba1e8ac..0000000
+++ /dev/null
@@ -1,90 +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.Generic;
-using System.IO;
-
-namespace Microsoft.SqlServer.TDS.ColInfo
-{
-    /// <summary>
-    /// Result set metadata description "COLINFO" token
-    /// </summary>
-    public class TDSColInfoToken : TDSPacketToken
-    {
-        /// <summary>
-        /// A collection of columns for which metadata is available
-        /// </summary>
-        public IList<TDSColumnProperty> Columns { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSColInfoToken()
-        {
-            // Prepare collection
-            Columns = new List<TDSColumnProperty>();
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Re-prepare collection
-            Columns = new List<TDSColumnProperty>();
-
-            // Read the length of the data
-            ushort length = TDSUtilities.ReadUShort(source);
-
-            // Current offset in the stream
-            ushort offset = 0;
-
-            // Inflate each property
-            while (offset < length)
-            {
-                // Allocate a new property
-                TDSColumnProperty newColumn = new TDSColumnProperty();
-
-                // Inflate
-                newColumn.Inflate(source);
-
-                // Register with the collection
-                Columns.Add(newColumn);
-
-                // Update offset with the size of the last inflated property
-                offset += (ushort)newColumn.InflationSize;
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.ColumnInfo);
-
-            // Allocate a memory stream for column information block
-            MemoryStream cache = new MemoryStream();
-
-            // Deflate all properties into the cache
-            foreach (TDSColumnProperty column in Columns)
-            {
-                column.Deflate(cache);
-            }
-
-            // Write the length of the token
-            TDSUtilities.WriteUShort(destination, (ushort)cache.Length);
-
-            // Write the cache itself
-            cache.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColumnProperty.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColumnProperty.cs
deleted file mode 100644 (file)
index 8e96530..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.ColInfo
-{
-    /// <summary>
-    /// Information about a single column
-    /// </summary>
-    public class TDSColumnProperty : IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// Number of bytes processed from the stream during inflation
-        /// </summary>
-        internal int InflationSize { get; private set; }
-
-        /// <summary>
-        /// Number of the column in the result
-        /// </summary>
-        public byte Number { get; set; }
-
-        /// <summary>
-        /// Number of the table
-        /// </summary>
-        public byte TableNumber { get; set; }
-
-        /// <summary>
-        /// Status
-        /// </summary>
-        public TDSColumnStatus Status { get; set; }
-
-        /// <summary>
-        /// Name of the column
-        /// </summary>
-        public string Name { get; set; }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public virtual bool Inflate(Stream source)
-        {
-            // Read column number
-            Number = (byte)source.ReadByte();
-
-            // Update offset with the read size
-            InflationSize += sizeof(byte);
-
-            // Read table number
-            TableNumber = (byte)source.ReadByte();
-
-            // Update offset with the read size
-            InflationSize += sizeof(byte);
-
-            // Read status
-            Status = (TDSColumnStatus)source.ReadByte();
-
-            // Update offset with the read size
-            InflationSize += sizeof(byte);
-
-            // Check if status indicates the table name
-            if ((Status & TDSColumnStatus.DifferentName) != 0)
-            {
-                // Read the length of the table name
-                byte tableNameLength = (byte)source.ReadByte();
-
-                // Read table name
-                Name = TDSUtilities.ReadString(source, (ushort)(tableNameLength * 2));
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public virtual void Deflate(Stream destination)
-        {
-            // Write column number
-            destination.WriteByte(Number);
-
-            // Write table number
-            destination.WriteByte(TableNumber);
-
-            // Write status number
-            destination.WriteByte((byte)Status);
-
-            // Check if we have a name
-            if (Name != null)
-            {
-                // Write length
-                destination.WriteByte((byte)Name.Length);
-
-                // Write data
-                TDSUtilities.WriteString(destination, Name);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColumnStatus.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColInfo/TDSColumnStatus.cs
deleted file mode 100644 (file)
index 58cee36..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.TDS.ColInfo
-{
-    /// <summary>
-    /// Status of the column
-    /// </summary>
-    [Flags]
-    public enum TDSColumnStatus : byte
-    {
-        /// <summary>
-        /// The column was the result of an expression
-        /// </summary>
-        Expression = 0x04,
-
-        /// <summary>
-        /// The column is part of a key for the associated table
-        /// </summary>
-        Key = 0x08,
-
-        /// <summary>
-        /// The column was not requested, but was added because it was part of a key for the associated table
-        /// </summary>
-        Hidden = 0x10,
-
-        /// <summary>
-        /// the column name is different than the requested column name in the case of a column alias
-        /// </summary>
-        DifferentName = 0x20
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColMetadataToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColMetadataToken.cs
deleted file mode 100644 (file)
index c5329ac..0000000
+++ /dev/null
@@ -1,95 +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.Generic;
-using System.IO;
-
-namespace Microsoft.SqlServer.TDS.ColMetadata
-{
-    /// <summary>
-    /// Result set metadata description "COLMETADATA" token
-    /// </summary>
-    public class TDSColMetadataToken : TDSPacketToken
-    {
-        /// <summary>
-        /// A collection of columns for which metadata is available
-        /// </summary>
-        public IList<TDSColumnData> Columns { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSColMetadataToken()
-        {
-            // Prepare collection
-            Columns = new List<TDSColumnData>();
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read column count
-            ushort count = TDSUtilities.ReadUShort(source);
-
-            // Check if count indicates that no columns are available
-            if (count == 0xFFFF)
-            {
-                // We're done
-                return true;
-            }
-
-            // Allocate new collection
-            Columns = new List<TDSColumnData>();
-
-            // Inflate each column
-            for (ushort usIndex = 0; usIndex < count; usIndex++)
-            {
-                // Create a new column data
-                TDSColumnData data = new TDSColumnData();
-
-                // Inflate
-                data.Inflate(source);
-
-                // Register data with the collection
-                Columns.Add(data);
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.ColumnMetadata);
-
-            // Check if there's any metadata
-            if (Columns != null && Columns.Count > 0)
-            {
-                // Write column count
-                TDSUtilities.WriteUShort(destination, (ushort)Columns.Count);
-
-                // Iterate through each column and deflate it
-                foreach (TDSColumnData column in Columns)
-                {
-                    // Deflate each column
-                    column.Deflate(destination);
-                }
-            }
-            else
-            {
-                // Indicate that there's no metadata
-                TDSUtilities.WriteUShort(destination, (ushort)0xFFFF);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnData.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnData.cs
deleted file mode 100644 (file)
index 0071261..0000000
+++ /dev/null
@@ -1,334 +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.Generic;
-using System.IO;
-
-namespace Microsoft.SqlServer.TDS.ColMetadata
-{
-    /// <summary>
-    /// Class that describes metadata of a single column
-    /// </summary>
-    public class TDSColumnData : IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// User type ID of the data type of the column
-        /// </summary>
-        public uint UserType { get; set; }
-
-        /// <summary>
-        /// Type of the data
-        /// </summary>
-        public TDSDataType DataType { get; set; }
-
-        /// <summary>
-        /// Information specific to the data type
-        /// </summary>
-        public object DataTypeSpecific { get; set; }
-
-        /// <summary>
-        /// Column metadata flags
-        /// </summary>
-        public TDSColumnDataFlags Flags { get; set; }
-
-        /// <summary>
-        /// Fully qualified base table name for the column
-        /// </summary>
-        public IList<string> TableName { get; set; }
-
-        /// <summary>
-        /// Name of the column
-        /// </summary>
-        public string Name { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSColumnData()
-        {
-            // Create flags
-            Flags = new TDSColumnDataFlags();
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public bool Inflate(Stream source)
-        {
-            // Read user type
-            UserType = TDSUtilities.ReadUInt(source);
-
-            // Read flags
-            Flags = new TDSColumnDataFlags(TDSUtilities.ReadUShort(source));
-
-            // Read server type
-            DataType = (TDSDataType)source.ReadByte();
-
-            // Dispatch further reading based on the type
-            switch (DataType)
-            {
-                case TDSDataType.Binary:
-                case TDSDataType.VarBinary:
-                case TDSDataType.Char:
-                case TDSDataType.VarChar:
-                // The above types are deprecated after TDS 7205.
-
-                case TDSDataType.BitN:
-                case TDSDataType.Guid:
-                case TDSDataType.IntN:
-                case TDSDataType.MoneyN:
-                case TDSDataType.FloatN:
-                case TDSDataType.DateTimeN:
-                    {
-                        // Byte length
-                        DataTypeSpecific = source.ReadByte();
-                        break;
-                    }
-                case TDSDataType.DateN:
-                    {
-                        // No details
-                        DataTypeSpecific = null;
-                        break;
-                    }
-                case TDSDataType.TimeN:
-                case TDSDataType.DateTime2N:
-                case TDSDataType.DateTimeOffsetN:
-                    {
-                        // Scale
-                        DataTypeSpecific = source.ReadByte();
-                        break;
-                    }
-                case TDSDataType.DecimalN:
-                case TDSDataType.NumericN:
-                    {
-                        // Read values
-                        byte length = (byte)source.ReadByte();
-                        byte precision = (byte)source.ReadByte();
-                        byte scale = (byte)source.ReadByte();
-
-                        // Decimal data type specific
-                        DataTypeSpecific = new TDSDecimalColumnSpecific(length, precision, scale);
-                        break;
-                    }
-                case TDSDataType.BigBinary:
-                case TDSDataType.BigVarBinary:
-                    {
-                        // Short length
-                        DataTypeSpecific = TDSUtilities.ReadUShort(source);
-                        break;
-                    }
-                case TDSDataType.BigChar:
-                case TDSDataType.BigVarChar:
-                case TDSDataType.NChar:
-                case TDSDataType.NVarChar:
-                    {
-                        // SHILOH CHAR types have collation associated with it.
-                        TDSShilohVarCharColumnSpecific typedSpecific = new TDSShilohVarCharColumnSpecific();
-
-                        // Read length
-                        typedSpecific.Length = TDSUtilities.ReadUShort(source);
-
-                        // Create collation
-                        typedSpecific.Collation = new TDSColumnDataCollation();
-
-                        // Read collation
-                        typedSpecific.Collation.WCID = TDSUtilities.ReadUInt(source);
-                        typedSpecific.Collation.SortID = (byte)source.ReadByte();
-
-                        DataTypeSpecific = typedSpecific;
-                        break;
-                    }
-                case TDSDataType.Text:
-                case TDSDataType.NText:
-                    {
-                        // YukonTextType.Len + YukonTextType.tdsCollationInfo + YukonTextType.cParts
-                        // cb = sizeof(LONG) + sizeof(TDSCOLLATION) + sizeof(BYTE);
-                        break;
-                    }
-                case TDSDataType.Image:
-                    {
-                        // Data length
-                        DataTypeSpecific = TDSUtilities.ReadUInt(source);
-                        break;
-                    }
-                case TDSDataType.SSVariant:
-                    {
-                        // Data length
-                        DataTypeSpecific = TDSUtilities.ReadUInt(source);
-                        break;
-                    }
-                case TDSDataType.Udt:
-                    {
-                        // hr = GetUDTColFmt(pvOwner, dwTimeout);
-                        break;
-                    }
-                case TDSDataType.Xml:
-                    {
-                        // cb = sizeof(lpColFmt->YukonXmlType.bSchemaPresent);
-                        break;
-                    }
-            }
-
-            // Check if table name is available
-            if (DataType == TDSDataType.Text || DataType == TDSDataType.NText || DataType == TDSDataType.Image)
-            {
-                // Allocate table name container
-                TableName = new List<string>();
-
-                // Read part count
-                byte partCount = (byte)source.ReadByte();
-
-                // Write each part
-                for (byte bPart = 0; bPart < partCount; bPart++)
-                {
-                    // Read table part length and value
-                    TableName.Add(TDSUtilities.ReadString(source, (ushort)(TDSUtilities.ReadUShort(source) * 2)));
-                }
-            }
-
-            // Read column name
-            Name = TDSUtilities.ReadString(source, (ushort)(source.ReadByte() * 2));
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public void Deflate(Stream destination)
-        {
-            // Write user type
-            TDSUtilities.WriteUInt(destination, UserType);
-
-            // Convert flags to value and write them
-            TDSUtilities.WriteUShort(destination, Flags.ToUShort());
-
-            // Write type
-            destination.WriteByte((byte)DataType);
-
-            // Dispatch further writing based on the type
-            switch (DataType)
-            {
-                case TDSDataType.Binary:
-                case TDSDataType.VarBinary:
-                case TDSDataType.Char:
-                case TDSDataType.VarChar:
-                case TDSDataType.BitN:
-                case TDSDataType.Guid:
-                case TDSDataType.IntN:
-                case TDSDataType.MoneyN:
-                case TDSDataType.FloatN:
-                case TDSDataType.DateTimeN:
-                    {
-                        // Byte length
-                        destination.WriteByte((byte)DataTypeSpecific);
-                        break;
-                    }
-                case TDSDataType.DateN:
-                    {
-                        // No details
-                        break;
-                    }
-                case TDSDataType.TimeN:
-                case TDSDataType.DateTime2N:
-                case TDSDataType.DateTimeOffsetN:
-                    {
-                        // Scale
-                        destination.WriteByte((byte)DataTypeSpecific);
-                        break;
-                    }
-                case TDSDataType.DecimalN:
-                case TDSDataType.NumericN:
-                    {
-                        // Cast to type-specific information
-                        TDSDecimalColumnSpecific typeSpecific = DataTypeSpecific as TDSDecimalColumnSpecific;
-
-                        // Write values
-                        destination.WriteByte(typeSpecific.Length);
-                        destination.WriteByte(typeSpecific.Precision);
-                        destination.WriteByte(typeSpecific.Scale);
-                        break;
-                    }
-                case TDSDataType.BigBinary:
-                case TDSDataType.BigVarBinary:
-                    {
-                        // Short length
-                        TDSUtilities.WriteUShort(destination, (ushort)DataTypeSpecific);
-                        break;
-                    }
-                case TDSDataType.BigChar:
-                case TDSDataType.BigVarChar:
-                case TDSDataType.NChar:
-                case TDSDataType.NVarChar:
-                    {
-                        // Cast to type specific information
-                        TDSShilohVarCharColumnSpecific typedSpecific = DataTypeSpecific as TDSShilohVarCharColumnSpecific;
-
-                        // Write length
-                        TDSUtilities.WriteUShort(destination, typedSpecific.Length);
-
-                        // Write collation
-                        TDSUtilities.WriteUInt(destination, typedSpecific.Collation.WCID);
-                        destination.WriteByte(typedSpecific.Collation.SortID);
-                        break;
-                    }
-                case TDSDataType.Text:
-                case TDSDataType.NText:
-                    {
-                        // YukonTextType.Len + YukonTextType.tdsCollationInfo + YukonTextType.cParts
-                        // cb = sizeof(LONG) + sizeof(TDSCOLLATION) + sizeof(BYTE);
-                        break;
-                    }
-                case TDSDataType.Image:
-                    {
-                        // Integer length
-                        TDSUtilities.WriteUInt(destination, (uint)DataTypeSpecific);
-                        break;
-                    }
-                case TDSDataType.SSVariant:
-                    {
-                        // Data length
-                        TDSUtilities.WriteUInt(destination, (uint)DataTypeSpecific);
-                        break;
-                    }
-                case TDSDataType.Udt:
-                    {
-                        // hr = GetUDTColFmt(pvOwner, dwTimeout);
-                        break;
-                    }
-                case TDSDataType.Xml:
-                    {
-                        // cb = sizeof(lpColFmt->YukonXmlType.bSchemaPresent);
-                        break;
-                    }
-            }
-
-            // Check if we need to write table name
-            if ((DataType == TDSDataType.Text || DataType == TDSDataType.NText || DataType == TDSDataType.Image) && (TableName != null))
-            {
-                // Write part count
-                destination.WriteByte((byte)TableName.Count);
-
-                // Write each part
-                foreach (string part in TableName)
-                {
-                    // Write table part length
-                    TDSUtilities.WriteUShort(destination, (ushort)(string.IsNullOrEmpty(part) ? 0 : part.Length));
-
-                    // Write table part
-                    TDSUtilities.WriteString(destination, part);
-                }
-            }
-
-            // Write column name length
-            destination.WriteByte((byte)(string.IsNullOrEmpty(Name) ? 0 : Name.Length));
-
-            // Write column name
-            TDSUtilities.WriteString(destination, Name);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataCollation.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataCollation.cs
deleted file mode 100644 (file)
index 891d827..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.ColMetadata
-{
-    /// <summary>
-    /// Collation associated with TDS column
-    /// </summary>
-    public class TDSColumnDataCollation
-    {
-        /// <summary>
-        /// I have no clue what this stands for
-        /// </summary>
-        public uint WCID { get; set; }
-
-        /// <summary>
-        /// Sort identifier
-        /// </summary>
-        public byte SortID { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSColumnDataCollation()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSColumnDataCollation(uint wcid)
-        {
-            WCID = wcid;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSColumnDataCollation(uint wcid, byte sortID)
-        {
-            WCID = wcid;
-            SortID = sortID;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataFlags.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataFlags.cs
deleted file mode 100644 (file)
index e444372..0000000
+++ /dev/null
@@ -1,119 +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.SqlServer.TDS.ColMetadata
-{
-    /// <summary>
-    /// Column data flags
-    /// </summary>
-    public class TDSColumnDataFlags
-    {
-        /// <summary>
-        /// Indicates that the column is case-sensitive
-        /// </summary>
-        public bool IsCaseSensitive { get; set; }
-
-        /// <summary>
-        /// Indicates that the column is nullable
-        /// </summary>
-        public bool IsNullable { get; set; }
-
-        /// <summary>
-        /// Indicates that the column updatability
-        /// </summary>
-        public TDSColumnDataUpdatableFlag Updatable { get; set; }
-
-        /// <summary>
-        /// Indicates that the column is identity
-        /// </summary>
-        public bool IsIdentity { get; set; }
-
-        /// <summary>
-        /// Indicates that the column is computed
-        /// </summary>
-        public bool IsComputed { get; set; }
-
-        /// <summary>
-        /// Reserved by ODS gateway supporting ODBC
-        /// </summary>
-        public byte ReservedODBC { get; set; }
-
-        /// <summary>
-        /// Indicates that the column is a fixed length CLR type
-        /// </summary>
-        public bool IsFixedLengthCLR { get; set; }
-
-        /// <summary>
-        /// Indicates that all values in the column are default used for TVP
-        /// </summary>
-        public bool IsDefault { get; set; }
-
-        /// <summary>
-        /// Indicates that the column sparse
-        /// </summary>
-        public bool IsSparseColumnSet { get; set; }
-
-        /// <summary>
-        /// Indicates that the column is part of the hidden key
-        /// </summary>
-        public bool IsHidden { get; set; }
-
-        /// <summary>
-        /// Indicates that the column is part of the primary key
-        /// </summary>
-        public bool IsKey { get; set; }
-
-        /// <summary>
-        /// Indicates that the column nullability is unknown
-        /// </summary>
-        public bool IsNullableUnknown { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSColumnDataFlags()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="flags">Flags to parse</param>
-        public TDSColumnDataFlags(ushort flags)
-        {
-            // Extract flags per TDS specification, section 2.2.7.4
-            IsNullable = ((flags & 0x1) != 0);
-            IsCaseSensitive = (((flags >> 1) & 0x1) != 0);
-            Updatable = (TDSColumnDataUpdatableFlag)((flags >> 2) & 0x3);
-            IsIdentity = (((flags >> 4) & 0x1) != 0);
-            IsComputed = (((flags >> 5) & 0x1) != 0);
-            ReservedODBC = (byte)((flags >> 6) & 0x3);
-            IsFixedLengthCLR = (((flags >> 8) & 0x1) != 0);
-            IsDefault = (((flags >> 9) & 0x1) != 0);
-            IsSparseColumnSet = (((flags >> 10) & 0x1) != 0);
-            IsHidden = (((flags >> 13) & 0x1) != 0);
-            IsKey = (((flags >> 14) & 0x1) != 0);
-            IsNullableUnknown = (((flags >> 15) & 0x1) != 0);
-        }
-
-        /// <summary>
-        /// Serialize flags back into a value
-        /// </summary>
-        public ushort ToUShort()
-        {
-            return (ushort)(((ushort)(IsNullable ? 0x1 : 0x0))
-                | ((ushort)(IsCaseSensitive ? 0x1 : 0x0)) << 1
-                | ((ushort)Updatable) << 2
-                | ((ushort)(IsIdentity ? 0x1 : 0x0)) << 4
-                | ((ushort)(IsComputed ? 0x1 : 0x0)) << 5
-                | ((ushort)ReservedODBC) << 6
-                | ((ushort)(IsFixedLengthCLR ? 0x1 : 0x0)) << 8
-                | ((ushort)(IsDefault ? 0x1 : 0x0)) << 9
-                | ((ushort)(IsHidden ? 0x1 : 0x0)) << 10
-                | ((ushort)(IsSparseColumnSet ? 0x1 : 0x0)) << 13
-                | ((ushort)(IsKey ? 0x1 : 0x0)) << 14
-                | ((ushort)(IsNullableUnknown ? 0x1 : 0x0)) << 15);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataUpdatableFlag.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSColumnDataUpdatableFlag.cs
deleted file mode 100644 (file)
index a938e1f..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.ColMetadata
-{
-    /// <summary>
-    /// Indicates type of updatability of the column
-    /// </summary>
-    public enum TDSColumnDataUpdatableFlag : byte
-    {
-        ReadOnly = 0,
-        ReadWrite = 1,
-        Unknown = 2
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSDecimalColumnSpecific.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSDecimalColumnSpecific.cs
deleted file mode 100644 (file)
index dac8bc6..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.ColMetadata
-{
-    /// <summary>
-    /// Metadata associated with decimal/numeric column
-    /// </summary>
-    public class TDSDecimalColumnSpecific
-    {
-        /// <summary>
-        /// Length of the data
-        /// </summary>
-        public byte Length { get; set; }
-
-        /// <summary>
-        /// Precision of the data
-        /// </summary>
-        public byte Precision { get; set; }
-
-        /// <summary>
-        /// Scale of the data
-        /// </summary>
-        public byte Scale { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSDecimalColumnSpecific()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDecimalColumnSpecific(byte length)
-        {
-            Length = length;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDecimalColumnSpecific(byte length, byte precision)
-        {
-            Length = length;
-            Precision = precision;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDecimalColumnSpecific(byte length, byte precision, byte scale)
-        {
-            Length = length;
-            Precision = precision;
-            Scale = scale;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSShilohVarCharColumnSpecific.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ColMetadata/TDSShilohVarCharColumnSpecific.cs
deleted file mode 100644 (file)
index 4947083..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.ColMetadata
-{
-    /// <summary>
-    /// Metadata associated with Shiloh variable character column
-    /// </summary>
-    public class TDSShilohVarCharColumnSpecific
-    {
-        /// <summary>
-        /// Length of the data
-        /// </summary>
-        public ushort Length { get; set; }
-
-        /// <summary>
-        /// Collation
-        /// </summary>
-        public TDSColumnDataCollation Collation { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSShilohVarCharColumnSpecific()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSShilohVarCharColumnSpecific(ushort length)
-        {
-            Length = length;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSShilohVarCharColumnSpecific(ushort length, TDSColumnDataCollation collation)
-        {
-            Length = length;
-            Collation = collation;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Configurations.props b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Configurations.props
deleted file mode 100644 (file)
index 69f0b7d..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-<Project DefaultTargets="Build">
-  <PropertyGroup>
-    <BuildConfigurations>
-      netstandard2.0-Unix;
-      netstandard2.0-Windows_NT;
-    </BuildConfigurations>
-  </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/DateFormatType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/DateFormatType.cs
deleted file mode 100644 (file)
index e942417..0000000
+++ /dev/null
@@ -1,42 +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.SqlServer.TDS
-{
-    /// <summary>
-    /// Format of the date
-    /// </summary>
-    public enum DateFormatType
-    {
-        /// <summary>
-        /// y/m/d
-        /// </summary>
-        YearMonthDay,
-
-        /// <summary>
-        /// y/d/m
-        /// </summary>
-        YearDayMonth,
-
-        /// <summary>
-        /// m/d/y
-        /// </summary>
-        MonthDayYear,
-
-        /// <summary>
-        /// m/y/d
-        /// </summary>
-        MonthYearDay,
-
-        /// <summary>
-        /// d/m/y
-        /// </summary>
-        DayMonthYear,
-
-        /// <summary>
-        /// d/y/m
-        /// </summary>
-        DayYearMonth
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneInProcToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneInProcToken.cs
deleted file mode 100644 (file)
index 3e3edb5..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.Done
-{
-    /// <summary>
-    /// Completion packet "DONEINPROC" token
-    /// </summary>
-    public class TDSDoneInProcToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Status of the completion
-        /// </summary>
-        public TDSDoneTokenStatusType Status { get; set; }
-
-        /// <summary>
-        /// Token for which completion is indicated
-        /// </summary>
-        public TDSDoneTokenCommandType Command { get; set; }
-
-        /// <summary>
-        /// Amount of rows returned
-        /// </summary>
-        public ulong RowCount { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSDoneInProcToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneInProcToken(TDSDoneTokenStatusType status)
-        {
-            // Apply properties
-            Status = status;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneInProcToken(TDSDoneTokenStatusType status, TDSDoneTokenCommandType command) :
-            this(status)
-        {
-            // Apply properties that weren't applied by nested constructor call
-            Command = command;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneInProcToken(TDSDoneTokenStatusType status, TDSDoneTokenCommandType command, ulong rowCount) :
-            this(status, command)
-        {
-            // Apply properties that weren't applied by nested constructor call
-            RowCount = rowCount;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read status
-            Status = (TDSDoneTokenStatusType)TDSUtilities.ReadUShort(source);
-
-            // Read command
-            Command = (TDSDoneTokenCommandType)TDSUtilities.ReadUShort(source);
-
-            // Read row count
-            RowCount = TDSUtilities.ReadULong(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.DoneInProc);
-
-            // Write status
-            TDSUtilities.WriteUShort(destination, (ushort)Status);
-
-            // Write command
-            TDSUtilities.WriteUShort(destination, (ushort)Command);
-
-            // Write row count
-            TDSUtilities.WriteULong(destination, RowCount);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneProcedureToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneProcedureToken.cs
deleted file mode 100644 (file)
index 98846e5..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.Done
-{
-    /// <summary>
-    /// Completion packet "DONEPROC" token
-    /// </summary>
-    public class TDSDoneProcedureToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Status of the completion
-        /// </summary>
-        public TDSDoneTokenStatusType Status { get; set; }
-
-        /// <summary>
-        /// Token for which completion is indicated
-        /// </summary>
-        public TDSDoneTokenCommandType Command { get; set; }
-
-        /// <summary>
-        /// Amount of rows returned
-        /// </summary>
-        public ulong RowCount { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSDoneProcedureToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneProcedureToken(TDSDoneTokenStatusType status)
-        {
-            // Apply properties
-            Status = status;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneProcedureToken(TDSDoneTokenStatusType status, TDSDoneTokenCommandType command) :
-            this(status)
-        {
-            // Apply properties that weren't applied by nested constructor call
-            Command = command;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneProcedureToken(TDSDoneTokenStatusType status, TDSDoneTokenCommandType command, ulong rowCount) :
-            this(status, command)
-        {
-            // Apply properties that weren't applied by nested constructor call
-            RowCount = rowCount;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read status
-            Status = (TDSDoneTokenStatusType)TDSUtilities.ReadUShort(source);
-
-            // Read command
-            Command = (TDSDoneTokenCommandType)TDSUtilities.ReadUShort(source);
-
-            // Read row count
-            RowCount = TDSUtilities.ReadULong(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.DoneProcedure);
-
-            // Write status
-            TDSUtilities.WriteUShort(destination, (ushort)Status);
-
-            // Write command
-            TDSUtilities.WriteUShort(destination, (ushort)Command);
-
-            // Write row count
-            TDSUtilities.WriteULong(destination, RowCount);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneToken.cs
deleted file mode 100644 (file)
index 98b56be..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.Done
-{
-    /// <summary>
-    /// Completion packet "DONE" token
-    /// </summary>
-    public class TDSDoneToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Status of the completion
-        /// </summary>
-        public TDSDoneTokenStatusType Status { get; set; }
-
-        /// <summary>
-        /// Token for which completion is indicated
-        /// </summary>
-        public TDSDoneTokenCommandType Command { get; set; }
-
-        /// <summary>
-        /// Amount of rows returned
-        /// </summary>
-        public ulong RowCount { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSDoneToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneToken(TDSDoneTokenStatusType status)
-        {
-            // Apply properties
-            Status = status;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneToken(TDSDoneTokenStatusType status, TDSDoneTokenCommandType command) :
-            this(status)
-        {
-            // Apply properties that weren't applied by nested constructor call
-            Command = command;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSDoneToken(TDSDoneTokenStatusType status, TDSDoneTokenCommandType command, ulong rowCount) :
-            this(status, command)
-        {
-            // Apply properties that weren't applied by nested constructor call
-            RowCount = rowCount;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read status
-            Status = (TDSDoneTokenStatusType)TDSUtilities.ReadUShort(source);
-
-            // Read command
-            Command = (TDSDoneTokenCommandType)TDSUtilities.ReadUShort(source);
-
-            // Read row count
-            RowCount = TDSUtilities.ReadULong(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.Done);
-
-            // Write status
-            TDSUtilities.WriteUShort(destination, (ushort)Status);
-
-            // Write command
-            TDSUtilities.WriteUShort(destination, (ushort)Command);
-
-            // Write row count
-            TDSUtilities.WriteULong(destination, RowCount);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneTokenCommandType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneTokenCommandType.cs
deleted file mode 100644 (file)
index 1f81c99..0000000
+++ /dev/null
@@ -1,34 +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.SqlServer.TDS.Done
-{
-    /// <summary>
-    /// Command completion of which a DONE token reports
-    /// </summary>
-    public enum TDSDoneTokenCommandType : ushort
-    {
-        SetOn = 0xb9,
-        SetOff = 0xba,
-        Shutdown = 0xbf,
-        Select = 0xc1,
-        SelectInto = 0xc2,
-        Insert = 0xc3,
-        Delete = 0xc4,
-        Update = 0xc5,
-        TableCreate = 0xc6,
-        TableDestroy = 0xc7,
-        IndxCreate = 0xc8,
-        IndexDestroy = 0xc9,
-        Goto = 0xca,
-        DatabaseCreate = 0xcb,
-        DatabaseDestrot = 0xcc,
-        ViewCreate = 0xcf,
-        ViewDestroy = 0xd0,
-        Set = 0xf9,
-        Done = 0xfd,
-        DoneProc = 0xfe,
-        DoneInProc = 0xff
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneTokenStatusType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Done/TDSDoneTokenStatusType.cs
deleted file mode 100644 (file)
index e4c6b10..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.TDS.Done
-{
-    /// <summary>
-    /// Status of the token
-    /// </summary>
-    [Flags]
-    public enum TDSDoneTokenStatusType : ushort
-    {
-        Final = 0x00,
-        More = 0x01,
-        Error = 0x02,
-        TransactionInProgress = 0x04,
-        Count = 0x10,
-        Attention = 0x20,
-        RPCInBatch = 0x80,
-        ServerError = 0x100,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSEnvChangeToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSEnvChangeToken.cs
deleted file mode 100644 (file)
index d8c3655..0000000
+++ /dev/null
@@ -1,340 +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;
-
-namespace Microsoft.SqlServer.TDS.EnvChange
-{
-    /// <summary>
-    /// Environment change token "ENVCHANGE"
-    /// </summary>
-    public class TDSEnvChangeToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Type of the token
-        /// </summary>
-        public TDSEnvChangeTokenType Type { get; set; }
-
-        /// <summary>
-        /// Old value of the token (optional)
-        /// </summary>
-        public object OldValue { get; set; }
-
-        /// <summary>
-        /// New value of the token
-        /// </summary>
-        public object NewValue { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSEnvChangeToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSEnvChangeToken(TDSEnvChangeTokenType type)
-        {
-            Type = type;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSEnvChangeToken(TDSEnvChangeTokenType type, object newValue) :
-            this(type)
-        {
-            NewValue = newValue;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSEnvChangeToken(TDSEnvChangeTokenType type, object newValue, object oldValue) :
-            this(type, newValue)
-        {
-            OldValue = oldValue;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-
-            // Read token length
-            ushort tokenLength = TDSUtilities.ReadUShort(source);
-
-            // Check if length can accomodate at least the type
-            if (tokenLength == 0)
-            {
-                // We're done inflating this token
-                return true;
-            }
-
-            // Read the token type
-            Type = (TDSEnvChangeTokenType)source.ReadByte();
-
-            // Update the token length left
-            tokenLength--;
-
-            // Check if we can squeez anything else
-            if (tokenLength == 0)
-            {
-                // We're done inflating this token
-                return true;
-            }
-
-            // Read the rest of the token based on the token type
-            switch (Type)
-            {
-                case TDSEnvChangeTokenType.Database:
-                case TDSEnvChangeTokenType.Language:
-                case TDSEnvChangeTokenType.CharacterSet:
-                case TDSEnvChangeTokenType.PacketSize:
-                case TDSEnvChangeTokenType.RealTimeLogShipping:
-                    {
-                        // Read new value length
-                        byte valueLength = (byte)source.ReadByte();
-
-                        // Update token length
-                        tokenLength--;
-
-                        // Read string of the specified size
-                        NewValue = TDSUtilities.ReadString(source, (ushort)(valueLength * 2));
-
-                        // Update token length
-                        tokenLength -= (ushort)(valueLength * 2);
-
-                        // Check if old value can fit in
-                        if (tokenLength == 0)
-                        {
-                            // Old value won't fit in
-                            break;
-                        }
-
-                        // Read old value length
-                        valueLength = (byte)source.ReadByte();
-
-                        // Update token length
-                        tokenLength--;
-
-                        // Read string of the specified size
-                        OldValue = TDSUtilities.ReadString(source, (ushort)(valueLength * 2));
-
-                        // Update token length
-                        tokenLength -= (ushort)(valueLength * 2);
-
-                        // Inflation is complete
-                        break;
-                    }
-                case TDSEnvChangeTokenType.Routing:
-                    {
-                        // Read the new value length
-                        ushort valueLength = TDSUtilities.ReadUShort(source);
-
-                        // Update token length
-                        tokenLength -= 2;  // sizeof(ushort)
-
-                        // Instantiate new value
-                        NewValue = new TDSRoutingEnvChangeTokenValue();
-
-                        // Inflate new value
-                        if (!(NewValue as TDSRoutingEnvChangeTokenValue).Inflate(source))
-                        {
-                            // We should never reach this point
-                            throw new Exception("Routing information inflation failed");
-                        }
-
-                        // Read always-zero old value unsigned short
-                        if (TDSUtilities.ReadUShort(source) != 0)
-                        {
-                            // We should never reach this point
-                            throw new Exception("Non-zero old value for routing information");
-                        }
-
-                        break;
-                    }
-                case TDSEnvChangeTokenType.SQLCollation:
-                    {
-                        // Read new value length
-                        byte valueLength = (byte)source.ReadByte();
-
-                        // Update token length
-                        tokenLength--;
-
-                        // Check if old value can fit in
-                        if (tokenLength == 0)
-                        {
-                            // Old value won't fit in
-                            break;
-                        }
-
-                        // Allocate the buffer
-                        byte[] byteValue = new byte[valueLength];
-
-                        // Read bytes off the wire
-                        source.Read(byteValue, 0, byteValue.Length);
-
-                        // Set new value
-                        NewValue = byteValue;
-
-                        // Update token length
-                        tokenLength -= valueLength;
-
-                        // Check if old value can fit in
-                        if (tokenLength == 0)
-                        {
-                            // Old value won't fit in
-                            break;
-                        }
-
-                        // Read old value length
-                        valueLength = (byte)source.ReadByte();
-
-                        // Update token length
-                        tokenLength--;
-
-                        // Check if old value can fit in
-                        if (tokenLength == 0)
-                        {
-                            // Old value won't fit in
-                            break;
-                        }
-
-                        // Allocate the buffer
-                        byteValue = new byte[valueLength];
-
-                        // Read bytes off the wire
-                        source.Read(byteValue, 0, byteValue.Length);
-
-                        // Set old value
-                        OldValue = byteValue;
-
-                        // Update token length
-                        tokenLength -= valueLength;
-
-                        // Inflation is complete
-                        break;
-                    }
-                default:
-                    {
-                        // Skip the rest of the token
-                        byte[] tokenData = new byte[tokenLength];
-                        source.Read(tokenData, 0, tokenData.Length);
-
-                        break;
-                    }
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Allocate stream for token data
-            // We need to cache it to calculate the environment change token length
-            MemoryStream cache = new MemoryStream();
-
-            // Write environment change type
-            cache.WriteByte((byte)Type);
-
-            // Write the rest of the token based on the token type
-            switch (Type)
-            {
-                case TDSEnvChangeTokenType.Database:
-                case TDSEnvChangeTokenType.Language:
-                case TDSEnvChangeTokenType.CharacterSet:
-                case TDSEnvChangeTokenType.PacketSize:
-                case TDSEnvChangeTokenType.RealTimeLogShipping:
-                    {
-                        // Write new value length
-                        cache.WriteByte((byte)(string.IsNullOrEmpty((string)NewValue) ? 0 : ((string)NewValue).Length));
-
-                        // Write new value
-                        TDSUtilities.WriteString(cache, (string)NewValue);
-
-                        // Write old value length
-                        cache.WriteByte((byte)(string.IsNullOrEmpty((string)OldValue) ? 0 : ((string)OldValue).Length));
-
-                        // Write old value
-                        TDSUtilities.WriteString(cache, (string)OldValue);
-
-                        break;
-                    }
-                case TDSEnvChangeTokenType.Routing:
-                    {
-                        // Create a sub-cache to determine the value length
-                        MemoryStream subCache = new MemoryStream();
-
-                        // Check if new value exists
-                        if (NewValue != null)
-                        {
-                            // Deflate token value
-                            (NewValue as TDSRoutingEnvChangeTokenValue).Deflate(subCache);
-                        }
-
-                        // Write new value length
-                        TDSUtilities.WriteUShort(cache, (ushort)subCache.Length);
-
-                        // Write new value
-                        subCache.WriteTo(cache);
-
-                        // Write zero for the old value length
-                        TDSUtilities.WriteUShort(cache, 0);
-
-                        break;
-                    }
-                case TDSEnvChangeTokenType.SQLCollation:
-                    {
-                        // Write new value length
-                        cache.WriteByte((byte)(NewValue != null ? ((byte[])NewValue).Length : 0));
-
-                        // Check if we have a new value
-                        if (NewValue != null)
-                        {
-                            // Write new value
-                            cache.Write((byte[])NewValue, 0, ((byte[])NewValue).Length);
-                        }
-
-                        // Write old value length
-                        cache.WriteByte((byte)(OldValue != null ? ((byte[])OldValue).Length : 0));
-
-                        // Check if we have a old value
-                        if (OldValue != null)
-                        {
-                            // Write old value
-                            cache.Write((byte[])OldValue, 0, ((byte[])OldValue).Length);
-                        }
-
-                        break;
-                    }
-                default:
-                    {
-                        throw new Exception("Unrecognized environment change type");
-                    }
-            }
-
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.EnvironmentChange);
-
-            // Write length
-            TDSUtilities.WriteUShort(destination, (ushort)cache.Length);
-
-            // Write token data
-            cache.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSEnvChangeTokenType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSEnvChangeTokenType.cs
deleted file mode 100644 (file)
index b4e1ae9..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.EnvChange
-{
-    /// <summary>
-    /// Type of TDS EnvChagne token
-    /// </summary>
-    public enum TDSEnvChangeTokenType : byte
-    {
-        Database = 1,
-        Language = 2,
-        CharacterSet = 3,
-        PacketSize = 4,
-        UnicodeSort = 5,
-        UnicodeFlags = 6,
-        SQLCollation = 7,
-        BeginTransaction = 8,
-        CommitTransaction = 9,
-        RollbackTransaction = 10,
-        EnlistDTCTransaction = 11,
-        DefectTransaction = 12,
-        RealTimeLogShipping = 13,
-        PromoteTransaction = 15,
-        TransactionManagerAddress = 16,
-        TransactionEnded = 17,
-        ResetConnectionAcknowledgement = 18,
-        UserInstance = 19,
-        Routing = 20
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSRoutingEnvChangeTokenValue.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSRoutingEnvChangeTokenValue.cs
deleted file mode 100644 (file)
index 544131e..0000000
+++ /dev/null
@@ -1,137 +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;
-
-namespace Microsoft.SqlServer.TDS.EnvChange
-{
-    /// <summary>
-    /// Token value that represents routing information
-    /// </summary>
-    public class TDSRoutingEnvChangeTokenValue : IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// Protocol to use when connecting to the target server
-        /// </summary>
-        public TDSRoutingEnvChangeTokenValueType Protocol { get; set; }
-
-        /// <summary>
-        /// Protocol details
-        /// </summary>
-        public object ProtocolProperty { get; set; }
-
-        /// <summary>
-        /// Location of the target server
-        /// </summary>
-        public string AlternateServer { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSRoutingEnvChangeTokenValue()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSRoutingEnvChangeTokenValue(TDSRoutingEnvChangeTokenValueType protocol)
-        {
-            // Save protocol
-            Protocol = protocol;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSRoutingEnvChangeTokenValue(TDSRoutingEnvChangeTokenValueType protocol, object protocolProperty)
-        {
-            // Save protocol and protocol property
-            Protocol = protocol;
-            ProtocolProperty = protocolProperty;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSRoutingEnvChangeTokenValue(TDSRoutingEnvChangeTokenValueType protocol, object protocolProperty, string alternateServer)
-        {
-            // Save all
-            Protocol = protocol;
-            ProtocolProperty = protocolProperty;
-            AlternateServer = alternateServer;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public virtual bool Inflate(Stream source)
-        {
-            // Read protocol value
-            Protocol = (TDSRoutingEnvChangeTokenValueType)source.ReadByte();
-
-            // Based on the protocol type read the rest of the token
-            switch (Protocol)
-            {
-                case TDSRoutingEnvChangeTokenValueType.TCP:
-                    {
-                        // Read port
-                        ProtocolProperty = TDSUtilities.ReadUShort(source);
-
-                        // Read alternate server name of the length
-                        AlternateServer = TDSUtilities.ReadString(source, (ushort)(TDSUtilities.ReadUShort(source) * 2));
-
-                        break;
-                    }
-                default:
-                    {
-                        throw new Exception("Unrecognized routing protocol");
-                    }
-            }
-
-            // Inflation is complete
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public virtual void Deflate(Stream destination)
-        {
-            // Write protocol value
-            destination.WriteByte((byte)Protocol);
-
-            // Based on the protocol type read the rest of the token
-            switch (Protocol)
-            {
-                default:
-                case TDSRoutingEnvChangeTokenValueType.TCP:
-                    {
-                        // Write port
-                        TDSUtilities.WriteUShort(destination, (ushort)ProtocolProperty);
-
-                        // Write alternate server name length
-                        TDSUtilities.WriteUShort(destination, (ushort)(string.IsNullOrEmpty(AlternateServer) ? 0 : AlternateServer.Length));
-
-                        // Write alternate server name
-                        TDSUtilities.WriteString(destination, AlternateServer);
-
-                        break;
-                    }
-            }
-        }
-
-        /// <summary>
-        /// Override string representation method
-        /// </summary>
-        public override string ToString()
-        {
-            return string.Format("Protocol: {0}; Protocol Property: {1}; Alternate Server: {2}", Protocol, ProtocolProperty, AlternateServer);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSRoutingEnvChangeTokenValueType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/EnvChange/TDSRoutingEnvChangeTokenValueType.cs
deleted file mode 100644 (file)
index 10cf778..0000000
+++ /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 Microsoft.SqlServer.TDS.EnvChange
-{
-    /// <summary>
-    /// Routing protocol
-    /// </summary>
-    public enum TDSRoutingEnvChangeTokenValueType
-    {
-        TCP = 0
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Error/TDSErrorToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Error/TDSErrorToken.cs
deleted file mode 100644 (file)
index 5a4e767..0000000
+++ /dev/null
@@ -1,225 +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;
-
-namespace Microsoft.SqlServer.TDS.Error
-{
-    /// <summary>
-    /// Environment change token "ERROR"
-    /// </summary>
-    public class TDSErrorToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Error number
-        /// </summary>
-        public uint Number { get; set; }
-
-        /// <summary>
-        /// Error state
-        /// </summary>
-        public byte State { get; set; }
-
-        /// <summary>
-        /// Error class
-        /// </summary>
-        public byte Class { get; set; }
-
-        /// <summary>
-        /// Description of the error
-        /// </summary>
-        public string Message { get; set; }
-
-        /// <summary>
-        /// Name of the server generated an error
-        /// </summary>
-        public string ServerName { get; set; }
-
-        /// <summary>
-        /// Procedure that produced an error
-        /// </summary>
-        public string ProcedureName { get; set; }
-
-        /// <summary>
-        /// Line number at which an error occurred
-        /// </summary>
-        public uint Line { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSErrorToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSErrorToken(uint number)
-        {
-            Number = number;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSErrorToken(uint number, byte state) :
-            this(number)
-        {
-            State = state;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSErrorToken(uint number, byte state, byte clazz) :
-            this(number, state)
-        {
-            Class = clazz;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSErrorToken(uint number, byte state, byte clazz, string message) :
-            this(number, state, clazz)
-        {
-            Message = message;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSErrorToken(uint number, byte state, byte clazz, string message, string serverName) :
-            this(number, state, clazz, message)
-        {
-            ServerName = serverName;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSErrorToken(uint number, byte state, byte clazz, string message, string serverName, string procedureName) :
-            this(number, state, clazz, message, serverName)
-        {
-            ProcedureName = procedureName;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSErrorToken(uint number, byte state, byte clazz, string message, string serverName, string procedureName, uint line) :
-            this(number, state, clazz, message, serverName, procedureName)
-        {
-            Line = line;
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSErrorToken(Stream source)
-        {
-            // Inflate the token
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-
-            // Read token length
-            ushort tokenLength = TDSUtilities.ReadUShort(source);
-
-            // Read the number
-            Number = TDSUtilities.ReadUInt(source);
-
-            // Read state
-            State = (byte)source.ReadByte();
-
-            // Read class
-            Class = (byte)source.ReadByte();
-
-            // Read the message text length
-            ushort textLength = TDSUtilities.ReadUShort(source);
-
-            // Read the message itself
-            Message = TDSUtilities.ReadString(source, (ushort)(textLength * 2));
-
-            // Read server name length
-            textLength = (byte)source.ReadByte();
-
-            // Read server name
-            ServerName = TDSUtilities.ReadString(source, (ushort)(textLength * 2));
-
-            // Read procedure name length
-            textLength = (byte)source.ReadByte();
-
-            // Read procedure name
-            ProcedureName = TDSUtilities.ReadString(source, (ushort)(textLength * 2));
-
-            // Read the line number
-            Line = TDSUtilities.ReadUInt(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.Error);
-
-            // Calculate the length
-            ushort totalLength = (ushort)(sizeof(uint) // Number
-                + sizeof(byte) // State
-                + sizeof(byte) // Class
-                + sizeof(ushort) + (string.IsNullOrEmpty(Message) ? 0 : Message.Length) * sizeof(char) // Message
-                + sizeof(byte) + (string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length) * sizeof(char) // Server Name
-                + sizeof(byte) + (string.IsNullOrEmpty(ProcedureName) ? 0 : ProcedureName.Length) * sizeof(char) // Procedure Name
-                + sizeof(uint)); // Line number
-
-            // Write token length
-            TDSUtilities.WriteUShort(destination, totalLength);
-
-            // Write the number
-            TDSUtilities.WriteUInt(destination, Number);
-
-            // Write state
-            destination.WriteByte((byte)State);
-
-            // Write class
-            destination.WriteByte((byte)Class);
-
-            // Write message text length
-            TDSUtilities.WriteUShort(destination, (ushort)(string.IsNullOrEmpty(Message) ? 0 : Message.Length));
-
-            // Write the message itself
-            TDSUtilities.WriteString(destination, Message);
-
-            // Write server name length
-            destination.WriteByte((byte)(string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length));
-
-            // Write server name
-            TDSUtilities.WriteString(destination, ServerName);
-
-            // Write procedure name length
-            destination.WriteByte((byte)(string.IsNullOrEmpty(ProcedureName) ? 0 : ProcedureName.Length));
-
-            // Write procedure name
-            TDSUtilities.WriteString(destination, ProcedureName);
-
-            // Write the line number
-            TDSUtilities.WriteUInt(destination, Line);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckFederatedAuthenticationOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckFederatedAuthenticationOption.cs
deleted file mode 100644 (file)
index 4d8d79f..0000000
+++ /dev/null
@@ -1,140 +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.Collections.Generic;
-
-using Microsoft.SqlServer.TDS.SessionState;
-
-namespace Microsoft.SqlServer.TDS.FeatureExtAck
-{
-    /// <summary>
-    /// Acknowledgement for federated authentication
-    /// </summary>
-    public class TDSFeatureExtAckFederatedAuthenticationOption : TDSFeatureExtAckOption
-    {
-        /// <summary>
-        /// Fixed Length of Nonce
-        /// </summary>
-        private static readonly uint s_nonceDataLength = 32;
-
-        /// <summary>
-        /// Fixed Length of Signature
-        /// </summary>
-        private static readonly uint s_signatureDataLength = 32;
-
-        /// <summary>
-        /// Signed nonce
-        /// </summary>
-        public byte[] ClientNonce { get; set; }
-
-        /// <summary>
-        /// The HMAC-SHA-256 [RFC6234] of the server-specified nonce
-        /// </summary>
-        public byte[] Signature { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSFeatureExtAckFederatedAuthenticationOption(byte[] clientNonce, byte[] signature) :
-            this()
-        {
-            // Nonce and/or Signature can be null depending on the FedAuthLibrary used
-            if (clientNonce == null && signature != null)
-            {
-                throw new ArgumentNullException(nameof(signature));
-            }
-            else if (clientNonce != null && clientNonce.Length != s_nonceDataLength)
-            {
-                throw new ArgumentOutOfRangeException("nonce");
-            }
-            else if (signature != null && signature.Length != s_signatureDataLength)
-            {
-                throw new ArgumentOutOfRangeException("signature");
-            }
-
-            // Save nonce
-            ClientNonce = clientNonce;
-
-            // Save signature
-            Signature = signature;
-        }
-
-        /// <summary>
-        /// Inflation constructor
-        /// </summary>
-        public TDSFeatureExtAckFederatedAuthenticationOption(Stream source) :
-            this()
-        {
-            // Inflate
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        private TDSFeatureExtAckFederatedAuthenticationOption()
-        {
-            // Set feature identifier
-            FeatureID = TDSFeatureID.FederatedAuthentication;
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write feature extension acknowledgement
-            destination.WriteByte((byte)TDSFeatureID.FederatedAuthentication);
-
-            // Write the data length
-            TDSUtilities.WriteUInt(destination, ((ClientNonce != null) ? s_nonceDataLength : 0) + ((Signature != null) ? s_signatureDataLength : 0));
-
-            if (ClientNonce != null)
-            {
-                // Write the Nonce
-                destination.Write(ClientNonce, 0, (int)s_nonceDataLength);
-            }
-
-            if (Signature != null)
-            {
-                // Write the signature
-                destination.Write(Signature, 0, (int)s_signatureDataLength);
-            }
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // We skip feature ID because it was read by construction factory
-
-            // Read the data length.
-            uint dataLength = TDSUtilities.ReadUInt(source);
-
-            if (dataLength > 0)
-            {
-                // Allocate a container
-                ClientNonce = new byte[s_nonceDataLength];
-
-                // Read the data
-                source.Read(ClientNonce, 0, (int)s_nonceDataLength);
-            }
-
-            if (dataLength > s_nonceDataLength)
-            {
-                // Allocate Signature
-                Signature = new byte[s_signatureDataLength];
-
-                // Read the data
-                source.Read(Signature, 0, (int)s_signatureDataLength);
-            }
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckGenericOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckGenericOption.cs
deleted file mode 100644 (file)
index 5613031..0000000
+++ /dev/null
@@ -1,121 +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;
-
-namespace Microsoft.SqlServer.TDS.FeatureExtAck
-{
-    /// <summary>
-    /// A single option of the feature extension acknowledgement block
-    /// </summary>
-    public class TDSFeatureExtAckGenericOption : TDSFeatureExtAckOption
-    {
-        /// <summary>
-        /// FeatureAck data length.
-        /// </summary>
-        public uint FeatureAckDataLen { get; set; }
-
-        /// <summary>
-        /// FeatureAck Data.
-        /// </summary>
-        public byte[] FeatureAckData { get; set; }
-
-        /// <summary>
-        /// Initialization Constructor.
-        /// </summary>
-        public TDSFeatureExtAckGenericOption()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="type">type of the FeatureExtAckToken.</param>
-        public TDSFeatureExtAckGenericOption(TDSFeatureID type)
-        {
-            FeatureID = type;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="type">type of the FeatureExtAckToken.</param>
-        /// <param name="featureAckDataLen">Length of the data.</param>
-        public TDSFeatureExtAckGenericOption(TDSFeatureID type, uint featureAckDataLen)
-            : this(type)
-        {
-            FeatureAckDataLen = featureAckDataLen;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="type">type of the FeatureExtAckToken.</param>
-        /// <param name="featureAckDataLen">Length of the data.</param>
-        /// <param name="data">Data of the FeatureAck token.</param>
-        public TDSFeatureExtAckGenericOption(TDSFeatureID type, uint featureAckDataLen, byte[] data)
-            : this(type, featureAckDataLen)
-        {
-            FeatureAckData = data;
-        }
-
-        /// <summary>
-        /// Inflating constructor.
-        /// </summary>
-        /// <param name="source"></param>
-        public TDSFeatureExtAckGenericOption(Stream source)
-        {
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        /// <param name="source"></param>
-        public TDSFeatureExtAckGenericOption(TDSFeatureID featureID, Stream source) :
-            this(source)
-        {
-            FeatureID = featureID;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from.</param>
-        /// <returns>True in case of success, false otherwise.</returns>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-
-            // Read the data length.
-            FeatureAckDataLen = TDSUtilities.ReadUInt(source);
-
-            // Read the Data.
-            if (FeatureAckDataLen > 0)
-            {
-                FeatureAckData = new byte[FeatureAckDataLen];
-                source.Read(FeatureAckData, 0, (int)FeatureAckDataLen);
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token.
-        /// </summary>
-        /// <param name="destination">Stream the token to deflate to.</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write FeatureID
-            destination.WriteByte((byte)FeatureID);
-
-            // Write FeatureAckDataLen
-            TDSUtilities.WriteUInt(destination, FeatureAckDataLen);
-
-            // Write data.
-            destination.Write(FeatureAckData, 0, (int)FeatureAckDataLen);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckOption.cs
deleted file mode 100644 (file)
index 70cd15d..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.FeatureExtAck
-{
-    /// <summary>
-    /// A single option of the feature extension acknowledgement block
-    /// </summary>
-    public abstract class TDSFeatureExtAckOption : IDeflatable, IInflatable
-    {
-        /// <summary>
-        /// Feature identifier
-        /// </summary>
-        public virtual TDSFeatureID FeatureID { get; protected set; }
-
-        /// <summary>
-        /// Initialization Constructor.
-        /// </summary>
-        public TDSFeatureExtAckOption()
-        {
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        public abstract bool Inflate(Stream source);
-
-        /// <summary>
-        /// Deflate the token.
-        /// </summary>
-        public abstract void Deflate(Stream destination);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckSessionStateOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckSessionStateOption.cs
deleted file mode 100644 (file)
index 6a3d1f4..0000000
+++ /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.IO;
-using System.Collections.Generic;
-
-using Microsoft.SqlServer.TDS.SessionState;
-
-namespace Microsoft.SqlServer.TDS.FeatureExtAck
-{
-    /// <summary>
-    /// Acknowledgement for session state recovery
-    /// </summary>
-    public class TDSFeatureExtAckSessionStateOption : TDSFeatureExtAckOption
-    {
-        /// <summary>
-        /// Options that carry session state
-        /// </summary>
-        public IList<TDSSessionStateOption> Options { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSFeatureExtAckSessionStateOption()
-        {
-            // Set feature identifier
-            FeatureID = TDSFeatureID.SessionRecovery;
-
-            // Create options collection
-            Options = new List<TDSSessionStateOption>();
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSFeatureExtAckSessionStateOption(IList<TDSSessionStateOption> options)
-        {
-            // Set feature identifier
-            FeatureID = TDSFeatureID.SessionRecovery;
-
-            // Save options
-            Options = options;
-        }
-
-        /// <summary>
-        /// Inflation constructor
-        /// </summary>
-        public TDSFeatureExtAckSessionStateOption(Stream source) :
-            this()
-        {
-            // Inflate
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write feature extension acknowledgement
-            destination.WriteByte((byte)TDSFeatureID.SessionRecovery);
-
-            // Allocate temporary memory stream
-            MemoryStream memoryStream = new MemoryStream();
-
-            // Iterate through all options and deflate them
-            foreach (TDSSessionStateOption option in Options)
-            {
-                // Deflate into the cache to calcualte the overall length
-                option.Deflate(memoryStream);
-            }
-
-            // Write the length
-            TDSUtilities.WriteUInt(destination, (uint)memoryStream.Length);
-
-            // Write the data itself
-            memoryStream.WriteTo(destination);
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Create options collection
-            Options = new List<TDSSessionStateOption>();
-
-            // We skip feature ID because it was read by construction factory
-
-            // Read the total length
-            uint totalLength = TDSUtilities.ReadUInt(source);
-
-            // Current position in the stream
-            uint currentLength = 0;
-
-            // Read while we have data
-            while (totalLength > currentLength)
-            {
-                // Read a byte that identifies the session state slot
-                byte stateID = (byte)source.ReadByte();
-
-                // Update current position
-                currentLength += sizeof(byte);
-
-                // Option being inflated
-                TDSSessionStateOption option = null;
-
-                // Dispatch inflation based on the state
-                switch (stateID)
-                {
-                    // UserOptionAll
-                    case TDSSessionStateUserOptionsOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateUserOptionsOption();
-                            break;
-                        }
-                    // DateFirstDateFormat
-                    case TDSSessionStateDateFirstDateFormatOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateDateFirstDateFormatOption();
-                            break;
-                        }
-                    // DbDeadlockPri
-                    case TDSSessionStateDeadlockPriorityOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateDeadlockPriorityOption();
-                            break;
-                        }
-                    // LockTimeout
-                    case TDSSessionStateLockTimeoutOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateLockTimeoutOption();
-                            break;
-                        }
-                    // IsoFips
-                    case TDSSessionStateISOFipsOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateISOFipsOption();
-                            break;
-                        }
-                    // TextSize
-                    case TDSSessionStateTextSizeOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateTextSizeOption();
-                            break;
-                        }
-                    // ContextInfo
-                    case TDSSessionStateContextInfoOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateContextInfoOption();
-                            break;
-                        }
-                    default:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateGenericOption(stateID);
-                            break;
-                        }
-                }
-
-                // Inflate the option
-                option.Inflate(source);
-
-                // Register option with the collection
-                Options.Add(option);
-
-                // Update current length with the inflation size of the data
-                currentLength += option.InflationSize;
-            }
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FeatureExtAck/TDSFeatureExtAckToken.cs
deleted file mode 100644 (file)
index c0816b9..0000000
+++ /dev/null
@@ -1,120 +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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS.FeatureExtAck
-{
-    /// <summary>
-    /// FeatureAck token definition.
-    /// </summary>
-    public class TDSFeatureExtAckToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Collection of feature extension acknowledged options
-        /// </summary>
-        public IList<TDSFeatureExtAckOption> Options { get; set; }
-
-        /// <summary>
-        /// Default Constructor.
-        /// </summary>
-        public TDSFeatureExtAckToken()
-        {
-            // Initialize options collection
-            Options = new List<TDSFeatureExtAckOption>();
-        }
-
-        /// <summary>
-        /// Initialization constructor.
-        /// </summary>
-        /// <param name="source"></param>
-        public TDSFeatureExtAckToken(params TDSFeatureExtAckOption[] options) :
-            this()
-        {
-            ((List<TDSFeatureExtAckOption>)Options).AddRange(options);
-        }
-
-        /// <summary>
-        /// Inflating constructor.
-        /// </summary>
-        /// <param name="source"></param>
-        public TDSFeatureExtAckToken(Stream source) :
-            this()
-        {
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from.</param>
-        /// <returns>True in case of success, false otherwise.</returns>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-            TDSFeatureID currentFeatureType = TDSFeatureID.FederatedAuthentication;
-
-            do
-            {
-                // Read feature type
-                currentFeatureType = (TDSFeatureID)source.ReadByte();
-
-                // Ensure we're not looking at the terminator
-                switch (currentFeatureType)
-                {
-                    case TDSFeatureID.SessionRecovery:
-                        {
-                            // Create a new option
-                            Options.Add(new TDSFeatureExtAckSessionStateOption(source));
-                            break;
-                        }
-
-                    case TDSFeatureID.FederatedAuthentication:
-                        {
-                            Options.Add(new TDSFeatureExtAckFederatedAuthenticationOption(source));
-                            break;
-                        }
-
-                    case TDSFeatureID.Terminator:
-                        {
-                            // Do nothing
-                            break;
-                        }
-                    default:
-                        {
-                            // Create a new generic option
-                            Options.Add(new TDSFeatureExtAckGenericOption(currentFeatureType, source));
-                            break;
-                        }
-                }
-            }
-            while (currentFeatureType != TDSFeatureID.Terminator);
-
-            // We're done inflating
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token.
-        /// </summary>
-        /// <param name="destination">Stream the token to deflate to.</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write the token type.
-            destination.WriteByte((byte)TDSTokenType.FeatureExtAck);
-
-            // Iterate through all options
-            foreach (TDSFeatureExtAckOption option in Options)
-            {
-                // Deflate the option itself
-                option.Deflate(destination);
-            }
-
-            // Write terminator
-            destination.WriteByte((byte)TDSFeatureID.Terminator);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoId.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoId.cs
deleted file mode 100644 (file)
index b3b1a70..0000000
+++ /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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS.Authentication
-{
-    public enum TDSFedAuthInfoId
-    {
-        /// <summary>
-        /// STS URL as Token Endpoint
-        /// </summary>
-        STSURL = 0x01,
-
-        /// <summary>
-        /// Service Principal Name
-        /// </summary>
-        SPN = 0x02,
-
-        /// <summary>
-        /// Invalid InfoId
-        /// </summary>
-        Invalid = 0xEE
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOption.cs
deleted file mode 100644 (file)
index 1ea068f..0000000
+++ /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.Collections.Generic;
-using System.IO;
-
-namespace Microsoft.SqlServer.TDS.Authentication
-{
-    /// <summary>
-    /// A single option of the feature extension acknowledgement block
-    /// </summary>
-    public abstract class TDSFedAuthInfoOption : IDeflatable, IInflatable
-    {
-        /// <summary>
-        /// FedAuth Info Identifier.
-        /// </summary>
-        public abstract TDSFedAuthInfoId FedAuthInfoId { get; }
-
-        /// <summary>
-        /// Initialization Constructor.
-        /// </summary>
-        public TDSFedAuthInfoOption()
-        {
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        public abstract bool Inflate(Stream source);
-
-        /// <summary>
-        /// Deflate the token.
-        /// </summary>
-        public abstract void Deflate(Stream destination);
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOptionSPN.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOptionSPN.cs
deleted file mode 100644 (file)
index 3f795c6..0000000
+++ /dev/null
@@ -1,116 +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.IO;
-using System.Text;
-
-namespace Microsoft.SqlServer.TDS.Authentication
-{
-    /// <summary>
-    /// TDS FedAuth Info Option for SPN
-    /// </summary>
-    public class TDSFedAuthInfoOptionSPN : TDSFedAuthInfoOption
-    {
-        /// <summary>
-        /// FedAuth Information ID
-        /// </summary>
-        private TDSFedAuthInfoId _fedAuthInfoId;
-
-        /// <summary>
-        /// Information Data Length
-        /// </summary>
-        private uint _infoDataLength;
-
-        /// <summary>
-        /// STS URL
-        /// </summary>
-        private byte[] _spn;
-
-        /// <summary>
-        /// Return the SPN as a unicode string.
-        /// </summary>
-        public string SPN
-        {
-            get
-            {
-                if (_spn != null)
-                {
-                    return Encoding.Unicode.GetString(_spn);
-                }
-
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// Return the FedAuthInfo Id.
-        /// </summary>
-        public override TDSFedAuthInfoId FedAuthInfoId
-        {
-            get
-            {
-                return _fedAuthInfoId;
-            }
-        }
-
-        /// <summary>
-        /// Default public constructor
-        /// </summary>
-        public TDSFedAuthInfoOptionSPN()
-        {
-            _fedAuthInfoId = TDSFedAuthInfoId.SPN;
-        }
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="infoDataLength">Info Data Length</param>
-        public TDSFedAuthInfoOptionSPN(uint infoDataLength)
-            : this()
-        {
-            _infoDataLength = infoDataLength;
-        }
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="spn">SPN string</param>
-        public TDSFedAuthInfoOptionSPN(string spn)
-            : this()
-        {
-            _spn = Encoding.Unicode.GetBytes(spn);
-            _infoDataLength = (uint)_spn.Length;
-        }
-
-        /// <summary>
-        /// Inflate the data from the stream, when receiving this token.
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Read the information data
-            //
-            if (_infoDataLength > 0)
-            {
-                _spn = new byte[_infoDataLength];
-                source.Read(_spn, 0, _spn.Length);
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the data to the stream, when writing this token.
-        /// </summary>
-        /// <param name="source"></param>
-        public override void Deflate(Stream source)
-        {
-            if (_infoDataLength > 0)
-            {
-                source.Write(_spn, 0, _spn.Length);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOptionSTSURL.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoOptionSTSURL.cs
deleted file mode 100644 (file)
index c100f96..0000000
+++ /dev/null
@@ -1,114 +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.IO;
-using System.Text;
-
-namespace Microsoft.SqlServer.TDS.Authentication
-{
-    /// <summary>
-    /// TDS FedAuth Info Option for STS URL
-    /// </summary>
-    public class TDSFedAuthInfoOptionSTSURL : TDSFedAuthInfoOption
-    {
-        /// <summary>
-        /// FedAuth Information ID
-        /// </summary>
-        private TDSFedAuthInfoId _fedAuthInfoId;
-
-        /// <summary>
-        /// Information Data Length
-        /// </summary>
-        private uint _infoDataLength;
-
-        /// <summary>
-        /// STS URL
-        /// </summary>
-        private byte[] _stsUrl;
-
-        /// <summary>
-        /// Return the FedAuthInfo Id.
-        /// </summary>
-        public override TDSFedAuthInfoId FedAuthInfoId
-        {
-            get
-            {
-                return _fedAuthInfoId;
-            }
-        }
-
-        /// <summary>
-        /// Return the STSURL as a unicode string.
-        /// </summary>
-        public string STSURL
-        {
-            get
-            {
-                if (_stsUrl != null)
-                {
-                    return Encoding.Unicode.GetString(_stsUrl);
-                }
-
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// Default public constructor
-        /// </summary>
-        public TDSFedAuthInfoOptionSTSURL()
-        {
-            _fedAuthInfoId = TDSFedAuthInfoId.STSURL;
-        }
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="infoDataLength">Info Data Length</param>
-        public TDSFedAuthInfoOptionSTSURL(uint infoDataLength) : this()
-        {
-            _infoDataLength = infoDataLength;
-        }
-
-        /// <summary>
-        /// Constructor
-        /// </summary>
-        /// <param name="stsurl">STSURL string</param>
-        public TDSFedAuthInfoOptionSTSURL(string stsurl) : this()
-        {
-            _stsUrl = Encoding.Unicode.GetBytes(stsurl);
-            _infoDataLength = (uint)_stsUrl.Length;
-        }
-
-        /// <summary>
-        /// Inflate the data from the stream, when receiving this token.
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Read the information data
-            //
-            if (_infoDataLength > 0)
-            {
-                _stsUrl = new byte[_infoDataLength];
-                source.Read(_stsUrl, 0, _stsUrl.Length);
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the data to the stream, when writing this token.
-        /// </summary>
-        /// <param name="source"></param>
-        public override void Deflate(Stream source)
-        {
-            if (_infoDataLength > 0)
-            {
-                source.Write(_stsUrl, 0, _stsUrl.Length);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthInfo/TDSFedAuthInfoToken.cs
deleted file mode 100644 (file)
index 7f5dc96..0000000
+++ /dev/null
@@ -1,159 +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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS.Authentication
-{
-    /// <summary>
-    /// FeatureAck token definition.
-    /// </summary>
-    public class TDSFedAuthInfoToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Collection of fedauth info options
-        /// </summary>
-        public SortedDictionary<int, TDSFedAuthInfoOption> Options { get; private set; }
-
-        /// <summary>
-        /// Default Constructor.
-        /// </summary>
-        public TDSFedAuthInfoToken()
-        {
-            // Initialize options collection
-            Options = new SortedDictionary<int, TDSFedAuthInfoOption>();
-        }
-
-        /// <summary>
-        /// Inflating constructor.
-        /// </summary>
-        /// <param name="source"></param>
-        public TDSFedAuthInfoToken(Stream source) :
-            this()
-        {
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from.</param>
-        /// <returns>True in case of success, false otherwise.</returns>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-            TDSFedAuthInfoId currentFeatureType = TDSFedAuthInfoId.Invalid;
-
-            uint infoDataLength = 0;
-            uint infoDataOffset = 0;
-
-            uint tokenLength = TDSUtilities.ReadUInt(source);
-            uint countOfIds = TDSUtilities.ReadUInt(source);
-
-            int i = 0;
-
-            do
-            {
-                // Read feature type.
-                //
-                currentFeatureType = (TDSFedAuthInfoId)source.ReadByte();
-
-                // Ensure we're not looking at the terminator.
-                //
-                switch (currentFeatureType)
-                {
-                    case TDSFedAuthInfoId.STSURL:
-                        {
-                            // Create an STSURL option.
-                            //
-                            infoDataLength = TDSUtilities.ReadUInt(source);
-                            infoDataOffset = TDSUtilities.ReadUInt(source);
-                            Options.Add(i++, new TDSFedAuthInfoOptionSTSURL(infoDataLength));
-                            break;
-                        }
-
-                    case TDSFedAuthInfoId.SPN:
-                        {
-                            // Create SPN option.
-                            //
-                            infoDataLength = TDSUtilities.ReadUInt(source);
-                            infoDataOffset = TDSUtilities.ReadUInt(source);
-                            Options.Add(i++, new TDSFedAuthInfoOptionSPN(infoDataLength));
-                            break;
-                        }
-
-                    default:
-                        {
-                            // Create a new generic option
-                            // Options.Add(new TDSFeatureExtAckGenericOption(currentFeatureType, source));
-                            break;
-                        }
-                }
-            }
-            while (--countOfIds > 0);
-
-            foreach (TDSFedAuthInfoOption infoOption in Options.Values)
-            {
-                infoOption.Inflate(source);
-            }
-
-            // We're done inflating
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token.
-        /// </summary>
-        /// <param name="destination">Stream the token to deflate to.</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.FedAuthInfo);
-
-            // Length of all of the options' FedAuthInfoID, FedAuthInfoDataLen, and FedAuthInfoDataOffset fields.
-            // For each option, 1 byte for ID, 4 bytes for DataLen, 4 bytes for offset.
-            uint optionsLen = ((uint)Options.Count) * 9;
-
-            // Total length of the token, not including token identifier.
-            // 4 bytes for CountOfInfoIDs, plus optionsLen. FedAuthInfoData length is added below.
-            uint tokenLength = 4 + optionsLen;
-
-            // add to tokenLength the length of each option's data
-            MemoryStream[] optionStreams = new MemoryStream[Options.Count];
-            for (int i = 0; i < Options.Count; i++)
-            {
-                optionStreams[i] = new MemoryStream();
-                Options[i].Deflate(optionStreams[i]);
-                tokenLength += (uint)optionStreams[i].Length;
-            }
-
-            // Write TokenLength
-            TDSUtilities.WriteUInt(destination, tokenLength);
-
-            // Write CountOfInfoIDs
-            TDSUtilities.WriteUInt(destination, (uint)Options.Count);
-
-            // Write FedAuthInfoOpt fields.
-            // Offset is measured from address of CountOfInfoIDs, so start currOffset
-            // pointing after CountOfInfoIDs and FedAuthInfoOpt
-            uint currOffset = 4 + optionsLen;
-            for (int i = 0; i < Options.Count; i++)
-            {
-                destination.WriteByte((byte)Options[i].FedAuthInfoId);
-                TDSUtilities.WriteUInt(destination, (uint)optionStreams[i].Length);
-                TDSUtilities.WriteUInt(destination, currOffset);
-
-                currOffset += (uint)optionStreams[i].Length;
-            }
-
-            // Write FedAuthInfoData
-            for (int i = 0; i < Options.Count; i++)
-            {
-                optionStreams[i].WriteTo(destination);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthMessage/TDSFedAuthMessageToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/FedAuthMessage/TDSFedAuthMessageToken.cs
deleted file mode 100644 (file)
index b862eb8..0000000
+++ /dev/null
@@ -1,118 +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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS.Authentication
-{
-    /// <summary>
-    /// FedAuthToken Message definition.
-    /// </summary>
-    public class TDSFedAuthToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Federated Authentication Token
-        /// </summary>
-        private byte[] _token;
-
-        /// <summary>
-        /// Nonce
-        /// </summary>
-        private byte[] _nonce;
-
-        public byte[] Token { get { return _token; } }
-        public byte[] Nonce { get { return _nonce; } }
-
-        /// <summary>
-        /// Default Constructor.
-        /// </summary>
-        public TDSFedAuthToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor.
-        /// </summary>
-        /// <param name="token">Token</param>
-        public TDSFedAuthToken(byte[] token, byte[] nonce) :
-            this()
-        {
-            _token = new byte[token.Length];
-            token.CopyTo(_token, 0);
-
-            if (nonce != null)
-            {
-                _nonce = new byte[nonce.Length];
-                nonce.CopyTo(_nonce, 0);
-            }
-        }
-
-        /// <summary>
-        /// Inflating constructor.
-        /// </summary>
-        /// <param name="source"></param>
-        public TDSFedAuthToken(Stream source) :
-            this()
-        {
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from.</param>
-        /// <returns>True in case of success, false otherwise.</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read length of entire message
-            uint totalLengthOfData = TDSUtilities.ReadUInt(source);
-
-            // Read length of the fedauth token
-            uint tokenLength = TDSUtilities.ReadUInt(source);
-
-            // Read the fedauth token
-            _token = new byte[tokenLength];
-            source.Read(_token, 0, (int)tokenLength);
-
-            // Read nonce if it exists
-            if (totalLengthOfData > tokenLength)
-            {
-                _nonce = new byte[totalLengthOfData - tokenLength];
-                source.Read(_nonce, 0, (int)(totalLengthOfData - tokenLength));
-            }
-            else if (tokenLength > totalLengthOfData)
-            {
-                // token length cannot be greater than the total length of the message
-                return false;
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token.
-        /// </summary>
-        /// <param name="destination">Stream the token to deflate to.</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write the total Length
-            uint totalLengthOfData = (uint)(sizeof(uint) /*bytes to carry the token length itself*/ + _token.Length + ((_nonce != null) ? _nonce.Length : 0));
-            TDSUtilities.WriteUInt(destination, totalLengthOfData);
-
-            // Write the Length of FedAuthToken
-            TDSUtilities.WriteUInt(destination, (uint)_token.Length);
-
-            // Write Fake Token
-            destination.Write(_token, 0, _token.Length);
-
-            // Write Nonce
-            if (_nonce != null)
-            {
-                destination.Write(_nonce, 0, _nonce.Length);
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/IDeflatable.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/IDeflatable.cs
deleted file mode 100644 (file)
index bc0d8c4..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Interface that enables object deflation
-    /// </summary>
-    public interface IDeflatable
-    {
-        /// <summary>
-        /// Deflate the object into a byte stream
-        /// </summary>
-        void Deflate(Stream destination);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/IInflatable.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/IInflatable.cs
deleted file mode 100644 (file)
index bce4795..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Interface that enables partial, sequential and continuable object inflation
-    /// </summary>
-    public interface IInflatable
-    {
-        /// <summary>
-        /// Inflate the object using the next available chunk of byte stream
-        /// </summary>
-        /// <param name="next">Next chunk of data, not necessarily sufficient to inflate the object</param>
-        /// <returns>TRUE if object is completely inflated, FALSE otherwise</returns>
-        bool Inflate(Stream source);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Info/TDSInfoToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Info/TDSInfoToken.cs
deleted file mode 100644 (file)
index 3d01010..0000000
+++ /dev/null
@@ -1,225 +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;
-
-namespace Microsoft.SqlServer.TDS.Info
-{
-    /// <summary>
-    /// Environment change token "INFO"
-    /// </summary>
-    public class TDSInfoToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Number
-        /// </summary>
-        public uint Number { get; set; }
-
-        /// <summary>
-        /// State
-        /// </summary>
-        public byte State { get; set; }
-
-        /// <summary>
-        /// Class
-        /// </summary>
-        public byte Class { get; set; }
-
-        /// <summary>
-        /// Description
-        /// </summary>
-        public string Message { get; set; }
-
-        /// <summary>
-        /// Name of the server generated the message
-        /// </summary>
-        public string ServerName { get; set; }
-
-        /// <summary>
-        /// Procedure that produced the message
-        /// </summary>
-        public string ProcedureName { get; set; }
-
-        /// <summary>
-        /// Line number at which the message was produced
-        /// </summary>
-        public uint Line { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSInfoToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSInfoToken(uint number)
-        {
-            Number = number;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSInfoToken(uint number, byte state) :
-            this(number)
-        {
-            State = state;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSInfoToken(uint number, byte state, byte clazz) :
-            this(number, state)
-        {
-            Class = clazz;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSInfoToken(uint number, byte state, byte clazz, string message) :
-            this(number, state, clazz)
-        {
-            Message = message;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSInfoToken(uint number, byte state, byte clazz, string message, string serverName) :
-            this(number, state, clazz, message)
-        {
-            ServerName = serverName;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSInfoToken(uint number, byte state, byte clazz, string message, string serverName, string procedureName) :
-            this(number, state, clazz, message, serverName)
-        {
-            ProcedureName = procedureName;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSInfoToken(uint number, byte state, byte clazz, string message, string serverName, string procedureName, uint line) :
-            this(number, state, clazz, message, serverName, procedureName)
-        {
-            Line = line;
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSInfoToken(Stream source)
-        {
-            // Inflate the token
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-
-            // Read token length
-            ushort tokenLength = TDSUtilities.ReadUShort(source);
-
-            // Read the number
-            Number = TDSUtilities.ReadUInt(source);
-
-            // Read state
-            State = (byte)source.ReadByte();
-
-            // Read class
-            Class = (byte)source.ReadByte();
-
-            // Read the message text length
-            ushort textLength = TDSUtilities.ReadUShort(source);
-
-            // Read the message itself
-            Message = TDSUtilities.ReadString(source, (ushort)(textLength * 2));
-
-            // Read server name length
-            textLength = (byte)source.ReadByte();
-
-            // Read server name
-            ServerName = TDSUtilities.ReadString(source, (ushort)(textLength * 2));
-
-            // Read procedure name length
-            textLength = (byte)source.ReadByte();
-
-            // Read procedure name
-            ProcedureName = TDSUtilities.ReadString(source, (ushort)(textLength * 2));
-
-            // Read the line number
-            Line = TDSUtilities.ReadUInt(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.Info);
-
-            // Calculate the length
-            ushort totalLength = (ushort)(sizeof(uint) // Number
-                + sizeof(byte) // State
-                + sizeof(byte) // Class
-                + sizeof(ushort) + (string.IsNullOrEmpty(Message) ? 0 : Message.Length) * sizeof(char) // Message
-                + sizeof(byte) + (string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length) * sizeof(char) // Server Name
-                + sizeof(byte) + (string.IsNullOrEmpty(ProcedureName) ? 0 : ProcedureName.Length) * sizeof(char) // Procedure Name
-                + sizeof(uint)); // Line number
-
-            // Write token length
-            TDSUtilities.WriteUShort(destination, totalLength);
-
-            // Write the number
-            TDSUtilities.WriteUInt(destination, Number);
-
-            // Write state
-            destination.WriteByte((byte)State);
-
-            // Write class
-            destination.WriteByte((byte)Class);
-
-            // Write message text length
-            TDSUtilities.WriteUShort(destination, (ushort)(string.IsNullOrEmpty(Message) ? 0 : Message.Length));
-
-            // Write the message itself
-            TDSUtilities.WriteString(destination, Message);
-
-            // Write server name length
-            destination.WriteByte((byte)(string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length));
-
-            // Write server name
-            TDSUtilities.WriteString(destination, ServerName);
-
-            // Write procedure name length
-            destination.WriteByte((byte)(string.IsNullOrEmpty(ProcedureName) ? 0 : ProcedureName.Length));
-
-            // Write procedure name
-            TDSUtilities.WriteString(destination, ProcedureName);
-
-            // Write the line number
-            TDSUtilities.WriteUInt(destination, Line);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LanguageString.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LanguageString.cs
deleted file mode 100644 (file)
index a96751c..0000000
+++ /dev/null
@@ -1,346 +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;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Class that contains language names and can convert between enumeration and strings
-    /// </summary>
-    public static class LanguageString
-    {
-        private const string English = "us_english";
-        private const string German = "Deutsch";
-        private const string French = "Fran\u00E7ais";
-        private const string Japanese = "\u65E5\u672C\u8A9E";
-        private const string Danish = "Dansk";
-        private const string Spanish = "Espa\u00F1o";
-        private const string Italian = "Italiano";
-        private const string Dutch = "Nederlands";
-        private const string Norwegian = "Norsk";
-        private const string Portuguese = "Portugu\u00EAs";
-        private const string Finnish = "Suomi";
-        private const string Swedish = "Svenska";
-        private const string Czech = "\u010De\u0161tina";
-        private const string Hungarian = "magyar";
-        private const string Polish = "polski";
-        private const string Romanian = "rom\u00E2n\u0103";
-        private const string Croatian = "hrvatski";
-        private const string Slovak = "sloven\u010Dina";
-        private const string Slovenian = "slovenski";
-        private const string Greek = "\u03B5\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC";
-        private const string Bulgarian = "\u0431\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438";
-        private const string Russian = "\u0440\u0443\u0441\u0441\u043A\u0438\u0439";
-        private const string Turkish = "T\u00FCrk\u00E7e";
-        private const string BritishEnglish = "British";
-        private const string Estonian = "eesti";
-        private const string Latvian = "latvie\u0161u";
-        private const string Lithuanian = "lietuvi\u0173";
-        private const string Brazilian = "Portugu\u00EAs (Brasil)";
-        private const string TraditionalChinese = "\u7E41\u9AD4\u4E2D\u6587";
-        private const string Korean = "\uD55C\uAD6D\uC5B4";
-        private const string SimplifiedChinese = "\u7B80\u4F53\u4E2D\u6587";
-        private const string Arabic = "Arabic";
-        private const string Thai = "\u0E44\u0E17\u0E22";
-        private const string Bokmal = "norsk (bokm\u00E5l)";
-
-        /// <summary>
-        /// Convert a language to enumeration
-        /// </summary>
-        public static LanguageType ToEnum(string value)
-        {
-            // Check every langauge
-            if (English.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.English;
-            }
-            else if (German.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.German;
-            }
-            else if (French.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.French;
-            }
-            else if (Japanese.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Japanese;
-            }
-            else if (Danish.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Danish;
-            }
-            else if (Spanish.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Spanish;
-            }
-            else if (Italian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Italian;
-            }
-            else if (Dutch.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Dutch;
-            }
-            else if (Norwegian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Norwegian;
-            }
-            else if (Portuguese.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Portuguese;
-            }
-            else if (Finnish.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Finnish;
-            }
-            else if (Swedish.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Swedish;
-            }
-            else if (Czech.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Czech;
-            }
-            else if (Hungarian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Hungarian;
-            }
-            else if (Polish.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Polish;
-            }
-            else if (Romanian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Romanian;
-            }
-            else if (Croatian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Croatian;
-            }
-            else if (Slovak.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Slovak;
-            }
-            else if (Slovenian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Slovenian;
-            }
-            else if (Greek.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Greek;
-            }
-            else if (Bulgarian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Bulgarian;
-            }
-            else if (Russian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Russian;
-            }
-            else if (Turkish.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Turkish;
-            }
-            else if (BritishEnglish.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.BritishEnglish;
-            }
-            else if (Estonian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Estonian;
-            }
-            else if (Latvian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Latvian;
-            }
-            else if (Lithuanian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Lithuanian;
-            }
-            else if (Brazilian.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Brazilian;
-            }
-            else if (TraditionalChinese.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.TraditionalChinese;
-            }
-            else if (Korean.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Korean;
-            }
-            else if (SimplifiedChinese.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.SimplifiedChinese;
-            }
-            else if (Arabic.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Arabic;
-            }
-            else if (Thai.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Thai;
-            }
-            else if (Bokmal.Equals(value, StringComparison.CurrentCultureIgnoreCase))
-            {
-                return LanguageType.Bokmal;
-            }
-
-            // Unknown value
-            throw new Exception("Unrecognized language string \"" + value + "\"");
-        }
-
-        /// <summary>
-        /// Convert enumeration to string
-        /// </summary>
-        public static string ToString(LanguageType value)
-        {
-            // Switch through the langauges
-            switch (value)
-            {
-                case LanguageType.English:
-                    {
-                        return English;
-                    }
-                case LanguageType.German:
-                    {
-                        return German;
-                    }
-                case LanguageType.French:
-                    {
-                        return French;
-                    }
-                case LanguageType.Japanese:
-                    {
-                        return Japanese;
-                    }
-                case LanguageType.Danish:
-                    {
-                        return Danish;
-                    }
-                case LanguageType.Spanish:
-                    {
-                        return Spanish;
-                    }
-                case LanguageType.Italian:
-                    {
-                        return Italian;
-                    }
-                case LanguageType.Dutch:
-                    {
-                        return Dutch;
-                    }
-                case LanguageType.Norwegian:
-                    {
-                        return Norwegian;
-                    }
-                case LanguageType.Portuguese:
-                    {
-                        return Portuguese;
-                    }
-                case LanguageType.Finnish:
-                    {
-                        return Finnish;
-                    }
-                case LanguageType.Swedish:
-                    {
-                        return Swedish;
-                    }
-                case LanguageType.Czech:
-                    {
-                        return Czech;
-                    }
-                case LanguageType.Hungarian:
-                    {
-                        return Hungarian;
-                    }
-                case LanguageType.Polish:
-                    {
-                        return Polish;
-                    }
-                case LanguageType.Romanian:
-                    {
-                        return Romanian;
-                    }
-                case LanguageType.Croatian:
-                    {
-                        return Croatian;
-                    }
-                case LanguageType.Slovak:
-                    {
-                        return Slovak;
-                    }
-                case LanguageType.Slovenian:
-                    {
-                        return Slovenian;
-                    }
-                case LanguageType.Greek:
-                    {
-                        return Greek;
-                    }
-                case LanguageType.Bulgarian:
-                    {
-                        return Bulgarian;
-                    }
-                case LanguageType.Russian:
-                    {
-                        return Russian;
-                    }
-                case LanguageType.Turkish:
-                    {
-                        return Turkish;
-                    }
-                case LanguageType.BritishEnglish:
-                    {
-                        return BritishEnglish;
-                    }
-                case LanguageType.Estonian:
-                    {
-                        return Estonian;
-                    }
-                case LanguageType.Latvian:
-                    {
-                        return Latvian;
-                    }
-                case LanguageType.Lithuanian:
-                    {
-                        return Lithuanian;
-                    }
-                case LanguageType.Brazilian:
-                    {
-                        return Brazilian;
-                    }
-                case LanguageType.TraditionalChinese:
-                    {
-                        return TraditionalChinese;
-                    }
-                case LanguageType.Korean:
-                    {
-                        return Korean;
-                    }
-                case LanguageType.SimplifiedChinese:
-                    {
-                        return SimplifiedChinese;
-                    }
-                case LanguageType.Arabic:
-                    {
-                        return Arabic;
-                    }
-                case LanguageType.Thai:
-                    {
-                        return Thai;
-                    }
-                case LanguageType.Bokmal:
-                    {
-                        return Bokmal;
-                    }
-            }
-
-            // Unknown value
-            throw new Exception("Unrecognized language type \"" + value.ToString() + "\"");
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LanguageType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LanguageType.cs
deleted file mode 100644 (file)
index 85ac06f..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Language of the server
-    /// </summary>
-    public enum LanguageType
-    {
-        English,
-        German,
-        French,
-        Japanese,
-        Danish,
-        Spanish,
-        Italian,
-        Dutch,
-        Norwegian,
-        Portuguese,
-        Finnish,
-        Swedish,
-        Czech,
-        Hungarian,
-        Polish,
-        Romanian,
-        Croatian,
-        Slovak,
-        Slovenian,
-        Greek,
-        Bulgarian,
-        Russian,
-        Turkish,
-        BritishEnglish,
-        Estonian,
-        Latvian,
-        Lithuanian,
-        Brazilian,
-        TraditionalChinese,
-        Korean,
-        SimplifiedChinese,
-        Arabic,
-        Thai,
-        Bokmal
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FeatureOptionToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FeatureOptionToken.cs
deleted file mode 100644 (file)
index 5ac7066..0000000
+++ /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.IO;
-
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-using Microsoft.SqlServer.TDS.PreLogin;
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Class that defines a feature option which is delivered in the login packet FeatureExt block
-    /// </summary>
-    public abstract class TDSLogin7FeatureOptionToken : IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// Size of the data read during inflation operation. It is needed to properly parse the option stream.
-        /// </summary>
-        internal uint InflationSize { get; set; }
-
-        /// <summary>
-        /// Feature type
-        /// </summary>
-        public virtual TDSFeatureID FeatureID { get; protected set; }
-
-        /// <summary>
-        /// Inflate the Feature option
-        /// </summary>
-        public abstract bool Inflate(Stream source);
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        public abstract void Deflate(Stream destination);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FeatureOptionsToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FeatureOptionsToken.cs
deleted file mode 100644 (file)
index 2a1c969..0000000
+++ /dev/null
@@ -1,110 +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.Collections.Generic;
-
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-using Microsoft.SqlServer.TDS.SessionState;
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Feature extension data delivered in the login packet
-    /// </summary>
-    public class TDSLogin7FeatureOptionsToken : List<TDSLogin7FeatureOptionToken>, IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// Property used internally by inflation/deflation routine to tell caller how much data was read/written to the stream
-        /// </summary>
-        internal uint InflationSize { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7FeatureOptionsToken()
-        {
-        }
-
-        /// <summary>
-        /// Inflate an object instance from the stream
-        /// </summary>
-        public bool Inflate(Stream source)
-        {
-            // Identifier of the feature
-            TDSFeatureID featureID = TDSFeatureID.Terminator;
-
-            // Iterate
-            do
-            {
-                // Read the feature type
-                featureID = (TDSFeatureID)source.ReadByte();
-
-                // Token being inflated
-                TDSLogin7FeatureOptionToken optionToken = null;
-
-                // skip this feature extension
-                switch (featureID)
-                {
-                    case TDSFeatureID.FederatedAuthentication:
-                        {
-                            // Federated authentication
-                            optionToken = new TDSLogin7FedAuthOptionToken();
-                            break;
-                        }
-                    case TDSFeatureID.SessionRecovery:
-                        {
-                            // Session recovery
-                            optionToken = new TDSLogin7SessionRecoveryOptionToken();
-                            break;
-                        }
-                    case TDSFeatureID.Terminator:
-                        {
-                            // Do nothing
-                            break;
-                        }
-                    default:
-                        {
-                            // Create a generic option
-                            optionToken = new TDSLogin7GenericOptionToken(featureID);
-                            break;
-                        }
-                }
-
-                // Check if we have an option token
-                if (optionToken != null)
-                {
-                    // Inflate it
-                    optionToken.Inflate(source);
-
-                    // Register with the collection
-                    Add(optionToken);
-
-                    // Update inflation offset
-                    InflationSize += optionToken.InflationSize;
-                }
-            }
-            while (TDSFeatureID.Terminator != featureID);
-
-            // We don't support continuation of inflation so report as fully inflated
-            return true;
-        }
-
-        /// <summary>
-        /// Serialize object into the stream
-        /// </summary>
-        /// <param name="destination"></param>
-        public void Deflate(Stream destination)
-        {
-            // Deflate each feature extension
-            foreach (TDSLogin7FeatureOptionToken option in this)
-            {
-                option.Deflate(destination);
-            }
-
-            // Write the Terminator.
-            destination.WriteByte((byte)TDSFeatureID.Terminator);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FedAuthOptionToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7FedAuthOptionToken.cs
deleted file mode 100644 (file)
index 9ba3bfc..0000000
+++ /dev/null
@@ -1,380 +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.Security.Cryptography;
-
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-using Microsoft.SqlServer.TDS.PreLogin;
-
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// The Federated authentication library type.
-    /// </summary>
-    public enum TDSFedAuthLibraryType : byte
-    {
-        IDCRL = 0x00,
-        SECURITY_TOKEN = 0x01,
-        ADAL = 0x02,
-        UNSUPPORTED = 0x03,
-    }
-
-    public enum TDSFedAuthADALWorkflow : byte
-    {
-        USERNAME_PASSWORD = 0X01,
-    }
-
-    /// <summary>
-    /// Feature option token definition.
-    /// </summary>
-    public class TDSLogin7FedAuthOptionToken : TDSLogin7FeatureOptionToken
-    {
-        /// <summary>
-        /// Nonce's length
-        /// </summary>
-        private static readonly uint s_nonceDataLength = 32;
-
-        /// <summary>
-        /// Signature's length
-        /// </summary>
-        private static readonly uint s_signatureDataLength = 32;
-
-        /// <summary>
-        /// Feature type
-        /// </summary>
-        public override TDSFeatureID FeatureID { get { return TDSFeatureID.FederatedAuthentication; } }
-
-        /// <summary>
-        /// Federated Authentication option length
-        /// </summary>
-        public uint Length
-        {
-            get
-            {
-                return (uint)(sizeof(byte) // Option (library + echo)
-                    + sizeof(uint) // Token length variable
-                    + (Token == null ? 0 : Token.Length) // Actual token length
-                    + (Nonce == null ? 0 : s_nonceDataLength) // Nonce Length
-                    + (ChannelBingingToken == null ? 0 : ChannelBingingToken.Length) // Channel binding token
-                    + (Signature == null ? 0 : s_signatureDataLength) // signature
-                    + (Library == TDSFedAuthLibraryType.ADAL ? 1 : 0)); // Workflow
-            }
-        }
-
-        /// <summary>
-        /// Federated authentication library.
-        /// </summary>
-        public TDSFedAuthLibraryType Library { get; private set; }
-
-        /// <summary>
-        /// FedAuthEcho: The intention of this flag is for the client to echo the server's FEDAUTHREQUIRED prelogin option.
-        /// </summary>
-        public TdsPreLoginFedAuthRequiredOption Echo { get; private set; }
-
-        /// <summary>
-        /// Whether this protocol is requesting further information from server to perform authentication.
-        /// </summary>
-        public bool IsRequestingAuthenticationInfo { get; private set; }
-
-        /// <summary>
-        /// Federated authentication token generated by the specified federated authentication library.
-        /// </summary>
-        public byte[] Token { get; private set; }
-
-        /// <summary>
-        /// The nonce provided by the server during prelogin exchange
-        /// </summary>
-        public byte[] Nonce { get; private set; }
-
-        /// <summary>
-        /// Channel binding token associated with the underlying SSL stream.
-        /// </summary>
-        public byte[] ChannelBingingToken { get; private set; }
-
-        /// <summary>
-        /// The HMAC-SHA-256 [RFC6234] of the server-specified nonce
-        /// </summary>
-        public byte[] Signature { get; private set; }
-
-        public TDSFedAuthADALWorkflow Workflow { get; private set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7FedAuthOptionToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization Constructor.
-        /// </summary>
-        public TDSLogin7FedAuthOptionToken(TdsPreLoginFedAuthRequiredOption echo,
-                                            TDSFedAuthLibraryType libraryType,
-                                            byte[] token,
-                                            byte[] nonce,
-                                            byte[] channelBindingToken,
-                                            bool fIncludeSignature,
-                                            bool fRequestingFurtherInfo,
-                                            TDSFedAuthADALWorkflow workflow = TDSFedAuthADALWorkflow.USERNAME_PASSWORD)
-            : this()
-        {
-            Echo = echo;
-            Library = libraryType;
-            Token = token;
-            Nonce = nonce;
-            ChannelBingingToken = channelBindingToken;
-            IsRequestingAuthenticationInfo = fRequestingFurtherInfo;
-            Workflow = workflow;
-
-            if (libraryType != TDSFedAuthLibraryType.SECURITY_TOKEN && fIncludeSignature)
-            {
-                Signature = new byte[s_signatureDataLength];
-                Signature = _GenerateRandomBytes(32);
-            }
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSLogin7FedAuthOptionToken(Stream source)
-            : this()
-        {
-            // Inflate feature extension data
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // We skip option identifier because it was read by construction factory
-            // Read the length of the data for the option
-            uint optionDataLength = TDSUtilities.ReadUInt(source);
-
-            // Update inflation offset
-            InflationSize += sizeof(uint);
-
-            // Read one byte for the flags
-            byte temp = (byte)source.ReadByte();
-
-            // Update inflation offset
-            InflationSize += sizeof(byte);
-
-            // Get the bit and set as a fedauth echo bit
-            Echo = (TdsPreLoginFedAuthRequiredOption)(temp & 0x01);
-
-            // Get the remaining 7 bits and set as a library.
-            Library = (TDSFedAuthLibraryType)(temp >> 1);
-
-            // When using the ADAL library, a FedAuthToken is never included, nor is its length included
-            if (Library != TDSFedAuthLibraryType.ADAL)
-            {
-                // Length of the FedAuthToken
-                uint fedauthTokenLen = TDSUtilities.ReadUInt(source);
-
-                // Update inflation offset
-                InflationSize += sizeof(uint);
-
-                // Check if the fedauth token is in the login7
-                if (fedauthTokenLen > 0)
-                {
-                    // Allocate a container
-                    Token = new byte[fedauthTokenLen];
-
-                    // Read the Fedauth token.
-                    source.Read(Token, 0, (int)fedauthTokenLen);
-
-                    // Update inflation offset
-                    InflationSize += fedauthTokenLen;
-                }
-            }
-            else
-            {
-                // Instead the workflow is included
-                Workflow = (TDSFedAuthADALWorkflow)source.ReadByte();
-            }
-
-            switch (Library)
-            {
-                case TDSFedAuthLibraryType.IDCRL:
-                    IsRequestingAuthenticationInfo = false;
-                    return ReadIDCRLLogin(source, optionDataLength);
-
-                case TDSFedAuthLibraryType.SECURITY_TOKEN:
-                    IsRequestingAuthenticationInfo = false;
-                    return ReadSecurityTokenLogin(source, optionDataLength);
-
-                case TDSFedAuthLibraryType.ADAL:
-                    IsRequestingAuthenticationInfo = true;
-                    return true;
-
-                default:
-                    return false;
-            }
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write option identifier
-            destination.WriteByte((byte)FeatureID);
-
-            // Calculate Feature Data length
-            uint optionDataLength = (uint)(sizeof(byte) // Options size (library and Echo)
-                                    + ((Token == null && IsRequestingAuthenticationInfo) ? 0 : sizeof(uint)) // Fedauth token length
-                                    + (Token == null ? 0 : (uint)Token.Length) // Fedauth Token
-                                    + (Nonce == null ? 0 : s_nonceDataLength) // Nonce
-                                    + (ChannelBingingToken == null ? 0 : (uint)ChannelBingingToken.Length) // Channel binding
-                                    + (Signature == null ? 0 : s_signatureDataLength) // Signature
-                                    + (Library == TDSFedAuthLibraryType.ADAL ? 1 : 0)); // Workflow
-
-            // Write the cache length into the destination
-            TDSUtilities.WriteUInt(destination, optionDataLength);
-
-            // Construct a byte from fedauthlibrary and fedauth echo.
-            byte temp = (byte)((((byte)(Library) << 1) | (byte)(Echo)));
-            destination.WriteByte(temp);
-
-            // Write FederatedAuthenticationRequired token.
-            if (Token == null && !IsRequestingAuthenticationInfo)
-            {
-                // Write the length of the token is 0
-                TDSUtilities.WriteUInt(destination, 0);
-            }
-            else if (Token != null)
-            {
-                // Write the FederatedAuthenticationRequired token length.
-                TDSUtilities.WriteUInt(destination, (uint)Token.Length);
-
-                // Write the token.
-                destination.Write(Token, 0, Token.Length);
-            }
-
-            if (Nonce != null)
-            {
-                // Write the nonce
-                destination.Write(Nonce, 0, Nonce.Length);
-            }
-
-            // Write the Channel Binding length
-            if (ChannelBingingToken != null)
-            {
-                destination.Write(ChannelBingingToken, 0, ChannelBingingToken.Length);
-            }
-
-            if (Signature != null)
-            {
-                // Write Signature
-                destination.Write(Signature, 0, (int)s_signatureDataLength);
-            }
-
-            if (Library == TDSFedAuthLibraryType.ADAL)
-            {
-                // Write Workflow
-                destination.WriteByte((byte)Workflow);
-            }
-        }
-
-        /// <summary>
-        /// Read the stream for IDCRL based login
-        /// </summary>
-        /// <param name="source">source</param>
-        /// <param name="optionDataLength">option data length</param>
-        /// <returns></returns>
-        private bool ReadIDCRLLogin(Stream source, uint optionDataLength)
-        {
-            // Allocate a container
-            Nonce = new byte[s_nonceDataLength];
-
-            // Read the nonce
-            source.Read(Nonce, 0, (int)s_nonceDataLength);
-
-            // Update inflation offset
-            InflationSize += s_nonceDataLength;
-
-            // Calculate the Channel binding data length.
-            uint channelBindingTokenLength = optionDataLength
-                                            - sizeof(byte) // Options size (library and Echo)
-                                            - sizeof(uint) // Token size
-                                            - (Token == null ? 0 : (uint)Token.Length) // Token
-                                            - s_nonceDataLength // Nonce length
-                                            - s_signatureDataLength; // Signature Length
-
-            // Read the channelBindingToken
-            if (channelBindingTokenLength > 0)
-            {
-                // Allocate a container
-                ChannelBingingToken = new byte[channelBindingTokenLength];
-
-                // Read the channel binding part.
-                source.Read(ChannelBingingToken, 0, (int)channelBindingTokenLength);
-
-                // Update inflation offset
-                InflationSize += channelBindingTokenLength;
-            }
-
-            // Allocate Signature
-            Signature = new byte[s_signatureDataLength];
-
-            // Read the Signature
-            source.Read(Signature, 0, (int)s_signatureDataLength);
-
-            // Update inflation offset
-            InflationSize += s_signatureDataLength;
-
-            return true;
-        }
-
-        /// <summary>
-        /// Read the stream for SecurityToken based login
-        /// </summary>
-        /// <param name="source">source</param>
-        /// <param name="optionDataLength">option data length</param>
-        /// <returns></returns>
-        private bool ReadSecurityTokenLogin(Stream source, uint optionDataLength)
-        {
-            // Check if any data is available
-            if (optionDataLength > InflationSize)
-            {
-                // Allocate a container
-                Nonce = new byte[s_nonceDataLength];
-
-                // Read the nonce
-                source.Read(Nonce, 0, (int)s_nonceDataLength);
-
-                // Update inflation offset
-                InflationSize += s_nonceDataLength;
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Generates random bytes
-        /// </summary>
-        /// <param name="count">The number of bytes to be generated.</param>
-        /// <returns>Generated random bytes.</returns>
-        private byte[] _GenerateRandomBytes(int count)
-        {
-            byte[] randomBytes = new byte[count];
-
-            RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
-            // Generate bytes
-            gen.GetBytes(randomBytes);
-
-            return randomBytes;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7GenericOptionToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7GenericOptionToken.cs
deleted file mode 100644 (file)
index 8a2be30..0000000
+++ /dev/null
@@ -1,115 +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 Microsoft.SqlServer.TDS.FeatureExtAck;
-using Microsoft.SqlServer.TDS.PreLogin;
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Option token that can contain any data and doesn't have specialized inflation/deflation logic
-    /// </summary>
-    public class TDSLogin7GenericOptionToken : TDSLogin7FeatureOptionToken
-    {
-        /// <summary>
-        /// Data that the token is carrying
-        /// </summary>
-        public byte[] Data { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7GenericOptionToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7GenericOptionToken(TDSFeatureID featureID)
-        {
-            // Save feature identifier
-            FeatureID = featureID;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7GenericOptionToken(TDSFeatureID featureID, byte[] data) :
-            this(featureID)
-        {
-            // Save data
-            Data = data;
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSLogin7GenericOptionToken(Stream source) :
-            this()
-        {
-            // Inflate feature extension data
-            Inflate(source);
-        }
-
-
-        /// <summary>
-        /// Inflate the Feature option
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // Skip feature ID inflation because it was read by options collection
-
-            // Read the length
-            int length = (int)TDSUtilities.ReadUInt(source);
-
-            // Update inflation size
-            InflationSize += sizeof(int);
-
-            // Allocate a container for the specified length
-            Data = new byte[length];
-
-            // Read the data
-            source.Read(Data, 0, Data.Length);
-
-            // Update inflation size
-            InflationSize += (uint)length;
-
-            // We've inflated the token option
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream the token to deflate to.</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write feature ID
-            destination.WriteByte((byte)FeatureID);
-
-            // Check if feature data is available
-            if (Data == null)
-            {
-                // Length is zero
-                TDSUtilities.WriteUInt(destination, 0);
-            }
-            else
-            {
-                // Write the length
-                TDSUtilities.WriteUInt(destination, (uint)Data.Length);
-
-                // Write the data itself
-                destination.Write(Data, 0, Data.Length);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7SessionRecoveryOptionToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7SessionRecoveryOptionToken.cs
deleted file mode 100644 (file)
index 93736ca..0000000
+++ /dev/null
@@ -1,129 +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 Microsoft.SqlServer.TDS.SessionState;
-using Microsoft.SqlServer.TDS.PreLogin;
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Token that is sent in the login packet for session recovery
-    /// </summary>
-    public class TDSLogin7SessionRecoveryOptionToken : TDSLogin7FeatureOptionToken
-    {
-        /// <summary>
-        /// Feature type
-        /// </summary>
-        public override TDSFeatureID FeatureID { get { return TDSFeatureID.SessionRecovery; } }
-
-        /// <summary>
-        /// Initial state
-        /// </summary>
-        public TDSSessionRecoveryData Initial { get; set; }
-
-        /// <summary>
-        /// Current state
-        /// </summary>
-        public TDSSessionRecoveryData Current { get; set; }
-
-        /// <summary>
-        /// Initialization Constructor.
-        /// </summary>
-        public TDSLogin7SessionRecoveryOptionToken()
-        {
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSLogin7SessionRecoveryOptionToken(Stream source) :
-            this()
-        {
-            // Inflate feature extension data
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // We skip option identifier because it was read by construction factory
-
-            // Read the length of the data for the option
-            uint optionDataLength = TDSUtilities.ReadUInt(source);
-
-            // Update inflation offset
-            InflationSize += sizeof(uint);
-
-            // Check if we still have space to read
-            if (InflationSize >= optionDataLength)
-            {
-                // Inflation is complete
-                return true;
-            }
-
-            // Inflate initial data set
-            Initial = new TDSSessionRecoveryData(source);
-
-            // Update inflation size with initial data set
-            InflationSize += Initial.InflationSize;
-
-            // Check if we still have space to read
-            if (InflationSize >= optionDataLength)
-            {
-                // Inflation is complete
-                return true;
-            }
-
-            // Inflate delta data set
-            Current = new TDSSessionRecoveryData(source);
-
-            // Update inflation size with initial data set
-            InflationSize += Current.InflationSize;
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write option identifier
-            destination.WriteByte((byte)FeatureID);
-
-            // Deflate the token into the memory cache to calculate the length
-            MemoryStream cache = new MemoryStream();
-
-            // Check if we have an initial state
-            if (Initial != null)
-            {
-                // Deflate initial state
-                Initial.Deflate(cache);
-            }
-
-            // Check if we have a delta state
-            if (Current != null)
-            {
-                // Deflate initial state
-                Current.Deflate(cache);
-            }
-
-            // Write the cache length into the destination
-            TDSUtilities.WriteUInt(destination, (uint)cache.Length);
-
-            // Write cache itself
-            cache.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7Token.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7Token.cs
deleted file mode 100644 (file)
index cc3dd12..0000000
+++ /dev/null
@@ -1,640 +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.IO;
-using System.Linq;
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Login 7 request packet
-    /// </summary>
-    public class TDSLogin7Token : TDSPacketToken
-    {
-        /// <summary>
-        /// Length of the fixed portion of the packet
-        /// </summary>
-        protected static ushort FixedPacketLength = sizeof(uint)  // Length
-                + sizeof(uint)  // TDSVersion
-                + sizeof(uint)  // PacketSize
-                + sizeof(uint)  // ClientProgramVersion
-                + sizeof(uint)  // ClientPID
-                + sizeof(uint)  // ConnectionID
-                + sizeof(byte)  // OptionalFlags1
-                + sizeof(byte)  // OptionalFlags2
-                + sizeof(byte)  // OptionalFlags3
-                + sizeof(byte)  // TypeFlags
-                + sizeof(int)  // ClientTimeZone
-                + sizeof(uint)  // ClientLCID
-                + sizeof(ushort) + sizeof(ushort)  // HostName
-                + sizeof(ushort) + sizeof(ushort)  // UserID
-                + sizeof(ushort) + sizeof(ushort)  // Password
-                + sizeof(ushort) + sizeof(ushort)  // ApplicationName
-                + sizeof(ushort) + sizeof(ushort)  // ServerName
-                + sizeof(ushort) + sizeof(ushort)  // Unused
-                + sizeof(ushort) + sizeof(ushort)  // LibraryName
-                + sizeof(ushort) + sizeof(ushort)  // Language
-                + sizeof(ushort) + sizeof(ushort)  // Database
-                + 6 * sizeof(byte)  // ClientID
-                + sizeof(ushort) + sizeof(ushort)  // SSPI
-                + sizeof(ushort) + sizeof(ushort)  // AttachDatabaseFile
-                + sizeof(ushort) + sizeof(ushort)  // ChangePassword
-                + sizeof(uint);  // LongSSPI;
-
-        /// <summary>
-        /// Version of the TDS protocol
-        /// </summary>
-        public Version TDSVersion { get; set; }
-
-        /// <summary>
-        /// Size of the TDS packet requested by the client
-        /// </summary>
-        public uint PacketSize { get; set; }
-
-        /// <summary>
-        /// Version of the client application
-        /// </summary>
-        public uint ClientProgramVersion { get; set; }
-
-        /// <summary>
-        /// Client application process identifier
-        /// </summary>
-        public uint ClientPID { get; set; }
-
-        /// <summary>
-        /// Connection identifier
-        /// </summary>
-        public uint ConnectionID { get; set; }
-
-        /// <summary>
-        /// First byte of optional flags
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags1 OptionalFlags1 { get; set; }
-
-        /// <summary>
-        /// Second byte of optional flags
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags2 OptionalFlags2 { get; set; }
-
-        /// <summary>
-        /// Third byte of optional flags
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags3 OptionalFlags3 { get; set; }
-
-        /// <summary>
-        /// Type flags
-        /// </summary>
-        public TDSLogin7TokenTypeFlags TypeFlags { get; set; }
-
-        /// <summary>
-        /// Time zone of the client
-        /// </summary>
-        public int ClientTimeZone { get; set; }
-
-        /// <summary>
-        /// Client locale identifier
-        /// </summary>
-        public uint ClientLCID { get; set; }
-
-        /// <summary>
-        /// Client host name
-        /// </summary>
-        public string HostName { get; set; }
-
-        /// <summary>
-        /// User ID
-        /// </summary>
-        public string UserID { get; set; }
-
-        /// <summary>
-        /// Password
-        /// </summary>
-        public string Password { get; set; }
-
-        /// <summary>
-        /// Application name
-        /// </summary>
-        public string ApplicationName { get; set; }
-
-        /// <summary>
-        /// Server name
-        /// </summary>
-        public string ServerName { get; set; }
-
-        /// <summary>
-        /// Client library name
-        /// </summary>
-        public string LibraryName { get; set; }
-
-        /// <summary>
-        /// User language
-        /// </summary>
-        public string Language { get; set; }
-
-        /// <summary>
-        /// User database
-        /// </summary>
-        public string Database { get; set; }
-
-        /// <summary>
-        /// Unique client identifier
-        /// </summary>
-        public byte[] ClientID { get; set; }
-
-        /// <summary>
-        /// Attach database file
-        /// </summary>
-        public string AttachDatabaseFile { get; set; }
-
-        /// <summary>
-        /// Change password
-        /// </summary>
-        public string ChangePassword { get; set; }
-
-        /// <summary>
-        /// SSPI authentication blob
-        /// </summary>
-        public byte[] SSPI { get; set; }
-
-        /// <summary>
-        /// Feature extension in the login7.
-        /// </summary>
-        public TDSLogin7FeatureOptionsToken FeatureExt { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7Token()
-        {
-            // Instantiate the first optional flags
-            OptionalFlags1 = new TDSLogin7TokenOptionalFlags1();
-
-            // Instantiate the second optional flags
-            OptionalFlags2 = new TDSLogin7TokenOptionalFlags2();
-
-            // Instantiate the third optional flags
-            OptionalFlags3 = new TDSLogin7TokenOptionalFlags3();
-
-            // Instantiate type flags
-            TypeFlags = new TDSLogin7TokenTypeFlags();
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSLogin7Token(Stream source)
-        {
-            // Inflate token
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read packet length
-            uint length = TDSUtilities.ReadUInt(source);
-
-            // Read TDS version
-            string tdsVersion = string.Format("{0:X}", TDSUtilities.ReadUInt(source));
-
-            // Consturct TDS version
-            TDSVersion = new Version(int.Parse(tdsVersion.Substring(0, 1)), int.Parse(tdsVersion.Substring(1, 1)), Convert.ToInt32(tdsVersion.Substring(2, 2), 16), Convert.ToInt32(tdsVersion.Substring(4, 4), 16));
-
-            // Read packet length
-            PacketSize = TDSUtilities.ReadUInt(source);
-
-            // Read client program version
-            ClientProgramVersion = TDSUtilities.ReadUInt(source);
-
-            // Read client program identifier
-            ClientPID = TDSUtilities.ReadUInt(source);
-
-            // Read connection identifier
-            ConnectionID = TDSUtilities.ReadUInt(source);
-
-            // Instantiate the first optional flags
-            OptionalFlags1 = new TDSLogin7TokenOptionalFlags1((byte)source.ReadByte());
-
-            // Instantiate the second optional flags
-            OptionalFlags2 = new TDSLogin7TokenOptionalFlags2((byte)source.ReadByte());
-
-            // Instantiate type flags
-            TypeFlags = new TDSLogin7TokenTypeFlags((byte)source.ReadByte());
-
-            // Instantiate the third optional flags
-            OptionalFlags3 = new TDSLogin7TokenOptionalFlags3((byte)source.ReadByte());
-
-            // Read client time zone
-            ClientTimeZone = TDSUtilities.ReadInt(source);
-
-            // Read client locale identifier
-            ClientLCID = TDSUtilities.ReadUInt(source);
-
-            // Prepare a collection of property values that will be set later
-            IList<TDSLogin7TokenOffsetProperty> variableProperties = new List<TDSLogin7TokenOffsetProperty>();
-
-            // Read client host name
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("HostName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read user name and password
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("UserID"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Password"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read application name
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ApplicationName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read server name
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ServerName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Check if extension is used
-            if (OptionalFlags3.ExtensionFlag)
-            {
-                // Read Feature extension. Note that this is just an offset of the value, not the value itself
-                variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("FeatureExt"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source), true));
-            }
-            else
-            {
-                // Skip unused
-                TDSUtilities.ReadUShort(source);
-                TDSUtilities.ReadUShort(source);
-            }
-
-            // Read client library name
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("LibraryName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read language
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Language"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read database
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Database"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            ClientID = new byte[6];
-
-            // Read unique client identifier
-            source.Read(ClientID, 0, ClientID.Length);
-
-            // Read SSPI blob
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("SSPI"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read database file to be attached
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("AttachDatabaseFile"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read password change
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ChangePassword"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source)));
-
-            // Read long SSPI
-            uint sspiLength = TDSUtilities.ReadUInt(source);
-
-            // At this point we surpassed the fixed packet length
-            long inflationOffset = FixedPacketLength;
-
-            // Order strings in ascending order by offset
-            // For the most cases this should not change the order of the options in the stream, but just in case
-            variableProperties = variableProperties.OrderBy(p => p.Position).ToList();
-
-            // We can't use "foreach" because FeatureExt processing changes the collection hence we can only go index-based way
-            int iCurrentProperty = 0;
-
-            // Iterate over each property
-            while (iCurrentProperty < variableProperties.Count)
-            {
-                // Get the property at the indexed position
-                TDSLogin7TokenOffsetProperty property = variableProperties[iCurrentProperty];
-
-                // Check if length is positive
-                if (property.Length == 0)
-                {
-                    // Move to the next propety
-                    iCurrentProperty++;
-                    continue;
-                }
-
-                // Ensure that current offset points to the option
-                while (inflationOffset < property.Position)
-                {
-                    // Read the stream
-                    source.ReadByte();
-
-                    // Advance position
-                    inflationOffset++;
-                }
-
-                // Check special properties
-                if (property.Property.Name == "Password" || property.Property.Name == "ChangePassword")
-                {
-                    // Read passwod string
-                    property.Property.SetValue(this, TDSUtilities.ReadPasswordString(source, (ushort)(property.Length * 2)), null);
-
-                    // Advance the position
-                    inflationOffset += (property.Length * 2);
-                }
-                else if (property.Property.Name == "SSPI")
-                {
-                    // If cbSSPI < USHRT_MAX, then this length MUST be used for SSPI and cbSSPILong MUST be ignored.
-                    // If cbSSPI == USHRT_MAX, then cbSSPILong MUST be checked.
-                    if (property.Length == ushort.MaxValue)
-                    {
-                        // If cbSSPILong > 0, then that value MUST be used. If cbSSPILong ==0, then cbSSPI (USHRT_MAX) MUST be used.
-                        if (sspiLength > 0)
-                        {
-                            // We don't know how to handle SSPI packets that exceed TDS packet size
-                            throw new NotSupportedException("Long SSPI blobs are not supported yet");
-                        }
-                    }
-
-                    // Use short length instead
-                    sspiLength = property.Length;
-
-                    // Allocate buffer for SSPI data
-                    SSPI = new byte[sspiLength];
-
-                    // Read SSPI blob
-                    source.Read(SSPI, 0, SSPI.Length);
-
-                    // Advance the position
-                    inflationOffset += sspiLength;
-                }
-                else if (property.Property.Name == "FeatureExt")
-                {
-                    // Check if this is the property or a pointer to the property
-                    if (property.IsOffsetOffset)
-                    {
-                        // Read the actual offset of the feature extension
-                        property.Position = TDSUtilities.ReadUInt(source);
-
-                        // Mark that now we have actual value
-                        property.IsOffsetOffset = false;
-
-                        // Advance the position
-                        inflationOffset += sizeof(uint);
-
-                        // Re-order the collection
-                        variableProperties = variableProperties.OrderBy(p => p.Position).ToList();
-
-                        // Subtract position to stay on the same spot for subsequent property
-                        iCurrentProperty--;
-                    }
-                    else
-                    {
-                        // Create a list of features.
-                        FeatureExt = new TDSLogin7FeatureOptionsToken();
-
-                        // Inflate feature extension
-                        FeatureExt.Inflate(source);
-
-                        // Advance position by the size of the inflated token
-                        inflationOffset += FeatureExt.InflationSize;
-                    }
-                }
-                else
-                {
-                    // Read the string and assign it to the property of this instance
-                    property.Property.SetValue(this, TDSUtilities.ReadString(source, (ushort)(property.Length * 2)), null);
-
-                    // Advance the position
-                    inflationOffset += (property.Length * 2);
-                }
-
-                // Advance to the next property
-                iCurrentProperty++;
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Calculate total length by adding strings
-            uint totalPacketLength = (uint)(FixedPacketLength
-                + (uint)(string.IsNullOrEmpty(HostName) ? 0 : HostName.Length * 2)  // HostName
-                + (uint)(string.IsNullOrEmpty(UserID) ? 0 : UserID.Length * 2)  // UserID
-                + (uint)(string.IsNullOrEmpty(Password) ? 0 : Password.Length * 2)  // Password
-                + (uint)(string.IsNullOrEmpty(ApplicationName) ? 0 : ApplicationName.Length * 2)  // ApplicationName
-                + (uint)(string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length * 2)  // ServerName
-                + (uint)(string.IsNullOrEmpty(LibraryName) ? 0 : LibraryName.Length * 2)  // LibraryName
-                + (uint)(string.IsNullOrEmpty(Language) ? 0 : Language.Length * 2)  // Language
-                + (uint)(string.IsNullOrEmpty(Database) ? 0 : Database.Length * 2)  // Database
-                + (uint)(string.IsNullOrEmpty(AttachDatabaseFile) ? 0 : AttachDatabaseFile.Length * 2)  // AttachDatabaseFile
-                + (uint)(string.IsNullOrEmpty(ChangePassword) ? 0 : ChangePassword.Length * 2)  // ChangePassword
-                + (uint)(SSPI == null ? 0 : SSPI.Length)  // SSPI
-                + 0);  // Feature extension
-
-            MemoryStream featureExtension = null;
-
-            // Check if we have a feature extension
-            if (FeatureExt != null)
-            {
-                // Allocate feature extension block
-                featureExtension = new MemoryStream();
-
-                // Serialize feature extension
-                FeatureExt.Deflate(featureExtension);
-
-                // Update total lentgh
-                totalPacketLength += (uint)(sizeof(uint) /* Offset of feature extension data */ + featureExtension.Length /* feature extension itself*/);
-            }
-
-            // Write packet length
-            TDSUtilities.WriteUInt(destination, totalPacketLength);
-
-            // Compile TDS version
-            uint tdsVersion = Convert.ToUInt32(string.Format("{0:X}", Math.Max(TDSVersion.Major, 0)) + string.Format("{0:X}", Math.Max(TDSVersion.Minor, 0)) + string.Format("{0:X2}", Math.Max(TDSVersion.Build, 0)) + string.Format("{0:X4}", Math.Max(TDSVersion.Revision, 0)), 16);
-
-            // Write TDS version
-            TDSUtilities.WriteUInt(destination, tdsVersion);
-
-            // Write packet length
-            TDSUtilities.WriteUInt(destination, PacketSize);
-
-            // Write client program version
-            TDSUtilities.WriteUInt(destination, ClientProgramVersion);
-
-            // Write client program identifier
-            TDSUtilities.WriteUInt(destination, ClientPID);
-
-            // Write connection identifier
-            TDSUtilities.WriteUInt(destination, ConnectionID);
-
-            // Write the first optional flags
-            destination.WriteByte(OptionalFlags1.ToByte());
-
-            // Write the second optional flags
-            destination.WriteByte(OptionalFlags2.ToByte());
-
-            // Instantiate type flags
-            destination.WriteByte(TypeFlags.ToByte());
-
-            // Write the third optional flags
-            destination.WriteByte(OptionalFlags3.ToByte());
-
-            // Write client time zone
-            TDSUtilities.WriteInt(destination, ClientTimeZone);
-
-            // Write client locale identifier
-            TDSUtilities.WriteUInt(destination, ClientLCID);
-
-            // Prepare a collection of property values that will be set later
-            IList<TDSLogin7TokenOffsetProperty> variableProperties = new List<TDSLogin7TokenOffsetProperty>();
-
-            // Write client host name
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("HostName"), FixedPacketLength, (ushort)(string.IsNullOrEmpty(HostName) ? 0 : HostName.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Write user name and password
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("UserID"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(UserID) ? 0 : UserID.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Password"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(Password) ? 0 : Password.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Write application name
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ApplicationName"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(ApplicationName) ? 0 : ApplicationName.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Write server name
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ServerName"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Check if we have a feature extension block
-            if (FeatureExt != null)
-            {
-                // Write the offset of the feature extension offset (pointer to pointer)
-                variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("FeatureExt"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), sizeof(uint) / 2, true));  // Should be 4 bytes, devided by 2 because the next step multiplies by 2
-                TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-                TDSUtilities.WriteUShort(destination, (ushort)(variableProperties.Last().Length * 2));  // Compensate for division by 2 above
-            }
-            else
-            {
-                // Skip unused
-                TDSUtilities.WriteUShort(destination, 0);
-                TDSUtilities.WriteUShort(destination, 0);
-            }
-
-            // Write client library name
-            // We do not need to account for skipped unused bytes here because they're already accounted in fixedPacketLength
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("LibraryName"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(LibraryName) ? 0 : LibraryName.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Write language
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Language"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(Language) ? 0 : Language.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Write database
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Database"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(Database) ? 0 : Database.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Check if client is defined
-            if (ClientID == null)
-            {
-                // Allocate empty identifier
-                ClientID = new byte[6];
-            }
-
-            // Write unique client identifier
-            destination.Write(ClientID, 0, 6);
-
-            // Write SSPI
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("SSPI"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(SSPI == null ? 0 : SSPI.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Write database file to be attached. NOTE, "variableProperties.Last().Length" without " * 2" because the preceeding buffer isn't string
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("AttachDatabaseFile"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length), (ushort)(string.IsNullOrEmpty(AttachDatabaseFile) ? 0 : AttachDatabaseFile.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Write password change
-            variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ChangePassword"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(ChangePassword) ? 0 : ChangePassword.Length)));
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position);
-            TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length);
-
-            // Skip long SSPI
-            TDSUtilities.WriteUInt(destination, 0);
-
-            // We will be changing collection as we go and serialize everything. As such we can't use foreach and iterator.
-            int iCurrentProperty = 0;
-
-            // Iterate through the collection
-            while (iCurrentProperty < variableProperties.Count)
-            {
-                // Get current property by index
-                TDSLogin7TokenOffsetProperty property = variableProperties[iCurrentProperty];
-
-                // Check if length is positive
-                if (property.Length == 0)
-                {
-                    // Move to the next property
-                    iCurrentProperty++;
-                    continue;
-                }
-
-                // Check special properties
-                if (property.Property.Name == "Password" || property.Property.Name == "ChangePassword")
-                {
-                    // Write encrypted string value
-                    TDSUtilities.WritePasswordString(destination, (string)property.Property.GetValue(this, null));
-                }
-                else if (property.Property.Name == "FeatureExt")
-                {
-                    // Check if we are to serialize the offset or the actual data
-                    if (property.IsOffsetOffset)
-                    {
-                        // Property will be written at the offset immediately following all variable length data
-                        property.Position = variableProperties.Last().Position + variableProperties.Last().Length;
-
-                        // Write the position at which we'll be serializing the feature extension block
-                        TDSUtilities.WriteUInt(destination, property.Position);
-
-                        // Order strings in ascending order by offset
-                        variableProperties = variableProperties.OrderBy(p => p.Position).ToList();
-
-                        // Compensate increment to the next position in order to stay on the same
-                        iCurrentProperty--;
-
-                        // No longer offset, actual data is going to follow
-                        property.IsOffsetOffset = false;
-                    }
-                    else
-                    {
-                        // Transfer deflated feature extension into the login stream
-                        featureExtension.WriteTo(destination);
-                    }
-                }
-                else if (property.Property.Name == "SSPI")
-                {
-                    // Write SSPI
-                    destination.Write(SSPI, 0, SSPI.Length);
-                }
-                else
-                {
-                    // Write the string value
-                    TDSUtilities.WriteString(destination, (string)property.Property.GetValue(this, null));
-                }
-
-                // Move to the next property
-                iCurrentProperty++;
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOffsetProperty.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOffsetProperty.cs
deleted file mode 100644 (file)
index 29eef1c..0000000
+++ /dev/null
@@ -1,53 +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.Reflection;
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Helper class that takes care of setting property value
-    /// </summary>
-    public class TDSLogin7TokenOffsetProperty
-    {
-        /// <summary>
-        /// Property which value is being set
-        /// </summary>
-        public PropertyInfo Property { get; set; }
-
-        /// <summary>
-        /// Position of the value in the data stream
-        /// </summary>
-        public uint Position { get; set; }
-
-        /// <summary>
-        /// Length of the property value in the data stream
-        /// </summary>
-        public uint Length { get; set; }
-
-        /// <summary>
-        /// This property is used to distinguish between "value" position in the stream and "offset of the value" position
-        /// </summary>
-        public bool IsOffsetOffset { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7TokenOffsetProperty(PropertyInfo property, ushort position, ushort length)
-        {
-            Property = property;
-            Position = position;
-            Length = length;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7TokenOffsetProperty(PropertyInfo property, ushort position, ushort length, bool isOffsetOffset) :
-            this(property, position, length)
-        {
-            IsOffsetOffset = isOffsetOffset;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags1.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags1.cs
deleted file mode 100644 (file)
index 8ae594a..0000000
+++ /dev/null
@@ -1,147 +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.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Flags that indicate fByteOrder bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags1Order : byte
-    {
-        OrderX86 = 0,
-        Order68000 = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fChar bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags1Char : byte
-    {
-        Ascii = 0,
-        Ebddic = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fFloat bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags1Float : byte
-    {
-        IEEE754 = 0,
-        VAX = 1,
-        ND5000 = 2
-    }
-
-    /// <summary>
-    /// Flags that indicate fDumpLoad bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags1DumpLoad : byte
-    {
-        On = 0,
-        Off = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fUseDB bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags1UseDB : byte
-    {
-        On = 0,
-        Off = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fDatabase bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags1Database : byte
-    {
-        Warning = 0,
-        Fatal = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fSetLang bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags1Language : byte
-    {
-        Off = 0,
-        On = 1
-    }
-
-    /// <summary>
-    /// Structure of the optional flags 1
-    /// </summary>
-    public class TDSLogin7TokenOptionalFlags1
-    {
-        /// <summary>
-        /// Order
-        /// </summary>
-        public TDSLogin7OptionalFlags1Order Order { get; set; }
-
-        /// <summary>
-        /// Character set
-        /// </summary>
-        public TDSLogin7OptionalFlags1Char CharacterSet { get; set; }
-
-        /// <summary>
-        /// Floating point standard
-        /// </summary>
-        public TDSLogin7OptionalFlags1Float FloatingPoint { get; set; }
-
-        /// <summary>
-        /// Dump load
-        /// </summary>
-        public TDSLogin7OptionalFlags1DumpLoad DumpLoad { get; set; }
-
-        /// <summary>
-        /// Use database notifications
-        /// </summary>
-        public TDSLogin7OptionalFlags1UseDB UseDB { get; set; }
-
-        /// <summary>
-        /// Database
-        /// </summary>
-        public TDSLogin7OptionalFlags1Database Database { get; set; }
-
-        /// <summary>
-        /// Language
-        /// </summary>
-        public TDSLogin7OptionalFlags1Language Language { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags1()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags1(byte flags)
-        {
-            // Parse bytes as per TDS specification, section 2.2.6.3 LOGIN 7
-            Order = (TDSLogin7OptionalFlags1Order)(flags & 0x1);
-            CharacterSet = (TDSLogin7OptionalFlags1Char)((flags >> 1) & 0x1);
-            FloatingPoint = (TDSLogin7OptionalFlags1Float)((flags >> 2) & 0x3);
-            DumpLoad = (TDSLogin7OptionalFlags1DumpLoad)((flags >> 4) & 0x1);
-            UseDB = (TDSLogin7OptionalFlags1UseDB)((flags >> 5) & 0x1);
-            Database = (TDSLogin7OptionalFlags1Database)((flags >> 6) & 0x1);
-            Language = (TDSLogin7OptionalFlags1Language)((flags >> 7) & 0x1);
-        }
-
-        /// <summary>
-        /// Assemble bits into a byte
-        /// </summary>
-        public byte ToByte()
-        {
-            return (byte)((byte)Order
-                | ((byte)CharacterSet) << 1
-                | ((byte)FloatingPoint) << 2
-                | ((byte)DumpLoad) << 4
-                | ((byte)UseDB) << 5
-                | ((byte)Database) << 6
-                | ((byte)Language) << 7);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags2.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags2.cs
deleted file mode 100644 (file)
index f15fa8a..0000000
+++ /dev/null
@@ -1,101 +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.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Flags that indicate fLanguage bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags2Language : byte
-    {
-        Warning = 0,
-        Fatal = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fODBC bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags2Odbc : byte
-    {
-        Off = 0,
-        On = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fUserType bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags2UserType : byte
-    {
-        Normal = 0,
-        Server = 1,
-        Remote = 2,
-        Replication = 3
-    }
-
-    /// <summary>
-    /// Flags that indicate fIntSecurity bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags2IntSecurity : byte
-    {
-        Off = 0,
-        On = 1
-    }
-
-    /// <summary>
-    /// Structure of the optional flags 1
-    /// </summary>
-    public class TDSLogin7TokenOptionalFlags2
-    {
-        /// <summary>
-        /// Set if the change to initial language must succeed if the connect is to succeed
-        /// </summary>
-        public TDSLogin7OptionalFlags2Language Language { get; set; }
-
-        /// <summary>
-        /// Set if the client is the ODBC driver.
-        /// </summary>
-        public TDSLogin7OptionalFlags2Odbc Odbc { get; set; }
-
-        /// <summary>
-        /// The type of user connecting to the server
-        /// </summary>
-        public TDSLogin7OptionalFlags2UserType UserType { get; set; }
-
-        /// <summary>
-        /// The type of security required by the client
-        /// </summary>
-        public TDSLogin7OptionalFlags2IntSecurity IntegratedSecurity { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags2()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags2(byte flags)
-        {
-            // Parse bytes as per TDS specification, section 2.2.6.3 LOGIN 7
-            Language = (TDSLogin7OptionalFlags2Language)(flags & 0x1);
-            Odbc = (TDSLogin7OptionalFlags2Odbc)((flags >> 1) & 0x1);
-            // Skipping deprecated fTranBoundary and fCacheConnect
-            UserType = (TDSLogin7OptionalFlags2UserType)((flags >> 4) & 0x7);
-            IntegratedSecurity = (TDSLogin7OptionalFlags2IntSecurity)((flags >> 7) & 0x1);
-        }
-
-        /// <summary>
-        /// Assemble bits into a byte
-        /// </summary>
-        public byte ToByte()
-        {
-            return (byte)((byte)Language
-                | ((byte)Odbc) << 1
-                | ((byte)UserType) << 4
-                | ((byte)IntegratedSecurity) << 7);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags3.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenOptionalFlags3.cs
deleted file mode 100644 (file)
index 7c5010a..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Flags that indicate fChangePassword bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags3ChangePassword : byte
-    {
-        No = 0,
-        Yes = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fUnknownCollationHandling bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7OptionalFlags3Collation : byte
-    {
-        Must = 0,
-        May = 1
-    }
-
-    /// <summary>
-    /// Structure of the optional flags 1
-    /// </summary>
-    public class TDSLogin7TokenOptionalFlags3
-    {
-        /// <summary>
-        /// Password change request
-        /// </summary>
-        public TDSLogin7OptionalFlags3ChangePassword ChangePassword { get; set; }
-
-        /// <summary>
-        /// Client is requesting separate process to be spawned as user instance
-        /// </summary>
-        public bool IsUserInstance { get; set; }
-
-        /// <summary>
-        /// Send Yukon binary XML.
-        /// </summary>
-        public bool SendYukonBinaryXML { get; set; }
-
-        /// <summary>
-        /// Unknown collection handling
-        /// </summary>
-        public TDSLogin7OptionalFlags3Collation UnknownCollation { get; set; }
-
-        /// <summary>
-        /// Feature extension flag.
-        /// </summary>
-        public bool ExtensionFlag { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags3()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7TokenOptionalFlags3(byte flags)
-        {
-            // Parse bytes as per TDS specification, section 2.2.6.3 LOGIN 7
-            ChangePassword = (TDSLogin7OptionalFlags3ChangePassword)(flags & 0x1);
-            IsUserInstance = ((flags >> 1) & 0x1) != 0;
-            SendYukonBinaryXML = ((flags >> 2) & 0x1) != 0;
-            UnknownCollation = (TDSLogin7OptionalFlags3Collation)((flags >> 3) & 0x1);
-            ExtensionFlag = ((flags >> 4) & 0x1) != 0;
-        }
-
-        /// <summary>
-        /// Assemble bits into a byte
-        /// </summary>
-        public byte ToByte()
-        {
-            return (byte)((byte)ChangePassword
-                | ((byte)(IsUserInstance ? 1 : 0)) << 1
-                | ((byte)(SendYukonBinaryXML ? 1 : 0)) << 2
-                | ((byte)UnknownCollation) << 3
-                | ((byte)(ExtensionFlag ? 1 : 0)) << 4);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenTypeFlags.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Login7/TDSLogin7TokenTypeFlags.cs
deleted file mode 100644 (file)
index eb1921f..0000000
+++ /dev/null
@@ -1,83 +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.SqlServer.TDS.Login7
-{
-    /// <summary>
-    /// Flags that indicate fSQLType bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7TypeFlagsSQL : byte
-    {
-        Default = 0,
-        SQL = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fOLEDB bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7TypeFlagsOleDb : byte
-    {
-        Off = 0,
-        On = 1
-    }
-
-    /// <summary>
-    /// Flags that indicate fReadOnlyIntent bit of LOGIN 7 options
-    /// </summary>
-    public enum TDSLogin7TypeFlagsReadOnlyIntent : byte
-    {
-        ReadWrite = 0,
-        ReadOnly = 1
-    }
-
-
-    /// <summary>
-    /// Structure of the flags 3
-    /// </summary>
-    public class TDSLogin7TokenTypeFlags
-    {
-        /// <summary>
-        /// The type of SQL the client sends to the server
-        /// </summary>
-        public TDSLogin7TypeFlagsSQL SQL { get; set; }
-
-        /// <summary>
-        /// Set if the client is the OLEDB driver
-        /// </summary>
-        public TDSLogin7TypeFlagsOleDb OleDb { get; set; }
-
-        /// <summary>
-        /// Application intent
-        /// </summary>
-        public TDSLogin7TypeFlagsReadOnlyIntent ReadOnlyIntent { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLogin7TokenTypeFlags()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLogin7TokenTypeFlags(byte flags)
-        {
-            // Parse bytes as per TDS specification, section 2.2.6.3 LOGIN 7
-            SQL = (TDSLogin7TypeFlagsSQL)(flags & 0xF);
-            OleDb = (TDSLogin7TypeFlagsOleDb)((flags >> 4) & 0x1);
-            ReadOnlyIntent = (TDSLogin7TypeFlagsReadOnlyIntent)((flags >> 5) & 0x1);
-        }
-
-        /// <summary>
-        /// Assemble bits into a byte
-        /// </summary>
-        public byte ToByte()
-        {
-            return (byte)((((byte)SQL) & 0xF)
-                | (((byte)OleDb) & 0x1) << 4
-                | (((byte)ReadOnlyIntent) & 0x1) << 5);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LoginAck/TDSLoginAckToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/LoginAck/TDSLoginAckToken.cs
deleted file mode 100644 (file)
index eb5a407..0000000
+++ /dev/null
@@ -1,167 +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.Text;
-
-using Microsoft.SqlServer.TDS.Login7;
-
-namespace Microsoft.SqlServer.TDS.LoginAck
-{
-    /// <summary>
-    /// Login acknowledgement packet
-    /// </summary>
-    public class TDSLoginAckToken : TDSPacketToken
-    {
-        /// <summary>
-        /// TDS Version used by the server
-        /// </summary>
-        public Version TDSVersion { get; set; }
-
-        /// <summary>
-        /// The type of interface with which the server will accept client requests
-        /// </summary>
-        public TDSLogin7TypeFlagsSQL Interface { get; set; }
-
-        /// <summary>
-        /// Name of the server (e.g. "Microsoft SQL Server")
-        /// </summary>
-        public string ServerName { get; set; }
-
-        /// <summary>
-        /// Server version
-        /// </summary>
-        public Version ServerVersion { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSLoginAckToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLoginAckToken(Version serverVersion)
-        {
-            ServerVersion = serverVersion;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLoginAckToken(Version serverVersion, Version tdsVersion) :
-            this(serverVersion)
-        {
-            TDSVersion = tdsVersion;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLoginAckToken(Version serverVersion, Version tdsVersion, TDSLogin7TypeFlagsSQL interfaceFlags) :
-            this(serverVersion, tdsVersion)
-        {
-            Interface = interfaceFlags;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSLoginAckToken(Version serverVersion, Version tdsVersion, TDSLogin7TypeFlagsSQL interfaceFlags, string serverName) :
-            this(serverVersion, tdsVersion, interfaceFlags)
-        {
-            ServerName = serverName;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-
-            // Read token length
-            ushort tokenLength = (ushort)(source.ReadByte() + (source.ReadByte() << 8));
-
-            // Read interface
-            Interface = (TDSLogin7TypeFlagsSQL)source.ReadByte();
-
-            // Read TDS version
-            string tdsVersion = string.Format("{0:X}", (uint)(source.ReadByte() << 24)
-                + (uint)(source.ReadByte() << 16)
-                + (uint)(source.ReadByte() << 8)
-                + (uint)(source.ReadByte()));
-
-            // Consturct TDS version
-            TDSVersion = new Version(int.Parse(tdsVersion.Substring(0, 1)), int.Parse(tdsVersion.Substring(1, 1)), Convert.ToInt32(tdsVersion.Substring(2, 2), 16), Convert.ToInt32(tdsVersion.Substring(4, 4), 16));
-
-            // Read server name length
-            byte serverNameLength = (byte)source.ReadByte();
-
-            // Allocate buffer for server name
-            byte[] serverNameBytes = new byte[serverNameLength * 2];
-
-            // Read data into the buffer
-            source.Read(serverNameBytes, 0, serverNameBytes.Length);
-
-            // Convert to string
-            ServerName = Encoding.Unicode.GetString(serverNameBytes);
-
-            // Read server version
-            ServerVersion = new Version(source.ReadByte(), source.ReadByte(), (source.ReadByte() << 8) + source.ReadByte());
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.LoginAcknowledgement);
-
-            // Calculate the length of the token
-            // The total length, in bytes, of the following fields: Interface, TDSVersion, Progname, and ProgVersion.
-            ushort tokenLength = (ushort)(sizeof(byte) + sizeof(uint) + sizeof(byte) + (string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length * 2) + sizeof(uint));
-
-            // Write the length
-            destination.WriteByte((byte)(tokenLength & 0xff));
-            destination.WriteByte((byte)((tokenLength >> 8) & 0xff));
-
-            // Write interface
-            destination.WriteByte((byte)Interface);
-
-            // Compile TDS version
-            uint tdsVersion = Convert.ToUInt32(string.Format("{0:X}", Math.Max(TDSVersion.Major, 0)) + string.Format("{0:X}", Math.Max(TDSVersion.Minor, 0)) + string.Format("{0:X2}", Math.Max(TDSVersion.Build, 0)) + string.Format("{0:X4}", Math.Max(TDSVersion.Revision, 0)), 16);
-
-            // Write TDS version
-            destination.WriteByte((byte)((tdsVersion >> 24) & 0xff));
-            destination.WriteByte((byte)((tdsVersion >> 16) & 0xff));
-            destination.WriteByte((byte)((tdsVersion >> 8) & 0xff));
-            destination.WriteByte((byte)(tdsVersion & 0xff));
-
-            // Write length of the server name
-            destination.WriteByte((byte)(string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length));
-
-            // Convert server name into byte stream
-            byte[] serverNameBytes = Encoding.Unicode.GetBytes(ServerName);
-
-            // Write server name
-            destination.Write(serverNameBytes, 0, serverNameBytes.Length);
-
-            // Write server version
-            destination.WriteByte((byte)(ServerVersion.Major & 0xff));
-            destination.WriteByte((byte)(ServerVersion.Minor & 0xff));
-            destination.WriteByte((byte)((ServerVersion.Build >> 8) & 0xff));
-            destination.WriteByte((byte)(ServerVersion.Build & 0xff));
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Order/TDSOrderToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Order/TDSOrderToken.cs
deleted file mode 100644 (file)
index 806a83a..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.Order
-{
-    /// <summary>
-    /// Completion packet "ORDER" token
-    /// </summary>
-    public class TDSOrderToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Column number
-        /// </summary>
-        public ushort Number { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSOrderToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSOrderToken(ushort value)
-        {
-            // Apply properties
-            Number = value;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read the stream length
-            ushort length = TDSUtilities.ReadUShort(source);
-
-            // Check if there's enough space for a short
-            if (length < sizeof(ushort))
-            {
-                return false;
-            }
-
-            // Read return value
-            Number = TDSUtilities.ReadUShort(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.Order);
-
-            // Write the length
-            TDSUtilities.WriteUShort(destination, sizeof(ushort));
-
-            // Write value
-            TDSUtilities.WriteUShort(destination, Number);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginAuthenticationType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginAuthenticationType.cs
deleted file mode 100644 (file)
index 7b6550f..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS.PreLogin
-{
-    /// <summary>
-    /// FedAuthRequired option in the prelogin packet.
-    /// </summary>
-    public enum TdsPreLoginFedAuthRequiredOption : byte
-    {
-        FedAuthNotRequired = 0x00,
-        FedAuthRequired = 0x01,
-        Illegal = 0x02
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginToken.cs
deleted file mode 100644 (file)
index 4c612e4..0000000
+++ /dev/null
@@ -1,400 +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.IO;
-using System.Linq;
-
-namespace Microsoft.SqlServer.TDS.PreLogin
-{
-    /// <summary>
-    /// Pre-login packet
-    /// </summary>
-    public class TDSPreLoginToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Version of the sender
-        /// Version: 4 bytes unsigned
-        /// Build: 2 bytes unsigned
-        /// </summary>
-        public Version Version { get; set; }
-
-        /// <summary>
-        /// Sub-build number of the sender.
-        /// </summary>
-        public ushort SubBuild { get; set; }
-
-        /// <summary>
-        /// Type of encryption
-        /// 1 byte
-        /// </summary>
-        public TDSPreLoginTokenEncryptionType Encryption { get; set; }
-
-        /// <summary>
-        /// Thread identifier of the sender
-        /// 4 bytes unsigned
-        /// </summary>
-        public uint ThreadID { get; set; }
-
-        /// <summary>
-        /// Indicates whether MARS is enabled on connection
-        /// 1 byte
-        /// </summary>
-        public bool IsMARS { get; set; }
-
-        /// <summary>
-        /// Client Application trace ID
-        /// </summary>
-        public byte[] ClientTraceID { get; set; }
-
-        /// <summary>
-        /// Client application activity ID, used for debugging purposes.
-        /// </summary>
-        public byte[] ActivityID { get; set; }
-
-        /// <summary>
-        /// Nonce to be encrypted using session key from federated authentication key
-        /// from federated handshake.
-        /// </summary>
-        public byte[] Nonce { get; set; }
-
-        /// <summary>
-        /// Federated Authentication required for the pre-login.
-        /// </summary>
-        public TdsPreLoginFedAuthRequiredOption FedAuthRequired { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSPreLoginToken()
-        {
-            // Initialize thread identifier
-            ThreadID = 0;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPreLoginToken(Version version)
-        {
-            // Save the version
-            Version = version;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPreLoginToken(Version version, TDSPreLoginTokenEncryptionType encryption) :
-            this(version)
-        {
-            // Save encryption setting
-            Encryption = encryption;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPreLoginToken(Version version, TDSPreLoginTokenEncryptionType encryption, bool isMARS) :
-            this(version, encryption)
-        {
-            // Save MARS
-            IsMARS = isMARS;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPreLoginToken(Version version, TDSPreLoginTokenEncryptionType encryption, bool isMARS, uint threadID) :
-            this(version, encryption, isMARS)
-        {
-            // Save thread ID
-            ThreadID = threadID;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPreLoginToken(Version version, TDSPreLoginTokenEncryptionType encryption, bool isMARS, uint threadID, TdsPreLoginFedAuthRequiredOption fedAuthRequired) :
-            this(version, encryption, isMARS, threadID)
-        {
-            FedAuthRequired = fedAuthRequired;
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSPreLoginToken(Stream source)
-        {
-            // Inflate token
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Prepare a list of options
-            IList<TDSPreLoginTokenOption> options = new List<TDSPreLoginTokenOption>();
-
-            // Inflate all options until terminator is detected
-            do
-            {
-                // Create a new option
-                options.Add(new TDSPreLoginTokenOption());
-
-                // Inflate it
-                if (!options[options.Count - 1].Inflate(source))
-                {
-                    return false;
-                }
-            }
-            while (options[options.Count - 1].Type != TDSPreLoginTokenOptionType.Terminator);
-
-            // Order the options in ascending order by offset
-            // For the most cases this should not change the order of the options in the stream, but just in case
-            options = options.OrderBy(o => o.Position).ToList();
-
-            // Calculate current inflation offset
-            ushort inflationOffset = (ushort)options.Sum(o => o.TokenLength);
-
-            // Iterate through each option and inflate it
-            foreach (TDSPreLoginTokenOption option in options)
-            {
-                // Ensure that current offset points to the option
-                while (inflationOffset < option.Position)
-                {
-                    // Read the stream
-                    source.ReadByte();
-
-                    // Advance position
-                    inflationOffset++;
-                }
-
-                // Check the type of the pre-login packet option type
-                switch (option.Type)
-                {
-                    case TDSPreLoginTokenOptionType.Version:
-                        {
-                            // Check if version fits
-                            if (option.Length >= 6)
-                            {
-                                // Read the data of the specified length at the specified position
-                                Version = new Version(
-                                    source.ReadByte() & 0xff, // Major
-                                    source.ReadByte(), // Minor
-                                    (source.ReadByte() << 8) + source.ReadByte());  // Build (swap bytes)
-
-                                // Read sub-build
-                                SubBuild = TDSUtilities.ReadUShort(source);
-
-                                // Update the offset
-                                inflationOffset += 6;
-                            }
-
-                            break;
-                        }
-                    case TDSPreLoginTokenOptionType.Encryption:
-                        {
-                            // Check is option fits
-                            if (option.Length >= 1)
-                            {
-                                // Read encryption
-                                Encryption = (TDSPreLoginTokenEncryptionType)source.ReadByte();
-
-                                // Update the offset
-                                inflationOffset += 1;
-                            }
-
-                            break;
-                        }
-                    case TDSPreLoginTokenOptionType.Instance:
-                        {
-                            // Currently does nothing.
-                            break;
-                        }
-                    case TDSPreLoginTokenOptionType.ThreadID:
-                        {
-                            // Check if thread ID fits
-                            if (option.Length >= 4)
-                            {
-                                // Read the data of the specified length at the specified position (big-endian)
-                                ThreadID = TDSUtilities.ReadUInt(source);
-
-                                // Update the offset
-                                inflationOffset += 4;
-                            }
-
-                            break;
-                        }
-                    case TDSPreLoginTokenOptionType.Mars:
-                        {
-                            // Check is option fits
-                            if (option.Length >= 1)
-                            {
-                                // Read byte
-                                IsMARS = (source.ReadByte() == 0x01);
-
-                                // Update the offset
-                                inflationOffset += 1;
-                            }
-
-                            break;
-                        }
-                    case TDSPreLoginTokenOptionType.TraceID:
-                        {
-                            if (option.Length >= 36)
-                            {
-                                // Allocate memory
-                                ClientTraceID = new byte[16];
-
-                                // Read connection Trace ID
-                                source.Read(ClientTraceID, 0, 16);
-
-                                // Allocate memory
-                                ActivityID = new byte[20];
-
-                                // Read Activity ID.
-                                source.Read(ActivityID, 0, 20);
-
-                                // Update the offset
-                                inflationOffset += 36;
-                            }
-                            break;
-                        }
-                    case TDSPreLoginTokenOptionType.FederatedAuthenticationRequired:
-                        {
-                            if (option.Length >= 1)
-                            {
-                                // Read authentication type.
-                                FedAuthRequired = (TdsPreLoginFedAuthRequiredOption)source.ReadByte();
-
-                                // Update the offset
-                                inflationOffset += 1;
-                            }
-                            break;
-                        }
-                    case TDSPreLoginTokenOptionType.NonceOption:
-                        {
-                            if (option.Length >= 32)
-                            {
-                                //Allocate memory
-                                Nonce = new byte[32];
-
-                                // Read Nonce.
-                                source.Read(Nonce, 0, 32);
-
-                                // Update the offset
-                                inflationOffset += 32;
-                            }
-                            break;
-                        }
-                }
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            IList<TDSPreLoginTokenOption> options = new List<TDSPreLoginTokenOption>();
-
-            // Prepare the sequence of options to serialize
-            options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.Version, 6));
-            options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.ThreadID, 4));
-            options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.Mars, 1));
-
-            //Check if the option is needed.
-            if (ActivityID != null && ClientTraceID != null)
-            {
-                options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.TraceID, 36));
-            }
-
-            // Add Federated authentication
-            if (FedAuthRequired == TdsPreLoginFedAuthRequiredOption.FedAuthRequired || FedAuthRequired == TdsPreLoginFedAuthRequiredOption.Illegal)
-            {
-                options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.FederatedAuthenticationRequired, 1));
-            }
-
-            // Check if the option is needed to be added.
-            if (Nonce != null)
-            {
-                options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.NonceOption, (ushort)Nonce.Length));
-            }
-
-            options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.Encryption, 1));
-            options.Add(new TDSPreLoginTokenOption(TDSPreLoginTokenOptionType.Terminator, 0));
-
-            // Calculate the total size of the token metadata
-            ushort dataOffset = (ushort)options.Sum(t => t.TokenLength);
-
-            // Update all the offsets
-            foreach (TDSPreLoginTokenOption option in options)
-            {
-                // Update token offset
-                option.Position = dataOffset;
-
-                // Update data offset
-                dataOffset += option.Length;
-            }
-
-            // Serialize all tokens first
-            foreach (TDSPreLoginTokenOption option in options)
-            {
-                // Deflate a token option
-                option.Deflate(destination);
-            }
-
-            // Write version
-            destination.WriteByte((byte)(Version.Major & 0xff));
-            destination.WriteByte((byte)(Version.Minor & 0xff));
-            destination.WriteByte((byte)((Version.Build >> 8) & 0xff));
-            destination.WriteByte((byte)(Version.Build & 0xff));
-
-            // Write sub-version
-            TDSUtilities.WriteUShort(destination, SubBuild);
-
-            // Write thread ID
-            TDSUtilities.WriteUInt(destination, ThreadID);
-
-            // Write MARS
-            destination.WriteByte((byte)(IsMARS ? 0x01 : 0x00));
-
-            // Write traceID
-            if (ClientTraceID != null)
-            {
-                destination.Write(ClientTraceID, 0, ClientTraceID.Length);
-            }
-
-            // Write ActivityID
-            if (ActivityID != null)
-            {
-                destination.Write(ActivityID, 0, ActivityID.Length);
-            }
-
-            // Write federated auth required part
-            if (FedAuthRequired == TdsPreLoginFedAuthRequiredOption.FedAuthRequired || FedAuthRequired == TdsPreLoginFedAuthRequiredOption.Illegal)
-            {
-                destination.WriteByte((byte)FedAuthRequired);
-            }
-
-            // Write Nonce.
-            if (Nonce != null)
-            {
-                destination.Write(Nonce, 0, Nonce.Length);
-            }
-
-            // Write Encryption
-            destination.WriteByte((byte)Encryption);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenEncryptionType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenEncryptionType.cs
deleted file mode 100644 (file)
index 5e98ef9..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.TDS.PreLogin
-{
-    /// <summary>
-    /// Type of encryption specified in the pre-login packet
-    /// </summary>
-    public enum TDSPreLoginTokenEncryptionType : byte
-    {
-        Off = 0x00,
-        On = 0x01,
-        NotSupported = 0x02,
-        Required = 0x03
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenOption.cs
deleted file mode 100644 (file)
index acbdb92..0000000
+++ /dev/null
@@ -1,101 +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;
-
-namespace Microsoft.SqlServer.TDS.PreLogin
-{
-    /// <summary>
-    /// Token of the pre-login packet
-    /// </summary>
-    public class TDSPreLoginTokenOption : IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// Token type
-        /// </summary>
-        public TDSPreLoginTokenOptionType Type { get; set; }
-
-        /// <summary>
-        /// The size of the token declaration
-        /// </summary>
-        public ushort TokenLength
-        {
-            get { return (ushort)(Type != TDSPreLoginTokenOptionType.Terminator ? (sizeof(byte) + sizeof(ushort) + sizeof(ushort)) : sizeof(byte)); }
-        }
-
-        /// <summary>
-        /// Position of the token in the data buffer
-        /// </summary>
-        public ushort Position { get; set; }
-
-        /// <summary>
-        /// Token data
-        /// </summary>
-        public ushort Length { get; set; }
-
-        /// <summary>
-        /// Default
-        /// </summary>
-        public TDSPreLoginTokenOption()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPreLoginTokenOption(TDSPreLoginTokenOptionType type)
-        {
-            Type = type;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPreLoginTokenOption(TDSPreLoginTokenOptionType type, ushort length)
-        {
-            Type = type;
-            Length = length;
-        }
-
-        /// <summary>
-        /// Inflate the option
-        /// </summary>
-        public bool Inflate(Stream source)
-        {
-            // Read pre-login packet token type
-            Type = (TDSPreLoginTokenOptionType)source.ReadByte();
-
-            // Check if terminator found
-            if (Type != TDSPreLoginTokenOptionType.Terminator)
-            {
-                // Read token position and length
-                Position = (ushort)((source.ReadByte() << 8) + source.ReadByte());
-                Length = (ushort)((source.ReadByte() << 8) + source.ReadByte());
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the option
-        /// </summary>
-        public void Deflate(Stream destination)
-        {
-            // Write type
-            destination.WriteByte((byte)Type);
-
-            // Check if terminator token
-            if (Type != TDSPreLoginTokenOptionType.Terminator)
-            {
-                // Write position
-                destination.WriteByte((byte)((Position >> 8) & 0xff));
-                destination.WriteByte((byte)(Position & 0xff));
-
-                // Write length
-                destination.WriteByte((byte)((Length >> 8) & 0xff));
-                destination.WriteByte((byte)(Length & 0xff));
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenOptionType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/PreLogin/TDSPreLoginTokenOptionType.cs
deleted file mode 100644 (file)
index 0b089b0..0000000
+++ /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 Microsoft.SqlServer.TDS.PreLogin
-{
-    /// <summary>
-    /// Types of the tokens in TDS prelogin packet
-    /// </summary>
-    public enum TDSPreLoginTokenOptionType : byte
-    {
-        Version = 0x00,
-        Encryption = 0x01,
-        Instance = 0x02,
-        ThreadID = 0x03,
-        Mars = 0x04,
-        TraceID = 0x05,
-        FederatedAuthenticationRequired = 0x06,
-        NonceOption = 0x07,
-        Terminator = 0xff
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ReturnStatus/TDSReturnStatusToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/ReturnStatus/TDSReturnStatusToken.cs
deleted file mode 100644 (file)
index d8104c3..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.ReturnStatus
-{
-    /// <summary>
-    /// Completion packet "RETURNSTATUS" token
-    /// </summary>
-    public class TDSReturnStatusToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Value of the status
-        /// </summary>
-        public int Value { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSReturnStatusToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSReturnStatusToken(int value)
-        {
-            // Apply properties
-            Value = value;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read return value
-            Value = TDSUtilities.ReadInt(source);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.ReturnStatus);
-
-            // Write value
-            TDSUtilities.WriteInt(destination, Value);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSNBCRowToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSNBCRowToken.cs
deleted file mode 100644 (file)
index 4969204..0000000
+++ /dev/null
@@ -1,110 +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.IO;
-using System.Text;
-
-using Microsoft.SqlServer.TDS.ColMetadata;
-
-namespace Microsoft.SqlServer.TDS.Row
-{
-    /// <summary>
-    /// Token that corresponds to the row of data with null-byte compression
-    /// </summary>
-    public class TDSNBCRowToken : TDSRowTokenBase
-    {
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSNBCRowToken(TDSColMetadataToken metadata) :
-            base(metadata)
-        {
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // NOTE: We skip the identifier because it was read by the factory
-
-            // Calculate the number of bytes necessary to contain all columns
-            int byteCount = (int)Math.Ceiling((double)Metadata.Columns.Count / 8); /* bits in a byte */
-
-            // Allocate a bit mask
-            byte[] bitMask = new byte[byteCount];
-
-            // Read the bit mask
-            if (source.Read(bitMask, 0, bitMask.Length) != bitMask.Length)
-            {
-                // We don't suppot continuation of inflation at this point
-                throw new Exception("Failed to inflate the bit mask of NBC row token");
-            }
-
-            // Process each column
-            for (int index = 0; index < Metadata.Columns.Count; index++)
-            {
-                // Check if column is null. Null columns have corresponding bits set
-                if (((bitMask[(int)(index / 8)] >> (index % 8)) & 0x01) != 0)
-                {
-                    // Data is null
-                    Data.Add(null);
-                }
-                else
-                {
-                    // Inflate and add data to the list
-                    Data.Add(InflateColumn(source, Metadata.Columns[index]));
-                }
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Serialize token identifier
-            destination.WriteByte((byte)TDSTokenType.NBCRow);
-
-            // Calculate the number of bytes necessary to contain all columns
-            int byteCount = (int)Math.Ceiling((double)Metadata.Columns.Count / 8); /* bits in a byte */
-
-            // Allocate a bit mask
-            byte[] bitMask = new byte[byteCount];
-
-            // Fist pass - figure out which column values are null
-            for (int index = 0; index < Data.Count; index++)
-            {
-                // Check if data is null
-                if (Data[index] == null)
-                {
-                    // Enable the corresponding bit
-                    bitMask[(int)(index / 8)] = (byte)(bitMask[(int)(index / 8)] | (0x01 << (index % 8)));
-                }
-            }
-
-            // Serialize the bit mask
-            destination.Write(bitMask, 0, bitMask.Length);
-
-            // Process each column
-            for (int index = 0; index < Data.Count; index++)
-            {
-                // Check if data isn't null
-                if (Data[index] != null)
-                {
-                    // Deflate each column
-                    DeflateColumn(destination, Metadata.Columns[index], Data[index]);
-                }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSRowToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSRowToken.cs
deleted file mode 100644 (file)
index ec1bf06..0000000
+++ /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.Collections.Generic;
-using System.IO;
-using System.Text;
-
-using Microsoft.SqlServer.TDS.ColMetadata;
-
-namespace Microsoft.SqlServer.TDS.Row
-{
-    /// <summary>
-    /// Token that corresponds to the row of data
-    /// </summary>
-    public class TDSRowToken : TDSRowTokenBase
-    {
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSRowToken(TDSColMetadataToken metadata) :
-            base(metadata)
-        {
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Process each column
-            foreach (TDSColumnData column in Metadata.Columns)
-            {
-                // Inflate and add data to the list
-                Data.Add(InflateColumn(source, column));
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Serialize token identifier
-            destination.WriteByte((byte)TDSTokenType.Row);
-
-            // Process each column
-            for (int index = 0; index < Metadata.Columns.Count; index++)
-            {
-                // Deflate each column
-                DeflateColumn(destination, Metadata.Columns[index], Data[index]);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSRowTokenBase.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/Row/TDSRowTokenBase.cs
deleted file mode 100644 (file)
index f4f94b7..0000000
+++ /dev/null
@@ -1,585 +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.IO;
-using System.Text;
-
-using Microsoft.SqlServer.TDS.ColMetadata;
-
-namespace Microsoft.SqlServer.TDS.Row
-{
-    /// <summary>
-    /// Base class for token that corresponds to the row of data
-    /// </summary>
-    public abstract class TDSRowTokenBase : TDSPacketToken
-    {
-        /// <summary>
-        /// Metadata associated with the row
-        /// </summary>
-        public TDSColMetadataToken Metadata { get; set; }
-
-        /// <summary>
-        /// Values
-        /// </summary>
-        public IList<object> Data { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSRowTokenBase(TDSColMetadataToken metadata)
-        {
-            // Store metadata to be able to serialize values properly
-            Metadata = metadata;
-
-            // Create data container
-            Data = new List<object>();
-        }
-
-        /// <summary>
-        /// Inflate a particular column from the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the column from</param>
-        /// <param name="column">Metadata about the column</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        protected virtual object InflateColumn(Stream source, TDSColumnData column)
-        {
-            // Dispatch further reading based on the type
-            switch (column.DataType)
-            {
-                case TDSDataType.Null:
-                    {
-                        // No data associated with it
-                        return null;
-                    }
-                case TDSDataType.Bit:
-                case TDSDataType.Int1:
-                    {
-                        // Bit, 1 byte data representation
-                        return (byte)source.ReadByte();
-                    }
-                case TDSDataType.Int2:
-                    {
-                        // SmallInt, 2 byte data representation
-                        return unchecked((short)TDSUtilities.ReadUShort(source));
-                    }
-                case TDSDataType.Int4:
-                    {
-                        // Int, 4 byte data representation
-                        return unchecked((int)TDSUtilities.ReadUInt(source));
-                    }
-                case TDSDataType.Float8:
-                    {
-                        // Float (8 byte data representation)
-                        return BitConverter.ToDouble(BitConverter.GetBytes(TDSUtilities.ReadULong(source)), 0);
-                    }
-                case TDSDataType.Int8:
-                    {
-                        // BigInt (8 byte data representation)
-                        return unchecked((long)TDSUtilities.ReadULong(source));
-                    }
-                case TDSDataType.BitN:
-                    {
-                        // Read length
-                        byte length = (byte)source.ReadByte();
-
-                        // Check if null
-                        if (length == 0)
-                        {
-                            // No data
-                            return null;
-                        }
-
-                        // Bit, 1 byte data representation
-                        return (byte)source.ReadByte();
-                    }
-                case TDSDataType.IntN:
-                    {
-                        // Read length
-                        byte length = (byte)source.ReadByte();
-
-                        // Check integer length
-                        switch (length)
-                        {
-                            case 0:
-                                {
-                                    // No data
-                                    return null;
-                                }
-                            case 1:
-                                {
-                                    // Bit data
-                                    return (byte)source.ReadByte();
-                                }
-                            case 2:
-                                {
-                                    // Short data
-                                    return unchecked((short)TDSUtilities.ReadUShort(source));
-                                }
-                            case 4:
-                                {
-                                    // Integer data
-                                    return unchecked((int)TDSUtilities.ReadUInt(source));
-                                }
-                            case 8:
-                                {
-                                    // Integer data
-                                    return unchecked((long)TDSUtilities.ReadULong(source));
-                                }
-                            default:
-                                {
-                                    // We don't know how to inflate this integer
-                                    throw new InvalidDataException(string.Format("Unable to inflate integer of {0} bytes", length));
-                                }
-                        }
-                    }
-                case TDSDataType.NumericN:
-                    {
-                        // Read length
-                        byte length = (byte)source.ReadByte();
-
-                        // Check if null
-                        if (length == 0)
-                        {
-                            // No data
-                            return null;
-                        }
-
-                        // Allocate value container
-                        byte[] guidBytes = new byte[length];
-
-                        // Read value
-                        source.Read(guidBytes, 0, guidBytes.Length);
-
-                        // Instantiate type
-                        return guidBytes;
-                    }
-                case TDSDataType.Guid:
-                    {
-                        // Read the length
-                        byte length = (byte)source.ReadByte();
-
-                        // Check if we have any data
-                        if (length == 0x0000)
-                        {
-                            // No data
-                            return null;
-                        }
-
-                        // Allocate value container
-                        byte[] guidBytes = new byte[length];
-
-                        // Read value
-                        source.Read(guidBytes, 0, guidBytes.Length);
-
-                        // Convert to type
-                        return new Guid(guidBytes);
-                    }
-                case TDSDataType.BigVarChar:
-                case TDSDataType.BigChar:
-                    {
-                        // Read length
-                        ushort length = TDSUtilities.ReadUShort(source);
-
-                        // Check if we have any data
-                        if (length == 0xFFFF)
-                        {
-                            // No data
-                            return null;
-                        }
-
-                        // Allocate value container
-                        byte[] textBytes = new byte[length];
-
-                        // Read value
-                        source.Read(textBytes, 0, textBytes.Length);
-
-                        // Convert to type
-                        return Encoding.ASCII.GetString(textBytes);
-                    }
-                case TDSDataType.NVarChar:
-                    {
-                        // Check if MAX type
-                        if ((column.DataTypeSpecific as TDSShilohVarCharColumnSpecific).Length == 0xFFFF)
-                        {
-                            // Read the length of partialy length-prefixed type
-                            ulong length = TDSUtilities.ReadULong(source);
-
-                            // Check the value
-                            if (length == 0xFFFFFFFFFFFFFFFF)
-                            {
-                                // There's no data
-                                return null;
-                            }
-                            else if (length == 0xFFFFFFFFFFFFFFFE)
-                            {
-                                throw new NotImplementedException("UNKNOWN_PLP_LEN is not implemented yet");
-                            }
-                            else
-                            {
-                                // Allocate a memory stream
-                                MemoryStream chunks = new MemoryStream();
-
-                                // Size of the last chunk
-                                uint chunkLength = 0;
-
-                                // Iterate until we read the whole data
-                                do
-                                {
-                                    // Read the length of the chunk
-                                    chunkLength = TDSUtilities.ReadUInt(source);
-
-                                    // Allocate chunk container
-                                    byte[] chunk = new byte[chunkLength];
-
-                                    // Read value
-                                    source.Read(chunk, 0, chunk.Length);
-
-                                    // Append into the stream
-                                    chunks.Write(chunk, 0, chunk.Length);
-                                }
-                                while (chunkLength > 0);
-
-                                // Convert to byte array
-                                byte[] byteString = chunks.ToArray();
-
-                                // Serialize the data into the string
-                                return Encoding.Unicode.GetString(byteString, 0, byteString.Length);
-                            }
-                        }
-                        else
-                        {
-                            // Read length
-                            ushort length = TDSUtilities.ReadUShort(source);
-
-                            // Check if we have any data
-                            if (length == 0xFFFF)
-                            {
-                                // No data
-                                return null;
-                            }
-
-                            // Read the whole string at once
-                            return TDSUtilities.ReadString(source, (ushort)length);
-                        }
-                    }
-                case TDSDataType.BigVarBinary:
-                    {
-                        byte[] bytes = null;
-
-                        // Check if MAX type
-                        if ((ushort)column.DataTypeSpecific == 0xFFFF)
-                        {
-                            // Read the length of partialy length-prefixed type
-                            ulong length = TDSUtilities.ReadULong(source);
-
-                            // Check the value
-                            if (length == 0xFFFFFFFFFFFFFFFF)
-                            {
-                                // There's no data
-                                return null;
-                            }
-                            else if (length == 0xFFFFFFFFFFFFFFFE)
-                            {
-                                throw new NotImplementedException("UNKNOWN_PLP_LEN is not implemented yet");
-                            }
-                            else
-                            {
-                                // Allocate a memory stream
-                                MemoryStream chunks = new MemoryStream();
-
-                                // Size of the last chunk
-                                uint chunkLength = 0;
-
-                                // Iterate until we read the whole data
-                                do
-                                {
-                                    // Read the length of the chunk
-                                    chunkLength = TDSUtilities.ReadUInt(source);
-
-                                    // Allocate chunk container
-                                    byte[] chunk = new byte[chunkLength];
-
-                                    // Read value
-                                    source.Read(chunk, 0, chunk.Length);
-
-                                    // Append into the stream
-                                    chunks.Write(chunk, 0, chunk.Length);
-                                }
-                                while (chunkLength > 0);
-
-                                // Serialize to byte array
-                                bytes = chunks.ToArray();
-                            }
-                        }
-                        else
-                        {
-                            // Read length
-                            ushort length = TDSUtilities.ReadUShort(source);
-
-                            // Check if we have any data
-                            if (length == 0xFFFF)
-                            {
-                                // No data
-                                return null;
-                            }
-
-                            // Allocate value container
-                            bytes = new byte[length];
-
-                            // Read value
-                            source.Read(bytes, 0, bytes.Length);
-                        }
-
-                        // Convert to type
-                        return bytes;
-                    }
-                case TDSDataType.BigBinary:
-                    {
-                        // Read length
-                        ushort length = TDSUtilities.ReadUShort(source);
-
-                        // Check if we have any data
-                        if (length == 0xFFFF)
-                        {
-                            // No data
-                            return null;
-                        }
-
-                        // Allocate value container
-                        byte[] bytes = new byte[length];
-
-                        // Read value
-                        source.Read(bytes, 0, bytes.Length);
-
-                        // Convert to type
-                        return bytes;
-                    }
-                default:
-                    {
-                        // We don't know this type
-                        throw new NotImplementedException(string.Format("Unrecognized data type {0} for inflation", column.DataType));
-                    }
-            }
-        }
-
-        /// <summary>
-        /// Deflate the column into the stream
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        /// <param name="column">Column metadata</param>
-        /// <param name="data">Column value</param>
-        protected virtual void DeflateColumn(Stream destination, TDSColumnData column, object data)
-        {
-            // Dispatch further reading based on the type
-            switch (column.DataType)
-            {
-                case TDSDataType.Null:
-                    {
-                        // No data associated with it
-                        break;
-                    }
-                case TDSDataType.Bit:
-                    {
-                        destination.WriteByte((byte)((bool)data ? 1 : 0));
-                        break;
-                    }
-                case TDSDataType.Int1:
-                    {
-                        // Bit, 1 byte data representation
-                        destination.WriteByte((byte)data);
-                        break;
-                    }
-                case TDSDataType.Int2:
-                    {
-                        // SmallInt, 2 byte data representation
-                        TDSUtilities.WriteUShort(destination, unchecked((ushort)((short)data)));
-                        break;
-                    }
-                case TDSDataType.Int4:
-                    {
-                        // Int, 4 byte data representation
-                        TDSUtilities.WriteUInt(destination, unchecked((uint)((int)data)));
-                        break;
-                    }
-                case TDSDataType.Float8:
-                    {
-                        // Float (8 byte data representation)
-                        byte[] floatBytes = BitConverter.GetBytes((double)data);
-                        destination.Write(floatBytes, 0, floatBytes.Length);
-                        break;
-                    }
-                case TDSDataType.Int8:
-                    {
-                        // BigInt (8 byte data representation)
-                        TDSUtilities.WriteULong(destination, unchecked((ulong)((long)data)));
-                        break;
-                    }
-                case TDSDataType.BitN:
-                    {
-                        // Check if data is available
-                        if (data == null)
-                        {
-                            // No data
-                            destination.WriteByte(0);
-                        }
-                        else
-                        {
-                            // One byte data
-                            destination.WriteByte(1);
-
-                            // Data
-                            destination.WriteByte((byte)((bool)data ? 1 : 0));
-                        }
-
-                        break;
-                    }
-                case TDSDataType.IntN:
-                    {
-                        // Check if data is available
-                        if (data == null)
-                        {
-                            // No data
-                            destination.WriteByte(0);
-                        }
-                        else if (data is byte)
-                        {
-                            // One-byte data
-                            destination.WriteByte(1);
-
-                            // Bit data
-                            destination.WriteByte((byte)data);
-                        }
-                        else if (data is short)
-                        {
-                            // One-byte data
-                            destination.WriteByte(2);
-
-                            // Short data
-                            TDSUtilities.WriteUShort(destination, unchecked((ushort)(short)data));
-                        }
-                        else if (data is int)
-                        {
-                            // One-byte data
-                            destination.WriteByte(4);
-
-                            // Integer data
-                            TDSUtilities.WriteUInt(destination, unchecked((uint)(int)data));
-                        }
-                        else if (data is long)
-                        {
-                            // One-byte data
-                            destination.WriteByte(8);
-
-                            // Long data
-                            TDSUtilities.WriteULong(destination, unchecked((ulong)(long)data));
-                        }
-                        else
-                        {
-                            // We don't know how to deflate this integer
-                            throw new InvalidDataException(string.Format("Unable to deflate integer of type {0}", data.GetType().FullName));
-                        }
-
-                        break;
-                    }
-                case TDSDataType.Guid:
-                    {
-                        // Check if data is available
-                        if (data == null)
-                        {
-                            // No data
-                            destination.WriteByte(0);
-                        }
-                        else
-                        {
-                            // Get bytes
-                            byte[] guidBytes = ((Guid)data).ToByteArray();
-
-                            // One byte data length
-                            destination.WriteByte((byte)guidBytes.Length);
-
-                            // Data
-                            destination.Write(guidBytes, 0, guidBytes.Length);
-                        }
-
-                        break;
-                    }
-                case TDSDataType.BigChar:
-                case TDSDataType.BigVarChar:
-                    {
-                        // Check if data is available
-                        if (data == null)
-                        {
-                            // No data
-                            TDSUtilities.WriteUShort(destination, 0xFFFF);
-                        }
-                        else
-                        {
-                            // Get bytes
-                            byte[] textBytes = Encoding.ASCII.GetBytes((string)data);
-
-                            // One data length
-                            TDSUtilities.WriteUShort(destination, (ushort)textBytes.Length);
-
-                            // Data
-                            destination.Write(textBytes, 0, textBytes.Length);
-                        }
-
-                        break;
-                    }
-                case TDSDataType.NVarChar:
-                    {
-                        // Check if data is available
-                        if (data == null)
-                        {
-                            // No data
-                            TDSUtilities.WriteUShort(destination, 0xFFFF);
-                        }
-                        else
-                        {
-                            // Get bytes
-                            byte[] textBytes = Encoding.Unicode.GetBytes((string)data);
-
-                            // One data length
-                            TDSUtilities.WriteUShort(destination, (ushort)textBytes.Length);
-
-                            // Data
-                            destination.Write(textBytes, 0, textBytes.Length);
-                        }
-
-                        break;
-                    }
-                case TDSDataType.BigVarBinary:
-                case TDSDataType.BigBinary:
-                    {
-                        // Check if data is available
-                        if (data == null)
-                        {
-                            // No data
-                            TDSUtilities.WriteUShort(destination, 0xFFFF);
-                        }
-                        else
-                        {
-                            // Get bytes
-                            byte[] bytes = (byte[])data;
-
-                            // One data length
-                            TDSUtilities.WriteUShort(destination, (ushort)bytes.Length);
-
-                            // Data
-                            destination.Write(bytes, 0, bytes.Length);
-                        }
-
-                        break;
-                    }
-                default:
-                    {
-                        // We don't know this type
-                        throw new NotImplementedException(string.Format("Unrecognized data type {0} for deflation", column.DataType));
-                    }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SQLBatch/TDSSQLBatchToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SQLBatch/TDSSQLBatchToken.cs
deleted file mode 100644 (file)
index f5f665e..0000000
+++ /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.IO;
-using System.Text;
-
-using Microsoft.SqlServer.TDS.AllHeaders;
-
-namespace Microsoft.SqlServer.TDS.SQLBatch
-{
-    /// <summary>
-    /// Login acknowledgement packet
-    /// </summary>
-    public class TDSSQLBatchToken : TDSPacketToken
-    {
-        /// <summary>
-        /// All headers definition
-        /// </summary>
-        public TDSAllHeadersToken AllHeaders { get; set; }
-
-        /// <summary>
-        /// Query text
-        /// </summary>
-        public string Text { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSQLBatchToken()
-        {
-        }
-
-        /// <summary>
-        /// Inflating constructor
-        /// </summary>
-        public TDSSQLBatchToken(Stream source)
-        {
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        public override bool Inflate(Stream source)
-        {
-            // Consturct all headers
-            AllHeaders = new TDSAllHeadersToken();
-
-            // Inflate all headers
-            if (!AllHeaders.Inflate(source))
-            {
-                // Failed to inflate headers
-                throw new ArgumentException("Failed to inflate all headers");
-            }
-
-            // Prepare memory stream
-            MemoryStream cache = new MemoryStream();
-
-            byte[] buffer = new byte[1024];
-            int lastRead = 0;
-
-            do
-            {
-                // Read the chunk of the stream into the memory stream
-                lastRead = source.Read(buffer, 0, 1024);
-
-                // Write into the memory stream
-                cache.Write(buffer, 0, lastRead);
-            }
-            while (lastRead >= buffer.Length);
-
-            // Read everything to the end of the stream
-            Text = Encoding.Unicode.GetString(cache.ToArray());
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Check if we have all headers
-            if (AllHeaders != null)
-            {
-                // Deflate all headers
-                AllHeaders.Deflate(destination);
-            }
-
-            // Convert text to stream
-            byte[] textBytes = Encoding.Unicode.GetBytes(Text);
-
-            // Write to the destination
-            destination.Write(textBytes, 0, textBytes.Length);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SSPI/TDSSSPIClientToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SSPI/TDSSSPIClientToken.cs
deleted file mode 100644 (file)
index 22175a5..0000000
+++ /dev/null
@@ -1,98 +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;
-
-namespace Microsoft.SqlServer.TDS.SSPI
-{
-    /// <summary>
-    /// Token that carries client's SSPI payload during login sequence
-    /// </summary>
-    public class TDSSSPIClientToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Data length
-        /// </summary>
-        private int _length;
-
-        /// <summary>
-        /// Current offset at which inflation occurs
-        /// </summary>
-        private int _inflationOffset;
-
-        /// <summary>
-        /// SSPI payload
-        /// </summary>
-        public byte[] Payload { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSSPIClientToken(Stream source, int length)
-        {
-            // Allocate buffer
-            Payload = new byte[length];
-
-            // Save the length to enable inflation
-            _length = length;
-
-            // Inflate
-            if (!Inflate(source))
-            {
-                // There was not enough data to inflate the token
-                throw new Exception(string.Format("Failed to inflate client SSPI token. Inflated {0} of {1} byte(s)", _inflationOffset, _length));
-            }
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSSSPIClientToken(byte[] payload)
-        {
-            // Save payload
-            Payload = payload;
-
-            // Not really used, but usefull anyway
-            _length = Payload.Length;
-
-            // Mark that the "inflation" is complete
-            _inflationOffset = _length;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Check if inflation is complete
-            if (_inflationOffset >= _length)
-            {
-                // We're done
-                return true;
-            }
-
-            // Read payload
-            int readSize = source.Read(Payload, _inflationOffset, Payload.Length - _inflationOffset);
-
-            // Update inflation offset with the new read size
-            _inflationOffset += readSize;
-
-            // Check if we're done
-            return (_inflationOffset >= _length);
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write the data
-            destination.Write(Payload, 0, Payload.Length);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SSPI/TDSSSPIToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SSPI/TDSSSPIToken.cs
deleted file mode 100644 (file)
index 5cc24fb..0000000
+++ /dev/null
@@ -1,73 +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;
-
-namespace Microsoft.SqlServer.TDS.SSPI
-{
-    /// <summary>
-    /// Token that carries SSPI payload during login sequence
-    /// </summary>
-    public class TDSSSPIToken : TDSPacketToken
-    {
-        /// <summary>
-        /// SSPI payload
-        /// </summary>
-        public byte[] Payload { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSSPIToken()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSSSPIToken(byte[] payload)
-        {
-            Payload = payload;
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public override bool Inflate(Stream source)
-        {
-            // Read the payload length
-            ushort length = TDSUtilities.ReadUShort(source);
-
-            // Allocate buffer
-            Payload = new byte[length];
-
-            // Read payload
-            source.Read(Payload, 0, Payload.Length);
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.SSPI);
-
-            // Write length
-            TDSUtilities.WriteUShort(destination, (ushort)((Payload != null) ? Payload.Length : 0));
-
-            // Check if data is available
-            if (Payload != null)
-            {
-                // Write the data
-                destination.Write(Payload, 0, Payload.Length);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionRecoveryData.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionRecoveryData.cs
deleted file mode 100644 (file)
index 18b03a9..0000000
+++ /dev/null
@@ -1,289 +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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Container for session recovery data
-    /// </summary>
-    public class TDSSessionRecoveryData : IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// Size of the data read during inflation operation. It is needed to properly parse the option stream.
-        /// </summary>
-        internal uint InflationSize { get; set; }
-
-        /// <summary>
-        /// Database into which the user is logged in
-        /// </summary>
-        public string Database { get; set; }
-
-        /// <summary>
-        /// Collation of the database
-        /// </summary>
-        public byte[] Collation { get; set; }
-
-        /// <summary>
-        /// Language of the session
-        /// </summary>
-        public string Language { get; set; }
-
-        /// <summary>
-        /// Options that carry session state
-        /// </summary>
-        public IList<TDSSessionStateOption> Options { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionRecoveryData()
-        {
-        }
-
-        /// <summary>
-        /// Inflation constructor
-        /// </summary>
-        public TDSSessionRecoveryData(Stream source)
-        {
-            Inflate(source);
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public virtual void Deflate(Stream destination)
-        {
-            // Allocate temporary memory stream
-            MemoryStream cache = new MemoryStream();
-
-            // Write database
-            cache.WriteByte((byte)(string.IsNullOrEmpty(Database) ? 0 : Database.Length));
-            TDSUtilities.WriteString(cache, Database);
-
-            // Write collation
-            if (Collation == null)
-            {
-                // We don't have a collation
-                cache.WriteByte(0);
-            }
-            else
-            {
-                // Write collation length
-                cache.WriteByte((byte)Collation.Length);
-
-                // Write it
-                cache.Write(Collation, 0, Collation.Length);
-            }
-
-            // Write language
-            cache.WriteByte((byte)(string.IsNullOrEmpty(Language) ? 0 : Language.Length));
-            TDSUtilities.WriteString(cache, Language);
-
-            // Check if we have options
-            if (Options != null)
-            {
-                // Iterate through all options and deflate them
-                foreach (TDSSessionStateOption option in Options)
-                {
-                    // Deflate into the cache to calcualte the overall length
-                    option.Deflate(cache);
-                }
-            }
-
-            // Write the length
-            TDSUtilities.WriteUInt(destination, (uint)cache.Length);
-
-            // Write the data itself
-            cache.WriteTo(destination);
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public virtual bool Inflate(Stream source)
-        {
-            // Create options collection
-            Options = new List<TDSSessionStateOption>();
-
-            // Current position in the stream
-            InflationSize = 0;
-
-            // Read the total length
-            uint totalLength = TDSUtilities.ReadUInt(source);
-
-            // Check if we still have space to read
-            if (InflationSize >= totalLength)
-            {
-                // Inflation is complete
-                return true;
-            }
-
-            // Read the length of the string
-            byte byteLength = (byte)source.ReadByte();
-
-            // Update offset
-            InflationSize += sizeof(byte);
-
-            // Check if we still have space to read
-            if (InflationSize >= totalLength)
-            {
-                // Inflation is complete
-                return true;
-            }
-
-            // Read the string
-            Database = TDSUtilities.ReadString(source, (ushort)(byteLength * 2));
-
-            // Update offset
-            InflationSize += ((uint)byteLength * 2);  // one character is 2 bytes long
-
-            // Check if we still have space to read
-            if (InflationSize >= totalLength)
-            {
-                // Inflation is complete
-                return true;
-            }
-
-            // Read the length of the collation
-            byteLength = (byte)source.ReadByte();
-
-            // Update offset
-            InflationSize += sizeof(byte);
-
-            // Check if we still have space to read
-            if (InflationSize >= totalLength)
-            {
-                // Inflation is complete
-                return true;
-            }
-
-            // Check if we have a collation
-            if (byteLength > 0)
-            {
-                // Allocate collation
-                Collation = new byte[5];
-
-                // Read collation
-                int readBytes = source.Read(Collation, 0, Collation.Length);
-
-                // Update offset
-                InflationSize += (uint)readBytes;
-
-                // Check if we still have space to read
-                if (InflationSize >= totalLength)
-                {
-                    // Inflation is complete
-                    return true;
-                }
-            }
-
-            // Read the length of the string
-            byteLength = (byte)source.ReadByte();
-
-            // Update offset
-            InflationSize += sizeof(byte);
-
-            // Check if we still have space to read
-            if (InflationSize >= totalLength)
-            {
-                // Inflation is complete
-                return true;
-            }
-
-            // Read the string
-            Language = TDSUtilities.ReadString(source, (ushort)(byteLength * 2));
-
-            // Update offset
-            InflationSize += ((uint)byteLength * 2);  // one character is 2 bytes long
-
-            // Read while we have data
-            while (totalLength > InflationSize)
-            {
-                // Read a byte that identifies the session state slot
-                byte stateID = (byte)source.ReadByte();
-
-                // Update current position
-                InflationSize += sizeof(byte);
-
-                // Option being inflated
-                TDSSessionStateOption option = null;
-
-                // Dispatch inflation based on the state
-                switch (stateID)
-                {
-                    // UserOptionAll
-                    case TDSSessionStateUserOptionsOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateUserOptionsOption();
-                            break;
-                        }
-                    // DateFirstDateFormat
-                    case TDSSessionStateDateFirstDateFormatOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateDateFirstDateFormatOption();
-                            break;
-                        }
-                    // DbDeadlockPri
-                    case TDSSessionStateDeadlockPriorityOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateDeadlockPriorityOption();
-                            break;
-                        }
-                    // LockTimeout
-                    case TDSSessionStateLockTimeoutOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateLockTimeoutOption();
-                            break;
-                        }
-                    // IsoFips
-                    case TDSSessionStateISOFipsOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateISOFipsOption();
-                            break;
-                        }
-                    // TextSize
-                    case TDSSessionStateTextSizeOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateTextSizeOption();
-                            break;
-                        }
-                    // ContextInfo
-                    case TDSSessionStateContextInfoOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateContextInfoOption();
-                            break;
-                        }
-                    default:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateGenericOption(stateID);
-                            break;
-                        }
-                }
-
-                // Inflate the option
-                option.Inflate(source);
-
-                // Register option with the collection
-                Options.Add(option);
-
-                // Update current length with the inflation size of the data
-                InflationSize += option.InflationSize;
-            }
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateContextInfoOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateContextInfoOption.cs
deleted file mode 100644 (file)
index 68dad20..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Session state for the context information
-    /// </summary>
-    public class TDSSessionStateContextInfoOption : TDSSessionStateOption
-    {
-        /// <summary>
-        /// Identifier of the session state option
-        /// </summary>
-        public const byte ID = 11;
-
-        /// <summary>
-        /// Context information
-        /// </summary>
-        public byte[] Value { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateContextInfoOption() :
-            base(ID) // State identifier
-        {
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // Store the value
-            DeflateValue(destination, Value);
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Read the value
-            Value = InflateValue(source);
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateDateFirstDateFormatOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateDateFirstDateFormatOption.cs
deleted file mode 100644 (file)
index 6d2d740..0000000
+++ /dev/null
@@ -1,158 +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;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Session state for the first date of the week
-    /// </summary>
-    public class TDSSessionStateDateFirstDateFormatOption : TDSSessionStateOption
-    {
-        /// <summary>
-        /// Identifier of the session state option
-        /// </summary>
-        public const byte ID = 2;
-
-        /// <summary>
-        /// First day of the week
-        /// </summary>
-        public byte DateFirst { get; set; }
-
-        /// <summary>
-        /// First day of the week
-        /// </summary>
-        public DateFormatType DateFormat { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateDateFirstDateFormatOption() :
-            base(ID) // State identifier
-        {
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // Allocate a container
-            byte[] value = new byte[2];
-
-            // Put the date first
-            value[0] = DateFirst;
-
-            // Put the date format
-            value[1] = _ToValue(DateFormat);
-
-            // Store the value
-            DeflateValue(destination, value);
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Read the value
-            byte[] value = InflateValue(source);
-
-            // Read the first byte
-            DateFirst = value[0];  // VSTS# 1023839 - OIPI documentation for session state #2 (datefirst) is incorrect
-
-            // Read the second byte
-            DateFormat = _ToEnum(value[1]);
-
-            // Inflation is complete
-            return true;
-        }
-
-        /// <summary>
-        /// Convert a wire representation to enum
-        /// </summary>
-        private DateFormatType _ToEnum(byte value)
-        {
-            switch (value)
-            {
-                case 1:
-                    {
-                        return DateFormatType.MonthDayYear;
-                    }
-                case 2:
-                    {
-                        return DateFormatType.DayMonthYear;
-                    }
-                case 3:
-                    {
-                        return DateFormatType.YearMonthDay;
-                    }
-                case 4:
-                    {
-                        return DateFormatType.YearDayMonth;
-                    }
-                case 5:
-                    {
-                        return DateFormatType.MonthYearDay;
-                    }
-                case 6:
-                    {
-                        return DateFormatType.DayYearMonth;
-                    }
-                default:
-                    {
-                        throw new Exception("Unrecognized date format value " + value.ToString());
-                    }
-            }
-        }
-
-        /// <summary>
-        /// Convert enum to wire format
-        /// </summary>
-        private byte _ToValue(DateFormatType value)
-        {
-            switch (value)
-            {
-                case DateFormatType.MonthDayYear:
-                    {
-                        return 1;
-                    }
-                case DateFormatType.DayMonthYear:
-                    {
-                        return 2;
-                    }
-                case DateFormatType.YearMonthDay:
-                    {
-                        return 3;
-                    }
-                case DateFormatType.YearDayMonth:
-                    {
-                        return 4;
-                    }
-                case DateFormatType.MonthYearDay:
-                    {
-                        return 5;
-                    }
-                case DateFormatType.DayYearMonth:
-                    {
-                        return 6;
-                    }
-                default:
-                    {
-                        throw new Exception("Unrecognized date format " + value.ToString());
-                    }
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateDeadlockPriorityOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateDeadlockPriorityOption.cs
deleted file mode 100644 (file)
index ab37a6f..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Session state for the deadlock priority
-    /// </summary>
-    public class TDSSessionStateDeadlockPriorityOption : TDSSessionStateOption
-    {
-        /// <summary>
-        /// Identifier of the session state option
-        /// </summary>
-        public const byte ID = 4;
-
-        /// <summary>
-        /// Deadlock priority value
-        /// </summary>
-        public sbyte Value { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateDeadlockPriorityOption() :
-            base(ID) // State identifier
-        {
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // Allocate a container
-            byte[] value = new byte[1];
-
-            // Put the date first
-            value[0] = (byte)Value;
-
-            // Store the value
-            DeflateValue(destination, value);
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Read the value
-            byte[] value = InflateValue(source);
-
-            // Read the first byte
-            Value = (sbyte)value[0];
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateGenericOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateGenericOption.cs
deleted file mode 100644 (file)
index 1e9cf93..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Generic session state option
-    /// </summary>
-    public class TDSSessionStateGenericOption : TDSSessionStateOption
-    {
-        /// <summary>
-        /// State option value
-        /// </summary>
-        public byte[] Value { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSSessionStateGenericOption(byte stateID) :
-            base(stateID)
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSSessionStateGenericOption(byte stateID, byte[] value) :
-            this(stateID)
-        {
-            Value = value;
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // Write value as is
-            DeflateValue(destination, Value);
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Inflate value
-            Value = InflateValue(source);
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateISOFipsOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateISOFipsOption.cs
deleted file mode 100644 (file)
index f46c45e..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Session state for the transaction isolation level and FIPS 127-2 compliance flags
-    /// </summary>
-    public class TDSSessionStateISOFipsOption : TDSSessionStateOption
-    {
-        /// <summary>
-        /// Identifier of the session state option
-        /// </summary>
-        public const byte ID = 7;
-
-        /// <summary>
-        /// Transaction isolation level
-        /// </summary>
-        public TransactionIsolationLevelType TransactionIsolationLevel { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateISOFipsOption() :
-            base(ID) // State identifier
-        {
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // Prepare container
-            byte[] value = new byte[1];
-
-            // Put transaction isolation level into it
-            value[0] = (byte)(((byte)TransactionIsolationLevel) & 0xf);
-
-            // Store the value
-            DeflateValue(destination, value);
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Read the value
-            byte[] value = InflateValue(source);
-
-            // Get transaction isolation level
-            TransactionIsolationLevel = (TransactionIsolationLevelType)((byte)(value[0] & 0xf));
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateLockTimeoutOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateLockTimeoutOption.cs
deleted file mode 100644 (file)
index 372d4d9..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Session state for the lock timeout
-    /// </summary>
-    public class TDSSessionStateLockTimeoutOption : TDSSessionStateOption
-    {
-        /// <summary>
-        /// Identifier of the session state option
-        /// </summary>
-        public const byte ID = 5;
-
-        /// <summary>
-        /// Lock timeout value
-        /// </summary>
-        public int Value { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateLockTimeoutOption() :
-            base(ID) // State identifier
-        {
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // Store the value
-            DeflateValue(destination, BitConverter.GetBytes(Value));
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Read the value
-            Value = BitConverter.ToInt32(InflateValue(source), 0);
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateOption.cs
deleted file mode 100644 (file)
index 00e78b2..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// A single option of the session state
-    /// </summary>
-    public abstract class TDSSessionStateOption : IDeflatable, IInflatable
-    {
-        /// <summary>
-        /// Property that tells the caller how much of the data from the stream was read by inflation logic
-        /// </summary>
-        internal uint InflationSize { get; set; }
-
-        /// <summary>
-        /// Identifier of the state option
-        /// </summary>
-        public byte StateID { get; protected set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSSessionStateOption(byte stateID)
-        {
-            StateID = stateID;
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public abstract void Deflate(Stream destination);
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public abstract bool Inflate(Stream source);
-
-        /// <summary>
-        /// Read the raw data but don't interpret it
-        /// </summary>
-        protected byte[] InflateValue(Stream source)
-        {
-            // Read the next byte to check if length is DWORD
-            int length = (int)source.ReadByte();
-
-            // Update inflation size
-            InflationSize += sizeof(byte);
-
-            // Check
-            if (length == 0xFF)
-            {
-                // Length is long
-                length = TDSUtilities.ReadInt(source);
-
-                // Update inflation size
-                InflationSize += sizeof(int);
-            }
-
-            // Allocate a container
-            byte[] value = new byte[length];
-
-            // Read all bytes
-            source.Read(value, 0, value.Length);
-
-            // Update inflation size
-            InflationSize += (uint)length;
-
-            return value;
-        }
-
-        /// <summary>
-        /// Write raw data
-        /// </summary>
-        protected void DeflateValue(Stream destination, byte[] value)
-        {
-            // Check length
-            if (value != null && value.Length >= 0xFF)
-            {
-                // Write the prefix to indicate a DWORD length
-                destination.WriteByte(0xFF);
-
-                // Length is DWORD
-                TDSUtilities.WriteUInt(destination, (uint)value.Length);
-            }
-            else
-            {
-                // Length is byte
-                destination.WriteByte((byte)value.Length);
-            }
-
-            // Serialize the data itself
-            if (value != null)
-            {
-                destination.Write(value, 0, value.Length);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateTextSizeOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateTextSizeOption.cs
deleted file mode 100644 (file)
index d2848bc..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Session state for the text size
-    /// </summary>
-    public class TDSSessionStateTextSizeOption : TDSSessionStateOption
-    {
-        /// <summary>
-        /// Identifier of the session state option
-        /// </summary>
-        public const byte ID = 9;
-
-        /// <summary>
-        /// Text size value
-        /// </summary>
-        public int Value { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateTextSizeOption() :
-            base(ID) // State identifier
-        {
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // Store the value
-            DeflateValue(destination, BitConverter.GetBytes(Value));
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Read the value
-            Value = BitConverter.ToInt32(InflateValue(source), 0);
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateToken.cs
deleted file mode 100644 (file)
index d79d5dd..0000000
+++ /dev/null
@@ -1,207 +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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Token that contains session state
-    /// </summary>
-    public class TDSSessionStateToken : TDSPacketToken
-    {
-        /// <summary>
-        /// Indicates that session is recoverable
-        /// </summary>
-        public bool IsRecoverable { get; set; }
-
-        /// <summary>
-        /// Sequential number of the state
-        /// </summary>
-        public int SequenceNumber { get; set; }
-
-        /// <summary>
-        /// State options
-        /// </summary>
-        public IList<TDSSessionStateOption> Options { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateToken()
-        {
-            Options = new List<TDSSessionStateOption>();
-        }
-
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        public override bool Inflate(Stream source)
-        {
-            // We skip the token identifier because it is read by token factory
-
-            // Current inflation offset
-            uint inflationOffset = 0;
-
-            // Read the length of the token
-            uint tokenLength = TDSUtilities.ReadUInt(source);
-
-            // NOTE: Length is excluded from the token length
-
-            // Check if we still have space left to read
-            if (inflationOffset >= tokenLength)
-            {
-                // We read the whole token
-                return true;
-            }
-
-            // Read sequence number
-            SequenceNumber = (int)TDSUtilities.ReadUInt(source);
-
-            // Update inflation offset
-            inflationOffset += sizeof(uint);
-
-            // Check if we still have space left to read
-            if (inflationOffset >= tokenLength)
-            {
-                // We read the whole token
-                return true;
-            }
-
-            // Read status
-            byte status = (byte)source.ReadByte();
-
-            // Update inflation offset
-            inflationOffset += sizeof(byte);
-
-            // Check if we still have space left to read
-            if (inflationOffset >= tokenLength)
-            {
-                // We read the whole token
-                return true;
-            }
-
-            // Parse status
-            IsRecoverable = ((status & 0x01) != 0);
-
-            // Read while we have data
-            while (tokenLength > inflationOffset)
-            {
-                // Read a byte that identifies the session state slot
-                byte stateID = (byte)source.ReadByte();
-
-                // Update current position
-                inflationOffset += sizeof(byte);
-
-                // Option being inflated
-                TDSSessionStateOption option = null;
-
-                // Dispatch inflation based on the state
-                switch (stateID)
-                {
-                    // UserOptionAll
-                    case TDSSessionStateUserOptionsOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateUserOptionsOption();
-                            break;
-                        }
-                    // DateFirstDateFormat
-                    case TDSSessionStateDateFirstDateFormatOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateDateFirstDateFormatOption();
-                            break;
-                        }
-                    // DbDeadlockPri
-                    case TDSSessionStateDeadlockPriorityOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateDeadlockPriorityOption();
-                            break;
-                        }
-                    // LockTimeout
-                    case TDSSessionStateLockTimeoutOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateLockTimeoutOption();
-                            break;
-                        }
-                    // IsoFips
-                    case TDSSessionStateISOFipsOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateISOFipsOption();
-                            break;
-                        }
-                    // TextSize
-                    case TDSSessionStateTextSizeOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateTextSizeOption();
-                            break;
-                        }
-                    // ContextInfo
-                    case TDSSessionStateContextInfoOption.ID:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateContextInfoOption();
-                            break;
-                        }
-                    default:
-                        {
-                            // Create a new option
-                            option = new TDSSessionStateGenericOption(stateID);
-                            break;
-                        }
-                }
-
-                // Inflate the option
-                option.Inflate(source);
-
-                // Register option with the collection
-                Options.Add(option);
-
-                // Update current length with the inflation size of the data
-                inflationOffset += option.InflationSize;
-            }
-
-            return true;
-        }
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public override void Deflate(Stream destination)
-        {
-            // Write token identifier
-            destination.WriteByte((byte)TDSTokenType.SessionState);
-
-            // Allocate a temporary memory stream
-            MemoryStream memoryStream = new MemoryStream();
-
-            // Iterate through all option
-            foreach (TDSSessionStateOption option in Options)
-            {
-                // Deflate into the memory stream to calcualte the overall length
-                option.Deflate(memoryStream);
-            }
-
-            // Write the length
-            TDSUtilities.WriteUInt(destination, (uint)(memoryStream.Length + sizeof(uint) /* Sequence Number */ + sizeof(byte) /* Status */ + memoryStream.Length));
-
-            // Write sequence number
-            TDSUtilities.WriteUInt(destination, (uint)SequenceNumber);
-
-            // Write status
-            destination.WriteByte((byte)(IsRecoverable ? 1 : 0));
-
-            // Write the options
-            memoryStream.WriteTo(destination);
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateUserOptionsOption.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/SessionState/TDSSessionStateUserOptionsOption.cs
deleted file mode 100644 (file)
index 9bd6c00..0000000
+++ /dev/null
@@ -1,354 +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;
-
-namespace Microsoft.SqlServer.TDS.SessionState
-{
-    /// <summary>
-    /// Session state of the user options
-    /// </summary>
-    public class TDSSessionStateUserOptionsOption : TDSSessionStateOption
-    {
-        #region Flags
-
-        /// <summary>
-        /// Bit that corresponds to ansi warnings flag
-        /// </summary>
-        private const int OPT_ANSI_WARNINGS = 0x10000000;
-
-        /// <summary>
-        /// Bit that corresponds to ansi nulls flag
-        /// </summary>
-        private const int OPT_ANSI_NULLS = 0x4000000;
-
-        /// <summary>
-        /// Bit that corresponds to cursor close on commit flag
-        /// </summary>
-        private const int OPT_CURSOR_COMMIT_CLOSE = 0x2000000;
-
-        /// <summary>
-        /// Bit that corresponds to quoted identifier flag
-        /// </summary>
-        private const int OPT_QUOTEDIDENT = 0x800000;
-
-        /// <summary>
-        /// Bit that corresponds to concatenation of nulls flag
-        /// </summary>
-        private const int OPT_CATNULL = 0x10000;
-
-        /// <summary>
-        /// Bit that corresponds to default position of ansi nulls flag
-        /// </summary>
-        private const int OPT_ANSINULLDFLTON = 0x4000;
-
-        /// <summary>
-        /// Bit that corresponds to ansi padding flag
-        /// </summary>
-        private const int OPT_ANSI_PADDING = 0x2000;
-
-        /// <summary>
-        /// Bit that corresponds to arithmetic abort flag
-        /// </summary>
-        private const int OPT_ARITHABORT = 0x1000;
-
-        /// <summary>
-        /// Bit that corresponds to abort truncation of numeric scale
-        /// </summary>
-        private const int OPT_NUMEABORT = 0x800;
-
-        /// <summary>
-        /// Bit that corresponds to transaction abort flag
-        /// </summary>
-        private const int OPT_XACTABORT = 0x10;
-
-        /// <summary>
-        /// Bit that corresponds to no count flag
-        /// </summary>
-        private const int OPT_NOCOUNT = 0x4;
-
-        /// <summary>
-        /// Bit that corresponds to arithmetic ignore flag
-        /// </summary>
-        private const int OPT_ARITHIGN = 0x2;
-
-        /// <summary>
-        /// Bit that corresponds to implicit transactions flag
-        /// </summary>
-        private const int OPT2_IMPLICIT_XACT = 0x02;
-
-        #endregion
-
-        /// <summary>
-        /// Identifier of the session state option
-        /// </summary>
-        public const byte ID = 0;
-
-        /// <summary>
-        /// Affects the nullability of new columns when the nullability of the column is not specified in the CREATE TABLE and ALTER TABLE statements.
-        /// </summary>
-        public bool AnsiNullDefaultOn { get; set; }
-
-        /// <summary>
-        /// Controls null behavior in T-SQL
-        /// </summary>
-        public bool AnsiNulls { get; set; }
-
-        /// <summary>
-        /// Impacts character column behavior (char, varchar, binary, and varbinary)
-        /// </summary>
-        public bool AnsiPadding { get; set; }
-
-        /// <summary>
-        /// Controls certain warning messages required for ansi compliance
-        /// </summary>
-        public bool AnsiWarnings { get; set; }
-
-        /// <summary>
-        /// Terminates a query when an overflow or divide-by-zero error occurs during query execution
-        /// </summary>
-        public bool ArithAbort { get; set; }
-
-        /// <summary>
-        /// Controls whether error messages are returned from overflow or divide-by-zero errors during a query
-        /// </summary>
-        public bool ArithIgnore { get; set; }
-
-        /// <summary>
-        /// Controls whether concatenation results are treated as null or empty string values
-        /// </summary>
-        public bool ConcatNullYieldsNull { get; set; }
-
-        /// <summary>
-        /// Controls whether the server will close cursors when you commit a transaction
-        /// </summary>
-        public bool CursorCloseOnCommit { get; set; }
-
-        /// <summary>
-        /// Sets implicit transaction mode for the connection
-        /// </summary>
-        public bool ImplicitTransactions { get; set; }
-
-        /// <summary>
-        /// Controls the emitting of Done w/count tokens from Transact-SQL.
-        /// </summary>
-        public bool NoCount { get; set; }
-
-        /// <summary>
-        /// Generates an error when a loss of precision occurs in an expression
-        /// </summary>
-        public bool NumericRoundAbort { get; set; }
-
-        /// <summary>
-        /// Causes SQL Server to follow the ISO rules regarding quotation mark delimiting identifiers and literal strings
-        /// </summary>
-        public bool QuotedIdentifier { get; set; }
-
-        /// <summary>
-        /// Specifies whether SQL Server automatically rolls back the current transaction when a Transact-SQL statement raises a run-time error
-        /// </summary>
-        public bool TransactionAbortOnError { get; set; }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSSessionStateUserOptionsOption() :
-            base(0) // State identifier
-        {
-        }
-
-        /// <summary>
-        /// Deflate state into the stream
-        /// </summary>
-        public override void Deflate(Stream destination)
-        {
-            // Write state ID
-            destination.WriteByte(StateID);
-
-            // First 4 bytes are flags
-            int userOptions = 0;
-
-            // Next 4 bytes are masks
-            int userOptionsMask = unchecked((int)0xffffffff);  // We only care about settings all bits
-
-            // Next byte are option user options
-            byte optionalUserOptions = 0;
-
-            // OPT_ANSI_WARNINGS
-            if (AnsiWarnings)
-            {
-                userOptions |= OPT_ANSI_WARNINGS;
-            }
-
-            // OPT_ANSI_NULLS
-            if (AnsiNulls)
-            {
-                userOptions |= OPT_ANSI_NULLS;
-            }
-
-            // OPT_CURSOR_COMMIT_CLOSE
-            if (CursorCloseOnCommit)
-            {
-                userOptions |= OPT_CURSOR_COMMIT_CLOSE;
-            }
-
-            // OPT_QUOTEDIDENT
-            if (QuotedIdentifier)
-            {
-                userOptions |= OPT_QUOTEDIDENT;
-            }
-
-            // OPT_CATNULL
-            if (ConcatNullYieldsNull)
-            {
-                userOptions |= OPT_CATNULL;
-            }
-
-            // OPT_ANSINULLDFLTON
-            if (AnsiNullDefaultOn)
-            {
-                userOptions |= OPT_ANSINULLDFLTON;
-            }
-            else
-            {
-                // Turn off the bit in the mask
-                userOptionsMask &= ~OPT_ANSINULLDFLTON;
-            }
-
-            // OPT_ANSI_PADDING
-            if (AnsiPadding)
-            {
-                userOptions |= OPT_ANSI_PADDING;
-            }
-
-            // OPT_ARITHABORT
-            if (ArithAbort)
-            {
-                userOptions |= OPT_ARITHABORT;
-            }
-
-            // OPT_NUMEABORT
-            if (NumericRoundAbort)
-            {
-                userOptions |= OPT_NUMEABORT;
-            }
-
-            // OPT_XACTABORT
-            if (TransactionAbortOnError)
-            {
-                userOptions |= OPT_XACTABORT;
-            }
-
-            // OPT_NOCOUNT
-            if (NoCount)
-            {
-                userOptions |= OPT_NOCOUNT;
-            }
-
-            // OPT_ARITHIGN
-            if (ArithIgnore)
-            {
-                userOptions |= OPT_ARITHIGN;
-            }
-
-            // OPT2_IMPLICIT_XACT
-            if (ImplicitTransactions)
-            {
-                optionalUserOptions |= OPT2_IMPLICIT_XACT;
-            }
-
-            // Allocate an array for all of this
-            MemoryStream cache = new MemoryStream();
-
-            // Put user options in it
-            byte[] subValue = BitConverter.GetBytes(userOptions);
-            cache.Write(subValue, 0, subValue.Length);
-
-            // Store mask in the cache
-            subValue = BitConverter.GetBytes(userOptionsMask);
-            cache.Write(subValue, 0, subValue.Length);
-
-            // Write additional byte
-            cache.WriteByte(optionalUserOptions);
-
-            // Store the value
-            DeflateValue(destination, cache.ToArray());
-        }
-
-        /// <summary>
-        /// Inflate from stream
-        /// </summary>
-        public override bool Inflate(Stream source)
-        {
-            // Reset inflation size
-            InflationSize = 0;
-
-            // NOTE: state ID is skipped because it is read by the construction factory
-
-            // Read the value
-            byte[] value = InflateValue(source);
-
-            // First 4 bytes are flags
-            int userOptions = BitConverter.ToInt32(value, 0);
-
-            // Next 4 bytes are masks
-            int userOptionsMask = BitConverter.ToInt32(value, 4);
-
-            // Next byte are option user options
-            int optionalUserOptions = (int)value[8];
-
-            // OPT_ANSI_WARNINGS
-            AnsiWarnings = (userOptions & OPT_ANSI_WARNINGS) != 0;
-
-            // OPT_ANSI_NULLS
-            AnsiNulls = (userOptions & OPT_ANSI_NULLS) != 0;
-
-            // OPT_CURSOR_COMMIT_CLOSE
-            CursorCloseOnCommit = (userOptions & OPT_CURSOR_COMMIT_CLOSE) != 0;
-
-            // OPT_QUOTEDIDENT
-            QuotedIdentifier = (userOptions & OPT_QUOTEDIDENT) != 0;
-
-            // OPT_CATNULL
-            ConcatNullYieldsNull = (userOptions & OPT_CATNULL) != 0;
-
-            // OPT_ANSINULLDFLTON - check the mask first
-            if ((userOptionsMask & OPT_ANSINULLDFLTON) != 0)
-            {
-                // Check the but
-                AnsiNullDefaultOn = (userOptions & OPT_ANSINULLDFLTON) != 0;
-            }
-            else
-            {
-                // Not set
-                AnsiNullDefaultOn = false;
-            }
-
-            // OPT_ANSI_PADDING
-            AnsiPadding = (userOptions & OPT_ANSI_PADDING) != 0;
-
-            // OPT_ARITHABORT
-            ArithAbort = (userOptions & OPT_ARITHABORT) != 0;
-
-            // OPT_NUMEABORT
-            NumericRoundAbort = (userOptions & OPT_NUMEABORT) != 0;
-
-            // OPT_XACTABORT
-            TransactionAbortOnError = (userOptions & OPT_XACTABORT) != 0;
-
-            // OPT_NOCOUNT
-            NoCount = (userOptions & OPT_NOCOUNT) != 0;
-
-            // OPT_ARITHIGN
-            ArithIgnore = (userOptions & OPT_ARITHIGN) != 0;
-
-            // OPT2_IMPLICIT_XACT
-            ImplicitTransactions = (optionalUserOptions & OPT2_IMPLICIT_XACT) != 0;
-
-            // Inflation is complete
-            return true;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDS.csproj b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDS.csproj
deleted file mode 100644 (file)
index 18ff7f3..0000000
+++ /dev/null
@@ -1,105 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-  <PropertyGroup>
-    <RootNamespace>Microsoft.SqlServer.TDS</RootNamespace>
-    <AssemblyName>Microsoft.SqlServer.TDS</AssemblyName>
-    <ClsCompliant>false</ClsCompliant>
-    <Configurations>netstandard2.0-Unix-Debug;netstandard2.0-Unix-Release;netstandard2.0-Windows_NT-Debug;netstandard2.0-Windows_NT-Release</Configurations>
-  </PropertyGroup>
-  <ItemGroup>
-    <Compile Include="AllHeaders\TDSQueryNotificationsHeader.cs" />
-    <Compile Include="AllHeaders\TDSTraceHeader.cs" />
-    <Compile Include="AllHeaders\TDSTransactionDescriptorHeader.cs" />
-    <Compile Include="AllHeaders\TDSHeaderType.cs" />
-    <Compile Include="AllHeaders\TDSAllHeaders.cs" />
-    <Compile Include="AutoTDSStream.cs" />
-    <Compile Include="ColInfo\TDSColInfoToken.cs" />
-    <Compile Include="ColInfo\TDSColumnProperty.cs" />
-    <Compile Include="ColInfo\TDSColumnStatus.cs" />
-    <Compile Include="ColMetadata\TDSColMetadataToken.cs" />
-    <Compile Include="ColMetadata\TDSColumnData.cs" />
-    <Compile Include="ColMetadata\TDSColumnDataCollation.cs" />
-    <Compile Include="ColMetadata\TDSColumnDataFlags.cs" />
-    <Compile Include="ColMetadata\TDSColumnDataUpdatableFlag.cs" />
-    <Compile Include="ColMetadata\TDSDecimalColumnSpecific.cs" />
-    <Compile Include="ColMetadata\TDSShilohVarCharColumnSpecific.cs" />
-    <Compile Include="DateFormatType.cs" />
-    <Compile Include="Done\TDSDoneInProcToken.cs" />
-    <Compile Include="Done\TDSDoneProcedureToken.cs" />
-    <Compile Include="Done\TDSDoneToken.cs" />
-    <Compile Include="Done\TDSDoneTokenCommandType.cs" />
-    <Compile Include="Done\TDSDoneTokenStatusType.cs" />
-    <Compile Include="EnvChange\TDSEnvChangeToken.cs" />
-    <Compile Include="EnvChange\TDSEnvChangeTokenType.cs" />
-    <Compile Include="EnvChange\TDSRoutingEnvChangeTokenValue.cs" />
-    <Compile Include="EnvChange\TDSRoutingEnvChangeTokenValueType.cs" />
-    <Compile Include="Error\TDSErrorToken.cs" />
-    <Compile Include="FeatureExtAck\TDSFeatureExtAckFederatedAuthenticationOption.cs" />
-    <Compile Include="FeatureExtAck\TDSFeatureExtAckGenericOption.cs" />
-    <Compile Include="FeatureExtAck\TDSFeatureExtAckOption.cs" />
-    <Compile Include="FeatureExtAck\TDSFeatureExtAckSessionStateOption.cs" />
-    <Compile Include="FeatureExtAck\TDSFeatureExtAckToken.cs" />
-    <Compile Include="FedAuthInfo\TDSFedAuthInfoId.cs" />
-    <Compile Include="FedAuthInfo\TDSFedAuthInfoOption.cs" />
-    <Compile Include="FedAuthInfo\TDSFedAuthInfoOptionSPN.cs" />
-    <Compile Include="FedAuthInfo\TDSFedAuthInfoOptionSTSURL.cs" />
-    <Compile Include="FedAuthInfo\TDSFedAuthInfoToken.cs" />
-    <Compile Include="FedAuthMessage\TDSFedAuthMessageToken.cs" />
-    <Compile Include="IDeflatable.cs" />
-    <Compile Include="IInflatable.cs" />
-    <Compile Include="Info\TDSInfoToken.cs" />
-    <Compile Include="LanguageString.cs" />
-    <Compile Include="LanguageType.cs" />
-    <Compile Include="Login7\TDSLogin7FeatureOptionsToken.cs" />
-    <Compile Include="Login7\TDSLogin7FeatureOptionToken.cs" />
-    <Compile Include="Login7\TDSLogin7FedAuthOptionToken.cs" />
-    <Compile Include="Login7\TDSLogin7GenericOptionToken.cs" />
-    <Compile Include="Login7\TDSLogin7SessionRecoveryOptionToken.cs" />
-    <Compile Include="Login7\TDSLogin7TokenOffsetProperty.cs" />
-    <Compile Include="Login7\TDSLogin7TokenOptionalFlags1.cs" />
-    <Compile Include="Login7\TDSLogin7TokenOptionalFlags2.cs" />
-    <Compile Include="Login7\TDSLogin7TokenOptionalFlags3.cs" />
-    <Compile Include="Login7\TDSLogin7Token.cs" />
-    <Compile Include="Login7\TDSLogin7TokenTypeFlags.cs" />
-    <Compile Include="LoginAck\TDSLoginAckToken.cs" />
-    <Compile Include="Order\TDSOrderToken.cs" />
-    <Compile Include="PreLogin\TDSPreLoginAuthenticationType.cs" />
-    <Compile Include="ReturnStatus\TDSReturnStatusToken.cs" />
-    <Compile Include="Row\TDSNBCRowToken.cs" />
-    <Compile Include="Row\TDSRowToken.cs" />
-    <Compile Include="Row\TDSRowTokenBase.cs" />
-    <Compile Include="SessionState\TDSSessionRecoveryData.cs" />
-    <Compile Include="SessionState\TDSSessionStateContextInfoOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateDateFirstDateFormatOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateDeadlockPriorityOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateGenericOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateISOFipsOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateLockTimeoutOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateTextSizeOption.cs" />
-    <Compile Include="SessionState\TDSSessionStateToken.cs" />
-    <Compile Include="SessionState\TDSSessionStateUserOptionsOption.cs" />
-    <Compile Include="SQLBatch\TDSSQLBatchToken.cs" />
-    <Compile Include="SSPI\TDSSSPIClientToken.cs" />
-    <Compile Include="SSPI\TDSSSPIToken.cs" />
-    <Compile Include="TDSClientState.cs" />
-    <Compile Include="TDSDataType.cs" />
-    <Compile Include="TDSEncryptionType.cs" />
-    <Compile Include="TDSFeatureID.cs" />
-    <Compile Include="TDSMessage.cs" />
-    <Compile Include="TDSMessageCollection.cs" />
-    <Compile Include="TDSPacketHeader.cs" />
-    <Compile Include="TDSPacketToken.cs" />
-    <Compile Include="TDSPacketStatus.cs" />
-    <Compile Include="TDSMessageType.cs" />
-    <Compile Include="PreLogin\TDSPreLoginTokenEncryptionType.cs" />
-    <Compile Include="PreLogin\TDSPreLoginToken.cs" />
-    <Compile Include="PreLogin\TDSPreLoginTokenOption.cs" />
-    <Compile Include="PreLogin\TDSPreLoginTokenOptionType.cs" />
-    <Compile Include="TDSTokenType.cs" />
-    <Compile Include="TDSStream.cs" />
-    <Compile Include="TDSTokenFactory.cs" />
-    <Compile Include="TDSUtilities.cs" />
-    <Compile Include="TDSVersion.cs" />
-    <Compile Include="TransactionIsolationLevelType.cs" />
-  </ItemGroup>
-</Project>
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSClientState.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSClientState.cs
deleted file mode 100644 (file)
index 2a2b4bd..0000000
+++ /dev/null
@@ -1,67 +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.SqlServer.TDS
-{
-    /// <summary>
-    /// State of the client TDS parser
-    /// </summary>
-    public enum TDSClientState
-    {
-        /// <summary>
-        /// Sent Initial PRELOGIN Packet State
-        /// </summary>
-        PreLoginSent,
-
-        /// <summary>
-        /// Sent TLS/SSL Negotiation Packet State
-        /// </summary>
-        SSLNegotiationSent,
-
-        /// <summary>
-        /// Sent LOGIN7 Record with Complete Authentication Token state
-        /// </summary>
-        CompleteLogin7Sent,
-
-        /// <summary>
-        /// Sent LOGIN7 Record with SPNEGO Packet State
-        /// </summary>
-        Login7SPNEGOSent,
-
-        /// <summary>
-        /// Sent LOGIN7 Record with Authentication information request.
-        /// </summary>
-        Login7FederatedAuthenticationInformationRequestSent,
-
-        /// <summary>
-        /// Logged In State
-        /// </summary>
-        LoggedIn,
-
-        /// <summary>
-        /// Sent Client Request State
-        /// </summary>
-        RequestSent,
-
-        /// <summary>
-        /// Sent Attention State
-        /// </summary>
-        AttentionSent,
-
-        /// <summary>
-        /// Indicates that a connection was re-routed to a different SQL Server and transport needs to be re-established
-        /// </summary>
-        ReConnect,
-
-        /// <summary>
-        /// Sent a final notification to the TDS Server
-        /// </summary>
-        LogoutSent,
-
-        /// <summary>
-        /// Final State
-        /// </summary>
-        Final
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSDataType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSDataType.cs
deleted file mode 100644 (file)
index a3a0859..0000000
+++ /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.SqlServer.TDS
-{
-    /// <summary>
-    /// Data types used by TDS server
-    /// </summary>
-    public enum TDSDataType : byte
-    {
-        Null = 0x1f,
-        Text = 0x23,
-        Guid = 0x24,
-        VarBinary = 0x25,
-        IntN = 0x26,
-        VarChar = 0x27,
-        Binary = 0x2d,
-        Image = 0x22,
-        DateN = 0x28,
-        TimeN = 0x29,
-        DateTime2N = 0x2a,
-        DateTimeOffsetN = 0x2b,
-        Char = 0x2f,
-        Int1 = 0x30,
-        Bit = 0x32,
-        Int2 = 0x34,
-        Decimal = 0x37,
-        Int4 = 0x38,
-        DateTime4 = 0x3a,
-        Float4 = 0x3b,
-        Money = 0x3c,
-        DateTime = 0x3d,
-        Float8 = 0x3e,
-        Numeric = 0x3f,
-        SSVariant = 0x62,
-        NText = 0x63,
-        BitN = 0x68,
-        DecimalN = 0x6a,
-        NumericN = 0x6c,
-        FloatN = 0x6d,
-        MoneyN = 0x6e,
-        DateTimeN = 0x6f,
-        Money4 = 0x7a,
-        Int8 = 0x7f,
-        BigVarBinary = 0xA5,
-        BigVarChar = 0xA7,
-        BigBinary = 0xAD,
-        BigChar = 0xAF,
-        NVarChar = 0xe7,
-        NChar = 0xef,
-        Udt = 0xF0,
-        Xml = 0xf1,
-        Table = 0xF3
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSEncryptionType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSEncryptionType.cs
deleted file mode 100644 (file)
index 348605b..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Types of encryption TDS clients and servers supports
-    /// </summary>
-    public enum TDSEncryptionType
-    {
-        /// <summary>
-        /// No transport encryption
-        /// </summary>
-        Off,
-
-        /// <summary>
-        /// Encryption of the login packet only
-        /// </summary>
-        LoginOnly,
-
-        /// <summary>
-        /// Encryption of the entire session
-        /// </summary>
-        Full
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSFeatureID.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSFeatureID.cs
deleted file mode 100644 (file)
index aaa4581..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// TDS feature identifier
-    /// </summary>
-    public enum TDSFeatureID : byte
-    {
-        /// <summary>
-        /// Session recovery (connection resiliency)
-        /// </summary>
-        SessionRecovery = 0x01,
-
-        /// <summary>
-        /// Federated authentication
-        /// </summary>
-        FederatedAuthentication = 0x02,
-
-        /// <summary>
-        /// End of the list
-        /// </summary>
-        Terminator = 0xFF
-    }
-}
\ No newline at end of file
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessage.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessage.cs
deleted file mode 100644 (file)
index 1fed26d..0000000
+++ /dev/null
@@ -1,336 +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.IO;
-using Microsoft.SqlServer.TDS.Login7;
-using Microsoft.SqlServer.TDS.PreLogin;
-using Microsoft.SqlServer.TDS.SQLBatch;
-using Microsoft.SqlServer.TDS.SSPI;
-using Microsoft.SqlServer.TDS.Authentication;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// A single message that consists of a collection of TDS packets and represents a semantically complete and indivisible unit of information
-    /// </summary>
-    public class TDSMessage : List<TDSPacketToken>
-    {
-        /// <summary>
-        /// Internal stream that contains the data
-        /// </summary>
-        private MemoryStream _dataStream;
-
-        /// <summary>
-        /// Type of the content being delivered
-        /// </summary>
-        public TDSMessageType MessageType { get; private set; }
-
-        /// <summary>
-        /// Collection of packet statuses
-        /// </summary>
-        public List<TDSPacketStatus> PacketStatuses { get; private set; }
-
-        /// <summary>
-        /// Check if we have seen Reset Connection request
-        /// </summary>
-        public bool IsResetConnectionRequestSet
-        {
-            get
-            {
-                return PacketStatuses.Count > 0 && (PacketStatuses[0] & TDSPacketStatus.ResetConnection) != 0;
-            }
-        }
-
-        /// <summary>
-        /// Check if we have seen Reset Connection Skip Transaction request
-        /// </summary>
-        public bool IsResetConnectionSkipTransactionRequestSet
-        {
-            get
-            {
-                return PacketStatuses.Count > 0 && (PacketStatuses[0] & TDSPacketStatus.ResetConnectionSkipTransaction) != 0;
-            }
-        }
-
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSMessage()
-        {
-            // Initialize PacketStatuses collection
-            PacketStatuses = new List<TDSPacketStatus>();
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSMessage(TDSMessageType type) :
-            this()
-        {
-            // Save type
-            MessageType = type;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSMessage(TDSMessageType type, params TDSPacketToken[] tokens) :
-            this(type)
-        {
-            AddRange(tokens);
-        }
-
-        /// <summary>
-        /// Inflate the message from protocol-aware stream on the server
-        /// </summary>
-        /// <param name="stream">Source to inflate the message</param>
-        public bool InflateClientRequest(TDSStream stream)
-        {
-            // Chck if data stream is fully inflated
-            if (!_InflateDataStream(stream))
-            {
-                return false;
-            }
-
-            // Inflate all tokens in the stream
-            _InflateClientTokens();
-
-            // If we reached this point it means that both data and tokens are inflated
-            return true;
-        }
-
-        /// <summary>
-        /// Inflate the message from protocol-aware stream on the client side
-        /// </summary>
-        /// <param name="clientState">State of the client parser</param>
-        /// <param name="stream">Source to inflate the message</param>
-        public bool InflateServerResponse(TDSClientState clientState, TDSStream stream)
-        {
-            // Chck if data stream is fully inflated
-            if (!_InflateDataStream(stream))
-            {
-                return false;
-            }
-
-            // Inflate all tokens in the stream
-            _InflateServerTokens(clientState);
-
-            // If we reached this point it means that both data and tokens are inflated
-            return true;
-        }
-
-        /// <summary>
-        /// Protocol-aware deflation routine
-        /// </summary>
-        /// <param name="stream">Destination to deflate the message</param>
-        public void Deflate(TDSStream stream)
-        {
-            // Start a message on the stream
-            stream.StartMessage(MessageType);
-
-            // Iterate through each token and deflate it
-            foreach (TDSPacketToken token in this)
-            {
-                // Deflate token into the data stream
-                token.Deflate(stream);
-            }
-
-            // Complete the message
-            stream.EndMessage();
-        }
-
-        /// <summary>
-        /// Inflates the stream of data in this message
-        /// </summary>
-        /// <returns></returns>
-        private bool _InflateDataStream(TDSStream stream)
-        {
-            // Indicates that end-of-message marker was reached
-            bool isEndOfMessageReached = false;
-
-            // Continue inflating packets as long as there's data in the stream or we've not reached the end of the message
-            while (!isEndOfMessageReached)
-            {
-                // Chunk of data still available in the current packet
-                int packetDataLeft = 0;
-
-                // Check if we have a packet header
-                if (stream.IncomingPacketHeader != null)
-                {
-                    // Calculate the chunk of remaining data
-                    packetDataLeft = stream.IncomingPacketHeader.Length - stream.IncomingPacketPosition;
-                }
-
-                // Check if we have data to work with
-                if (packetDataLeft == 0)
-                {
-                    // Position stream on the next packet header and read it
-                    if (!stream.ReadNextHeader())
-                    {
-                        // We couldn't inflate the next packet header
-                        break;
-                    }
-
-                    // Record packet status
-                    PacketStatuses.Add(stream.IncomingPacketHeader.Status);
-
-                    // Use the packet header to establish message type
-                    MessageType = stream.IncomingPacketHeader.Type;
-
-                    // Recalculate the chunk of remaining data
-                    packetDataLeft = stream.IncomingPacketHeader.Length - stream.IncomingPacketPosition;
-                }
-
-                // Allocate a buffer to read the data into the buffer
-                byte[] packetDataBuffer = new byte[packetDataLeft];
-
-                // Read the data into the buffer
-                int packetDataRead = stream.Read(packetDataBuffer, 0, packetDataLeft);
-
-                // Check if we have a data stream
-                if (_dataStream == null)
-                {
-                    // Allocate a new data stream
-                    _dataStream = new MemoryStream();
-                }
-
-                // Write the data into the message stream
-                _dataStream.Write(packetDataBuffer, 0, packetDataRead);
-
-                // Check if the whole packet was read
-                if (packetDataRead < packetDataLeft)
-                {
-                    // We don't have enough data to inflate the whole message
-                    break;
-                }
-
-                // Check if inflation succeded
-                isEndOfMessageReached = (stream.IncomingPacketHeader.Status & TDSPacketStatus.EndOfMessage) != 0;
-            }
-
-            // Tell caller whether we reached the end of message
-            return isEndOfMessageReached;
-        }
-
-        /// <summary>
-        /// Traverse the input stream and inflate tokens that server sends to the client
-        /// </summary>
-        private void _InflateServerTokens(TDSClientState clientState)
-        {
-            // Check if we have a data stream
-            if (_dataStream == null)
-            {
-                // Nothing to inflate
-                return;
-            }
-
-            // Position to the beginning on the stream
-            _dataStream.Seek(0, SeekOrigin.Begin);
-
-            // Check client state
-            switch (clientState)
-            {
-                case TDSClientState.PreLoginSent:
-                    {
-                        // Create a pre-login token
-                        Add(new TDSPreLoginToken(_dataStream));
-                        break;
-                    }
-                default:
-                    {
-                        // Check message type
-                        switch (MessageType)
-                        {
-                            case TDSMessageType.Response:
-                                {
-                                    // Server responses must be inflated using token factory
-                                    AddRange(TDSTokenFactory.Create(_dataStream));
-                                    break;
-                                }
-                            default:
-                                {
-                                    // We don't recognize this message type
-                                    throw new NotImplementedException(string.Format("Inflation for {0} TDS message is not implemented", MessageType));
-                                }
-                        }
-                        break;
-                    }
-            }
-
-            // Inflation is complete so we should release the stream
-            _dataStream.Dispose();
-
-            // Make sure we're not going to reuse it
-            _dataStream = null;
-        }
-
-        /// <summary>
-        /// Traverse the input stream and inflate tokens that client sends to the server
-        /// </summary>
-        private void _InflateClientTokens()
-        {
-            // Check if we have a data stream
-            if (_dataStream == null)
-            {
-                // Nothing to inflate
-                return;
-            }
-
-            // Position to the beginning on the stream
-            _dataStream.Seek(0, SeekOrigin.Begin);
-
-            // Check message type
-            switch (MessageType)
-            {
-                case TDSMessageType.PreLogin:
-                    {
-                        // Create a pre-login token
-                        Add(new TDSPreLoginToken(_dataStream));
-                        break;
-                    }
-                case TDSMessageType.TDS7Login:
-                    {
-                        // Create and inflate login token
-                        Add(new TDSLogin7Token(_dataStream));
-                        break;
-                    }
-                case TDSMessageType.SSPI:
-                    {
-                        // Create a client-originated SSPI token
-                        Add(new TDSSSPIClientToken(_dataStream, (int)_dataStream.Length));
-                        break;
-                    }
-                case TDSMessageType.SQLBatch:
-                    {
-                        // Create and inflate SQL batch token
-                        Add(new TDSSQLBatchToken(_dataStream));
-                        break;
-                    }
-                case TDSMessageType.Attention:
-                    {
-                        // Do nothing
-                        break;
-                    }
-                case TDSMessageType.FederatedAuthenticationToken:
-                    {
-                        Add(new TDSFedAuthToken(_dataStream));
-                        break;
-                    }
-                default:
-                    {
-                        // We don't recognize this message type
-                        throw new NotImplementedException(string.Format("Inflation for {0} TDS message is not implemented", MessageType));
-                    }
-            }
-
-            // Inflation is complete so we should release the stream
-            _dataStream.Dispose();
-
-            // Make sure we're not going to reuse it
-            _dataStream = null;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessageCollection.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessageCollection.cs
deleted file mode 100644 (file)
index d23294d..0000000
+++ /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.Collections.Generic;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Collection of TDS messages
-    /// </summary>
-    public class TDSMessageCollection : List<TDSMessage>
-    {
-        /// <summary>
-        /// Default constructor
-        /// </summary>
-        public TDSMessageCollection()
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSMessageCollection(params TDSMessage[] messages)
-        {
-            AddRange(messages);
-        }
-
-        /// <summary>
-        /// Protocol-aware deflation routine
-        /// </summary>
-        /// <param name="stream">Destination to deflate the message</param>
-        public void Deflate(TDSStream stream)
-        {
-            // Iterate through each message
-            foreach (TDSMessage current in this)
-            {
-                // Deflate the message
-                current.Deflate(stream);
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessageType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSMessageType.cs
deleted file mode 100644 (file)
index 4a18189..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Type of TDS packet
-    /// </summary>
-    public enum TDSMessageType : byte
-    {
-        SQLBatch = 1,
-        PreTDS7Login = 2,
-        RPC = 3,
-        Response = 4,
-        Attention = 6,
-        BulkLoad = 7,
-        FederatedAuthenticationToken = 8,
-        TransactionManager = 14,
-        TDS7Login = 16,
-        SSPI = 17,
-        PreLogin = 18,
-        FederatedAuthenticationInfo = 238
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketHeader.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketHeader.cs
deleted file mode 100644 (file)
index ee176d8..0000000
+++ /dev/null
@@ -1,200 +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;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// TDS packet header
-    /// </summary>
-    public class TDSPacketHeader : IInflatable
-    {
-        /// <summary>
-        /// Size of the packet header in bytes
-        /// </summary>
-        public const int Size = 8;
-
-        /// <summary>
-        /// Packet header data
-        /// </summary>
-        private byte[] _data;
-
-        /// <summary>
-        /// The last offset where inflation operation was interrupted
-        /// </summary>
-        private ushort _inflationOffset;
-
-        /// <summary>
-        /// Type of the packet
-        /// 1 byte unsigned
-        /// </summary>
-        public TDSMessageType Type
-        {
-            get
-            {
-                // Read a byte from the buffer
-                return (TDSMessageType)_data[0];
-            }
-            set
-            {
-                // Write into the buffer
-                _data[0] = (byte)value;
-            }
-        }
-
-        /// <summary>
-        /// Status of the packet
-        /// 1 byte unsigned
-        /// </summary>
-        public TDSPacketStatus Status
-        {
-            get
-            {
-                // Read a byte from the buffer
-                return (TDSPacketStatus)_data[1];
-            }
-            set
-            {
-                // Write into the buffer
-                _data[1] = (byte)value;
-            }
-        }
-
-        /// <summary>
-        /// Size of the packet including header
-        /// 2 byte unsigned short
-        /// </summary>
-        public ushort Length
-        {
-            get
-            {
-                // Read big endian length from the buffer
-                return (ushort)((ushort)(_data[2] << 8) + (ushort)_data[3]);
-            }
-            set
-            {
-                // Write big endian value into the buffer
-                _data[2] = (byte)(value >> 8);
-                _data[3] = unchecked((byte)value);
-            }
-        }
-
-        /// <summary>
-        /// Process ID that sent this packet
-        /// 2 byte big-endian
-        /// </summary>
-        public ushort SPID
-        {
-            get
-            {
-                // Read big endian length from the buffer
-                return (ushort)((ushort)(_data[4] << 8) + (ushort)_data[5]);
-            }
-            set
-            {
-                // Write big endian value into the buffer
-                _data[4] = (byte)(value >> 8);
-                _data[5] = (byte)value;
-            }
-        }
-
-        /// <summary>
-        /// Identifier of the packet
-        /// 1 byte unsigned char
-        /// Incremented by 1 modulo 256
-        /// </summary>
-        public byte PacketID
-        {
-            get
-            {
-                // Read a byte from the buffer
-                return _data[6];
-            }
-            set
-            {
-                // Write into the buffer
-                _data[6] = value;
-            }
-        }
-
-        /// <summary>
-        /// Window (not used)
-        /// 1 byte
-        /// Should always be set to 0x00
-        /// </summary>
-        public byte Window
-        {
-            get
-            {
-                // Read a byte from the buffer
-                return _data[7];
-            }
-            set
-            {
-                // Write into the buffer
-                _data[7] = value;
-            }
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        /// <param name="buffer">Buffer which contains or will contain a packet header</param>
-        public TDSPacketHeader(byte[] buffer)
-        {
-            // Allocate packet header data
-            _data = buffer;
-
-            // We have not started the inflation
-            _inflationOffset = 0;
-
-            // Default length of the packet
-            Length = Size;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPacketHeader(byte[] buffer, TDSMessageType type) :
-            this(buffer)
-        {
-            // Save type
-            Type = type;
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSPacketHeader(byte[] buffer, TDSMessageType type, TDSPacketStatus status) :
-            this(buffer, type)
-        {
-            // Save status
-            Status = status;
-        }
-
-        /// <summary>
-        /// Inflate TDS packet from the stream
-        /// </summary>
-        /// <param name="source">Source of data</param>
-        public bool Inflate(Stream source)
-        {
-            // Check if inflation is complete
-            if (_inflationOffset < Size)
-            {
-                // Calculate remaining bytes
-                int packetHeaderLeft = Size - _inflationOffset;
-
-                // Read the rest of the packet header
-                int packetHeaderRead = source.Read(_data, _inflationOffset, packetHeaderLeft);
-
-                // Update offset
-                _inflationOffset += (ushort)packetHeaderRead;
-            }
-
-            // Tell caller if inflation is complete
-            return _inflationOffset >= Size;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketStatus.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketStatus.cs
deleted file mode 100644 (file)
index ef84603..0000000
+++ /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;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Bitmask of the packet status
-    /// </summary>
-    [Flags]
-    public enum TDSPacketStatus
-    {
-        Normal = 0x0,
-        EndOfMessage = 0x1,
-        IgnoreEvent = 0x2,
-        ResetConnection = 0x08,
-        ResetConnectionSkipTransaction = 0x10
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketToken.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSPacketToken.cs
deleted file mode 100644 (file)
index 96a0335..0000000
+++ /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.IO;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Container for the packet data
-    /// </summary>
-    public abstract class TDSPacketToken : IInflatable, IDeflatable
-    {
-        /// <summary>
-        /// Inflate the token
-        /// </summary>
-        /// <param name="source">Stream to inflate the token from</param>
-        /// <returns>TRUE if inflation is complete</returns>
-        public abstract bool Inflate(Stream source);
-
-        /// <summary>
-        /// Deflate the token
-        /// </summary>
-        /// <param name="destination">Stream to deflate token to</param>
-        public abstract void Deflate(Stream destination);
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSStream.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSStream.cs
deleted file mode 100644 (file)
index fadd48a..0000000
+++ /dev/null
@@ -1,540 +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.Threading;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Stream that wraps the data with TDS protocol
-    /// </summary>
-    public class TDSStream : Stream
-    {
-        /// <summary>
-        /// Indicates whether inner stream should be closed when TDS stream is closed
-        /// </summary>
-        private bool _leaveInnerStreamOpen = false;
-
-        /// <summary>
-        /// Size of the packet
-        /// </summary>
-        private uint _packetSize;
-
-        /// <summary>
-        /// Header of the packet being processed
-        /// </summary>
-        private TDSPacketHeader OutgoingPacketHeader { get; set; }
-
-        /// <summary>
-        /// Cache of packet header and data
-        /// </summary>
-        private byte[] _outgoingPacket;
-
-        /// <summary>
-        /// Header of the packet being read
-        /// </summary>
-        public TDSPacketHeader IncomingPacketHeader { get; private set; }
-
-        /// <summary>
-        /// Indicates the position inside the request packet data section
-        /// </summary>
-        public ushort IncomingPacketPosition { get; private set; }
-
-        /// <summary>
-        /// Transport stream used to deliver TDS protocol
-        /// </summary>
-        public Stream InnerStream { get; set; }
-
-        /// <summary>
-        /// Size of the TDS packet
-        /// </summary>
-        public uint PacketSize
-        {
-            get
-            {
-                return _packetSize;
-            }
-            set
-            {
-                // Update packet size
-                _packetSize = value;
-
-                // Reallocate outgoing packet buffers
-                _AllocateOutgoingPacket();
-            }
-        }
-
-        /// <summary>
-        /// Identifier of the session
-        /// </summary>
-        public ushort OutgoingSessionID { get; set; }
-
-        /// <summary>
-        /// Indicates whether stream can be read
-        /// </summary>
-        public override bool CanRead
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.CanRead; }
-        }
-
-        /// <summary>
-        /// Indicates whether the stream can be positioned
-        /// </summary>
-        public override bool CanSeek
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.CanSeek; }
-        }
-
-        /// <summary>
-        /// Indicates whether the stream can be written
-        /// </summary>
-        public override bool CanWrite
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.CanWrite; }
-        }
-
-        /// <summary>
-        /// Return the length of the stream
-        /// </summary>
-        public override long Length
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.Length; }
-        }
-
-        /// <summary>
-        /// Return position in the stream
-        /// </summary>
-        public override long Position
-        {
-            // Delegate to the inner stream
-            get { return InnerStream.Position; }
-            set { InnerStream.Position = value; }
-        }
-
-        /// <summary>
-        /// Call back function before calling InnerStream.Write
-        /// the func should return actual packet length to send
-        /// </summary>
-        public Func<byte[], int, int, ushort> PreWriteCallBack { get; set; }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSStream(Stream innerStream) :
-            this(innerStream, true)
-        {
-        }
-
-        /// <summary>
-        /// Initialization constructor
-        /// </summary>
-        public TDSStream(Stream innerStream, bool leaveInnerStreamOpen)
-        {
-            // Check if inner stream is valid
-            if (innerStream == null)
-            {
-                // We can't proceed without underlying stream
-                throw new ArgumentNullException(nameof(innerStream), "Underlying stream is required");
-            }
-
-            // Save transport stream
-            InnerStream = innerStream;
-
-            // Save whether inner stream is to be closed as well
-            _leaveInnerStreamOpen = leaveInnerStreamOpen;
-        }
-
-        /// <summary>
-        /// Close the stream
-        /// </summary>
-        public override void Close()
-        {
-            // Check if inner stream needs to be closed
-            if (!_leaveInnerStreamOpen)
-            {
-                // Close inner stream
-                InnerStream.Close();
-            }
-
-            // Delegate to the base class
-            base.Close();
-        }
-
-        /// <summary>
-        /// Flush the data into the underlying stream
-        /// </summary>
-        public override void Flush()
-        {
-            // Complete current message before flushing the data
-            EndMessage();
-
-            // Delegate to the inner stream
-            InnerStream.Flush();
-        }
-
-        /// <summary>
-        /// Start a new message
-        /// </summary>
-        /// <param name="type">Type of the message to start</param>
-        public virtual void StartMessage(TDSMessageType type)
-        {
-            // Flush current packet if available
-            _SendCurrentPacket();
-
-            // Create a new packet of the specified type
-            _CreateOutgoingPacket(type, 1);
-        }
-
-        /// <summary>
-        /// Send the last packet of the message and complete the request/response
-        /// </summary>
-        public virtual void EndMessage()
-        {
-            // Check if we have a current packet
-            if (OutgoingPacketHeader != null)
-            {
-                // Indicate that this is the end of message
-                OutgoingPacketHeader.Status |= TDSPacketStatus.EndOfMessage;
-
-                // Send the packet out
-                _SendCurrentPacket();
-            }
-        }
-
-        /// <summary>
-        /// Read packet header
-        /// </summary>
-        public virtual bool ReadNextHeader()
-        {
-            // Check if we can move to the next incoming packet header
-            if (!_MoveToNextIncomingPacketHeader())
-            {
-                // We can't reach next header at this time
-                return false;
-            }
-
-            // Allocate a new incoming packet
-            _AllocateIncomingPacket();
-
-            // Inflate the header
-            if (!IncomingPacketHeader.Inflate(InnerStream))
-            {
-                // Header inflation failed
-                return false;
-            }
-
-            // Advance post header position
-            IncomingPacketPosition += TDSPacketHeader.Size;
-
-            // Header successfully inflated
-            return true;
-        }
-
-        /// <summary>
-        /// Read the data from the stream
-        /// </summary>
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            // Indication of current position in the buffer that was read from the underlying stream
-            int bufferReadPosition = 0;
-
-            // Get the starting time
-            DateTime startTime = DateTime.Now;
-
-            // Read operation timeout
-            TimeSpan timeout = new TimeSpan(0, 0, 30); // 30 Sec
-
-            // Iterate while there's buffer data left
-            while (bufferReadPosition < count && DateTime.Now - startTime < timeout)
-            {
-                // We need to make sure that there's a packet to read before we start reading it
-                if (!_EnsureIncomingPacketHasData())
-                {
-                    // We don't have enough data
-                    return bufferReadPosition;
-                }
-
-                // Calculate how much data can be read until the end of the packet is reached
-                long packetDataAvailable = IncomingPacketHeader.Length - IncomingPacketPosition;
-
-                // Check how much data we should give back in the current iteration
-                int packetDataToRead = Math.Min((int)packetDataAvailable, count - bufferReadPosition);
-
-                // Check if there's data chunk still to be returned
-                if (packetDataToRead > 0)
-                {
-                    // Do read operation while the number of read bytes is 0
-                    // Read the data from the underlying stream
-                    int packetDataRead = InnerStream.Read(buffer, bufferReadPosition + offset, packetDataToRead);
-
-                    if (packetDataRead == 0)
-                    {
-                        for (int i = 0; i < 3 && packetDataRead == 0; i++)
-                        {
-                            Thread.Sleep(50);
-                            packetDataRead = InnerStream.Read(buffer, bufferReadPosition + offset, packetDataToRead);
-                        }
-
-                        if (packetDataRead == 0)
-                        {
-                            // Server side socket is FIN_WAIT_2 state, throw
-                            throw new EndOfStreamException("Unexpected end of stream");
-                        }
-                    }
-
-                    // Update current read position
-                    bufferReadPosition += packetDataRead;
-
-                    // Update current packet position
-                    IncomingPacketPosition += (ushort)packetDataRead;
-                }
-            }
-
-            // Check if timeout expired
-            if (DateTime.Now - startTime > timeout)
-            {
-                throw new EndOfStreamException("Unexpected end of stream");
-            }
-
-            return bufferReadPosition;
-        }
-
-        /// <summary>
-        /// Seek position in the stream
-        /// </summary>
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            // Delegate to the inner stream
-            return InnerStream.Seek(offset, origin);
-        }
-
-        /// <summary>
-        /// Set stream length
-        /// </summary>
-        public override void SetLength(long value)
-        {
-            // Delegate to the inner stream
-            InnerStream.SetLength(value);
-        }
-
-        /// <summary>
-        /// Write data into the stream
-        /// </summary>
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            // Indication of current position in the buffer that was sent to the underlying stream
-            int bufferWrittenPosition = 0;
-
-            // Iterate while there's buffer data left
-            while (bufferWrittenPosition < count)
-            {
-                // We need to make sure that current packet has enough space for at least a single byte
-                _EnsureOutgoingPacketHasSpace();
-
-                // Check the last packet available and see how much of data we can write
-                long packetDataAvailable = PacketSize - OutgoingPacketHeader.Length;
-
-                // Check how much data we still have to write
-                // We shouldn't be writing more than packet data available or left to write
-                int packetDataToWrite = Math.Min((int)packetDataAvailable, count - bufferWrittenPosition);
-
-                // Check if there's space in the last packet
-                if (packetDataToWrite > 0)
-                {
-                    // Append new data to the end of the packet data
-                    Array.Copy(buffer, bufferWrittenPosition + offset, _outgoingPacket, OutgoingPacketHeader.Length, packetDataToWrite);
-
-                    // Register that we've written new data
-                    bufferWrittenPosition += packetDataToWrite;
-
-                    // Update packet length
-                    OutgoingPacketHeader.Length += (ushort)packetDataToWrite;
-                }
-            }
-        }
-
-        /// <summary>
-        /// Skip current packet if it is pending and move to the next packet, reading only the header
-        /// </summary>
-        private bool _MoveToNextIncomingPacketHeader()
-        {
-            // Check if we have a packet
-            if (IncomingPacketHeader == null)
-            {
-                // We don't have a packet which means we are at the right spot
-                return true;
-            }
-
-            // Calculate the span between current position in the packet and it's end
-            int distanceToEnd = IncomingPacketHeader.Length - IncomingPacketPosition;
-
-            // Check if we are right at the end of the packet
-            if (distanceToEnd <= 0)
-            {
-                // We consumed the whole packet so we are ready for the next one
-                return true;
-            }
-
-            // Allocate a buffer for the rest of the packet
-            byte[] packetData = new byte[distanceToEnd];
-
-            // Read the data
-            int packetDataRead = InnerStream.Read(packetData, 0, packetData.Length);
-
-            // Update packet position
-            IncomingPacketPosition += (ushort)packetDataRead;
-
-            // Check if all of the data was read
-            return packetDataRead >= packetData.Length;
-        }
-
-        /// <summary>
-        /// This routine checks whether current packet still has data to read and moves to the next if it doesn't
-        /// </summary>
-        private bool _EnsureIncomingPacketHasData()
-        {
-            // Indicates whether the current packet is the one we need
-            bool IsRightPacket = true;  // Assume
-
-            do
-            {
-                // Check if we have a packet
-                if (IncomingPacketHeader == null || !IsRightPacket)
-                {
-                    // Move to the next packet
-                    if (!ReadNextHeader())
-                    {
-                        return false;
-                    }
-                }
-
-                // Check if current packet is right
-                IsRightPacket = (IncomingPacketPosition < IncomingPacketHeader.Length);
-            }
-            while (!IsRightPacket);
-
-            // We found a packet that satisfies the requirements
-            return true;
-        }
-
-        /// <summary>
-        /// Ensures that the current packet has at least a single spare byte
-        /// </summary>
-        /// <param name="type">Type of the packet to look for</param>
-        private void _EnsureOutgoingPacketHasSpace()
-        {
-            // Check if we have a packet
-            if (OutgoingPacketHeader == null)
-            {
-                // Message must be started before we can ensure packet availability
-                throw new InvalidOperationException("Message has not been started");
-            }
-
-            // Check if last packet has no space in it
-            if (OutgoingPacketHeader.Length >= PacketSize)
-            {
-                // Save outgoing packet type before sending it, which will reset the packet header
-                TDSMessageType outgoingPacketType = OutgoingPacketHeader.Type;
-
-                // Save outgoing packet number
-                byte packetID = OutgoingPacketHeader.PacketID;
-
-                // Before allocating a new packet we need to serialize the current packet
-                _SendCurrentPacket();
-
-                // Allocate a new packet since the last packet is full
-                _CreateOutgoingPacket(outgoingPacketType, (byte)(((int)packetID + 1) % 256));
-            }
-        }
-
-        /// <summary>
-        /// Create a new TDS packet in the message
-        /// </summary>
-        private void _CreateOutgoingPacket(TDSMessageType type, byte packetID)
-        {
-            // Allocate an outgoing packet in case it isn't available
-            _AllocateOutgoingPacket();
-
-            // Allocate a new packet with the specified type and normal status
-            OutgoingPacketHeader = new TDSPacketHeader(_outgoingPacket, type, TDSPacketStatus.Normal);
-
-            // Assign session identifier to the packet
-            OutgoingPacketHeader.SPID = OutgoingSessionID;
-
-            // Increment packet identifier
-            OutgoingPacketHeader.PacketID = packetID;
-        }
-
-        /// <summary>
-        /// Serialize current packet into the underlying stream
-        /// </summary>
-        private void _SendCurrentPacket()
-        {
-            // Check if we have a current packet
-            if (OutgoingPacketHeader != null)
-            {
-                // store the OutgoingPacketHeader.Length, it could be updated in PreWriteCallBack (for Fuzz test)
-                ushort outgoingPacketHeader_Length = OutgoingPacketHeader.Length;
-
-                // PreWrite call before packet writing
-                if (PreWriteCallBack != null)
-                {
-                    // By calling PreWriteCallBack,
-                    // The length value in OutgoingPacketHeader (i.e. OutgoingPacketHeader.Length) could be fuzzed
-                    // The actual written length of the packet (i.e. outgoingPacketHeader_Length) could be fuzzed
-                    outgoingPacketHeader_Length = PreWriteCallBack(_outgoingPacket, 0, OutgoingPacketHeader.Length);
-                }
-
-                // Send the packet header along with packet body into the underlying stream
-                InnerStream.Write(_outgoingPacket, 0, outgoingPacketHeader_Length);
-
-                // Reset packet header
-                OutgoingPacketHeader = null;
-
-                // Reset packet
-                _outgoingPacket = null;
-            }
-        }
-
-        /// <summary>
-        /// Allocate or reallocate a packet
-        /// </summary>
-        private void _AllocateOutgoingPacket()
-        {
-            // Check if we have incoming packet already
-            if (_outgoingPacket != null)
-            {
-                // Check if incoming packet complies
-                if (_outgoingPacket.Length != PacketSize)
-                {
-                    // Re-allocate
-                    Array.Resize(ref _outgoingPacket, (int)PacketSize);
-                }
-            }
-            else
-            {
-                // Allocate a new packet
-                _outgoingPacket = new byte[PacketSize];
-            }
-        }
-
-        /// <summary>
-        /// Prepare to read and inflate incoming packet
-        /// </summary>
-        private void _AllocateIncomingPacket()
-        {
-            // Create a new incoming packet header
-            IncomingPacketHeader = new TDSPacketHeader(new byte[TDSPacketHeader.Size]);
-
-            // Reset header data position
-            IncomingPacketPosition = 0;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSTokenFactory.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSTokenFactory.cs
deleted file mode 100644 (file)
index 1eb1256..0000000
+++ /dev/null
@@ -1,171 +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.IO;
-using System.Linq;
-
-using Microsoft.SqlServer.TDS.Authentication;
-using Microsoft.SqlServer.TDS.ColInfo;
-using Microsoft.SqlServer.TDS.ColMetadata;
-using Microsoft.SqlServer.TDS.Done;
-using Microsoft.SqlServer.TDS.EnvChange;
-using Microsoft.SqlServer.TDS.Error;
-using Microsoft.SqlServer.TDS.FeatureExtAck;
-using Microsoft.SqlServer.TDS.Info;
-using Microsoft.SqlServer.TDS.LoginAck;
-using Microsoft.SqlServer.TDS.Row;
-using Microsoft.SqlServer.TDS.SSPI;
-using Microsoft.SqlServer.TDS.SessionState;
-using Microsoft.SqlServer.TDS.ReturnStatus;
-using Microsoft.SqlServer.TDS.Order;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Constructor for TDS tokens
-    /// </summary>
-    public class TDSTokenFactory
-    {
-        /// <summary>
-        /// Reconstruct token sequence from the stream
-        /// </summary>
-        /// <returns>Token collection</returns>
-        public static IList<TDSPacketToken> Create(Stream source)
-        {
-            // Prepare collection
-            IList<TDSPacketToken> tokens = new List<TDSPacketToken>();
-
-            // Process the whole stream
-            while (source.Position < source.Length)
-            {
-                // Read token type
-                TDSTokenType tokenType = (TDSTokenType)source.ReadByte();
-
-                // Call corresponding constructor based on the token type
-                switch (tokenType)
-                {
-                    case TDSTokenType.EnvironmentChange:
-                        {
-                            tokens.Add(new TDSEnvChangeToken());
-                            break;
-                        }
-                    case TDSTokenType.Info:
-                        {
-                            tokens.Add(new TDSInfoToken());
-                            break;
-                        }
-                    case TDSTokenType.Error:
-                        {
-                            tokens.Add(new TDSErrorToken());
-                            break;
-                        }
-                    case TDSTokenType.Done:
-                        {
-                            tokens.Add(new TDSDoneToken());
-                            break;
-                        }
-                    case TDSTokenType.DoneInProc:
-                        {
-                            tokens.Add(new TDSDoneInProcToken());
-                            break;
-                        }
-                    case TDSTokenType.DoneProcedure:
-                        {
-                            tokens.Add(new TDSDoneProcedureToken());
-                            break;
-                        }
-                    case TDSTokenType.LoginAcknowledgement:
-                        {
-                            tokens.Add(new TDSLoginAckToken());
-                            break;
-                        }
-                    case TDSTokenType.ColumnInfo:
-                        {
-                            tokens.Add(new TDSColInfoToken());
-                            break;
-                        }
-                    case TDSTokenType.ColumnMetadata:
-                        {
-                            tokens.Add(new TDSColMetadataToken());
-                            break;
-                        }
-                    case TDSTokenType.Row:
-                        {
-                            // Find column metadata token
-                            TDSColMetadataToken columnMetadata = tokens.Where(t => t is TDSColMetadataToken).LastOrDefault() as TDSColMetadataToken;
-
-                            // Column metadata must be immediately preceeding row
-                            if (columnMetadata == null)
-                            {
-                                throw new Exception("No column metadata is available for row token");
-                            }
-
-                            tokens.Add(new TDSRowToken(columnMetadata));
-                            break;
-                        }
-                    case TDSTokenType.NBCRow:
-                        {
-                            // Find column metadata token
-                            TDSColMetadataToken columnMetadata = tokens.Where(t => t is TDSColMetadataToken).LastOrDefault() as TDSColMetadataToken;
-
-                            // Column metadata must be immediately preceeding row
-                            if (columnMetadata == null)
-                            {
-                                throw new Exception("No column metadata is available for null-byte compression row token");
-                            }
-
-                            tokens.Add(new TDSNBCRowToken(columnMetadata));
-                            break;
-                        }
-                    case TDSTokenType.SSPI:
-                        {
-                            tokens.Add(new TDSSSPIToken());
-                            break;
-                        }
-                    case TDSTokenType.FedAuthInfo:
-                        {
-                            tokens.Add(new TDSFedAuthInfoToken());
-                            break;
-                        }
-                    case TDSTokenType.FeatureExtAck:
-                        {
-                            tokens.Add(new TDSFeatureExtAckToken());
-                            break;
-                        }
-                    case TDSTokenType.SessionState:
-                        {
-                            tokens.Add(new TDSSessionStateToken());
-                            break;
-                        }
-                    case TDSTokenType.ReturnStatus:
-                        {
-                            tokens.Add(new TDSReturnStatusToken());
-                            break;
-                        }
-                    case TDSTokenType.Order:
-                        {
-                            tokens.Add(new TDSOrderToken());
-                            break;
-                        }
-                    default:
-                        {
-                            // Either the token has not been implemented yet or is invalid
-                            throw new NotImplementedException(string.Format("Token \"{0}\" is not recognized", tokenType));
-                        }
-                }
-
-                // Inflate the last token from the stream
-                if (!tokens.Last().Inflate(source))
-                {
-                    // Throw exception at this point since this operation is not interruptable (yet)
-                    throw new Exception(string.Format("Token \"{0}\" inflation failed", tokenType));
-                }
-            }
-
-            return tokens;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSTokenType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSTokenType.cs
deleted file mode 100644 (file)
index 23ba1c1..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Types of the tokens in data buffer of the packet
-    /// </summary>
-    public enum TDSTokenType
-    {
-        AlternativeMetadata = 088,
-        AlternativeRow = 0xD3,
-        ColumnMetadata = 0x81,
-        ColumnInfo = 0xA5,
-        Done = 0xFD,
-        DoneProcedure = 0xFE,
-        DoneInProc = 0xFF,
-        EnvironmentChange = 0xE3,
-        Error = 0xAA,
-        FeatureExtAck = 0xAE,
-        FedAuthInfo = 0xEE,
-        Info = 0xAB,
-        LoginAcknowledgement = 0xAD,
-        NBCRow = 0xD2,
-        Offset = 0x78,
-        Order = 0xA9,
-        ReturnStatus = 0x79,
-        ReturnValue = 0xAC,
-        Row = 0xD1,
-        SSPI = 0xED,
-        TableName = 0xA4,
-        SessionState = 0xE4,
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSUtilities.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSUtilities.cs
deleted file mode 100644 (file)
index 111d959..0000000
+++ /dev/null
@@ -1,444 +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.Reflection;
-using System.Security.Cryptography;
-using System.Text;
-
-using Microsoft.SqlServer.TDS.Login7;
-using Microsoft.SqlServer.TDS.PreLogin;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Internal utilities
-    /// </summary>
-    public static class TDSUtilities
-    {
-        /// <summary>
-        /// Object lock for log writer
-        /// </summary>
-        private static object s_logWriterLock = new object();
-
-        /// <summary>
-        /// Read unsigned long from the stream
-        /// </summary>
-        internal static ulong ReadULong(Stream source)
-        {
-            return (ulong)(source.ReadByte()
-                + (source.ReadByte() << 8)
-                + (source.ReadByte() << 16)
-                + (source.ReadByte() << 24)
-                + (source.ReadByte() << 32)
-                + (source.ReadByte() << 40)
-                + (source.ReadByte() << 48)
-                + (source.ReadByte() << 56));
-        }
-
-        /// <summary>
-        /// Write unsigned long into the stream
-        /// </summary>
-        internal static void WriteULong(Stream destination, ulong value)
-        {
-            destination.WriteByte((byte)(value & 0xff));
-            destination.WriteByte((byte)((value >> 8) & 0xff));
-            destination.WriteByte((byte)((value >> 16) & 0xff));
-            destination.WriteByte((byte)((value >> 24) & 0xff));
-            destination.WriteByte((byte)((value >> 32) & 0xff));
-            destination.WriteByte((byte)((value >> 40) & 0xff));
-            destination.WriteByte((byte)((value >> 48) & 0xff));
-            destination.WriteByte((byte)((value >> 56) & 0xff));
-        }
-
-        /// <summary>
-        /// Read unsigned integer from the stream
-        /// </summary>
-        internal static uint ReadUInt(Stream source)
-        {
-            return (uint)(source.ReadByte())
-                + (uint)(source.ReadByte() << 8)
-                + (uint)(source.ReadByte() << 16)
-                + (uint)(source.ReadByte() << 24);
-        }
-
-        /// <summary>
-        /// Write unsigned integer into the stream
-        /// </summary>
-        public static void WriteUInt(Stream destination, uint value)
-        {
-            unchecked
-            {
-                destination.WriteByte((byte)value);
-                destination.WriteByte((byte)(value >> 8));
-                destination.WriteByte((byte)(value >> 16));
-                destination.WriteByte((byte)(value >> 24));
-            }
-        }
-
-        /// <summary>
-        /// Read signed integer from the packet
-        /// </summary>
-        internal static int ReadInt(Stream source)
-        {
-            return (int)(source.ReadByte())
-                + (int)(source.ReadByte() << 8)
-                + (int)(source.ReadByte() << 16)
-                + (int)(source.ReadByte() << 24);
-        }
-
-        /// <summary>
-        /// Write signed integer into the stream
-        /// </summary>
-        internal static void WriteInt(Stream destination, int value)
-        {
-            destination.WriteByte((byte)value);
-            destination.WriteByte((byte)(value >> 8));
-            destination.WriteByte((byte)(value >> 16));
-            destination.WriteByte((byte)(value >> 24));
-        }
-
-        /// <summary>
-        /// Read unsigned short from the packet
-        /// </summary>
-        internal static ushort ReadUShort(Stream source)
-        {
-            return (ushort)(source.ReadByte() + (ushort)(source.ReadByte() << 8));
-        }
-
-        /// <summary>
-        /// Write unsigned short into the stream
-        /// </summary>
-        internal static void WriteUShort(Stream destination, ushort value)
-        {
-            destination.WriteByte(unchecked((byte)value));
-            destination.WriteByte((byte)(value >> 8));
-        }
-
-        /// <summary>
-        /// Write unsigned short into the stream in network byte order (big-endian)
-        /// </summary>
-        internal static void WriteUShortBigEndian(Stream destination, ushort value)
-        {
-            destination.WriteByte((byte)(value >> 8));
-            destination.WriteByte((byte)value);
-        }
-
-        /// <summary>
-        /// Read string from the packet
-        /// </summary>
-        internal static string ReadString(Stream source, ushort length)
-        {
-            // Check if any data will be read
-            if (length == 0)
-            {
-                // Instead of returning an empty string later we just return NULL
-                return null;
-            }
-
-            // Allocate buffer
-            byte[] byteString = new byte[length];
-
-            // Read into a byte buffer
-            source.Read(byteString, 0, byteString.Length);
-
-            // Convert
-            return Encoding.Unicode.GetString(byteString, 0, byteString.Length);
-        }
-
-        /// <summary>
-        /// Write string from into the packet
-        /// </summary>
-        internal static void WriteString(Stream destination, string value)
-        {
-            // Check if value is null
-            if (string.IsNullOrEmpty(value))
-            {
-                // There's nothing to write
-                return;
-            }
-
-            // Convert
-            byte[] byteString = Encoding.Unicode.GetBytes(value);
-
-            // Write into a the stream
-            destination.Write(byteString, 0, byteString.Length);
-        }
-
-        /// <summary>
-        /// Read a password string and decrypt it
-        /// </summary>
-        internal static string ReadPasswordString(Stream source, ushort length)
-        {
-            // Allocate buffer
-            byte[] byteString = new byte[length];
-
-            // Read into a byte buffer
-            source.Read(byteString, 0, byteString.Length);
-
-            // Perform password decryption
-            for (int i = 0; i < byteString.Length; i++)
-            {
-                // XOR first
-                byteString[i] ^= 0xA5;
-
-                // Swap 4 high bits with 4 low bits
-                byteString[i] = (byte)(((byteString[i] & 0xf0) >> 4) | ((byteString[i] & 0xf) << 4));
-            }
-
-            // Convert
-            return Encoding.Unicode.GetString(byteString, 0, byteString.Length);
-        }
-
-        /// <summary>
-        /// Write password string encrypted into the packet
-        /// </summary>
-        internal static void WritePasswordString(Stream destination, string value)
-        {
-            // Check if value is null
-            if (string.IsNullOrEmpty(value))
-            {
-                // There's nothing to write
-                return;
-            }
-
-            // Convert
-            byte[] byteString = Encoding.Unicode.GetBytes(value);
-
-            // Perform password decryption
-            for (int i = 0; i < byteString.Length; i++)
-            {
-                // Swap 4 high bits with 4 low bits
-                byteString[i] = (byte)(((byteString[i] & 0xf0) >> 4) | ((byteString[i] & 0xf) << 4));
-
-                // XOR
-                byteString[i] ^= 0xA5;
-            }
-
-            // Write into a the stream
-            destination.Write(byteString, 0, byteString.Length);
-        }
-
-        /// <summary>
-        /// Generate an encryption response based on the client request and server setting
-        /// </summary>
-        /// <param name="client">A value received from the client</param>
-        /// <param name="server">Configuration of the server</param>
-        public static TDSPreLoginTokenEncryptionType GetEncryptionResponse(TDSPreLoginTokenEncryptionType client, TDSPreLoginTokenEncryptionType server)
-        {
-            // Check each equivalence class
-            if (client == TDSPreLoginTokenEncryptionType.NotSupported)
-            {
-                // Check server response
-                if (server == TDSPreLoginTokenEncryptionType.Off || server == TDSPreLoginTokenEncryptionType.NotSupported)
-                {
-                    return TDSPreLoginTokenEncryptionType.NotSupported;
-                }
-                else
-                {
-                    return TDSPreLoginTokenEncryptionType.Required;
-                }
-            }
-            else if (client == TDSPreLoginTokenEncryptionType.Off)
-            {
-                // Check corresponding server
-                if (server == TDSPreLoginTokenEncryptionType.NotSupported)
-                {
-                    return TDSPreLoginTokenEncryptionType.NotSupported;
-                }
-                else if (server == TDSPreLoginTokenEncryptionType.Off)
-                {
-                    return TDSPreLoginTokenEncryptionType.Off;
-                }
-                else
-                {
-                    return TDSPreLoginTokenEncryptionType.Required;
-                }
-            }
-            else if (client == TDSPreLoginTokenEncryptionType.On)
-            {
-                // Check server
-                if (server == TDSPreLoginTokenEncryptionType.Off || server == TDSPreLoginTokenEncryptionType.On || server == TDSPreLoginTokenEncryptionType.Required)
-                {
-                    return TDSPreLoginTokenEncryptionType.On;
-                }
-                else
-                {
-                    throw new ArgumentException("Server is configured to not support encryption", "server");
-                }
-            }
-
-            // This case is not documented so pick a default
-            return TDSPreLoginTokenEncryptionType.Off;
-        }
-
-        /// <summary>
-        /// Convert indications of encryption support by client and server into expected behavior
-        /// </summary>
-        public static TDSEncryptionType ResolveEncryption(TDSPreLoginTokenEncryptionType client, TDSPreLoginTokenEncryptionType server)
-        {
-            // Check each equivalence class
-            if (client == TDSPreLoginTokenEncryptionType.NotSupported)
-            {
-                // Check server response
-                if (server == TDSPreLoginTokenEncryptionType.Off || server == TDSPreLoginTokenEncryptionType.NotSupported)
-                {
-                    return TDSEncryptionType.Off;
-                }
-                else
-                {
-                    // Encrypt login only
-                    return TDSEncryptionType.LoginOnly;
-                }
-            }
-            else if (client == TDSPreLoginTokenEncryptionType.Off)
-            {
-                // Check corresponding server
-                if (server == TDSPreLoginTokenEncryptionType.NotSupported)
-                {
-                    // Encryption should be turned off
-                    return TDSEncryptionType.Off;
-                }
-                else if (server == TDSPreLoginTokenEncryptionType.Off)
-                {
-                    // We encrypt only login packet
-                    return TDSEncryptionType.LoginOnly;
-                }
-            }
-            else if (client == TDSPreLoginTokenEncryptionType.On)
-            {
-                // Check server
-                if (server == TDSPreLoginTokenEncryptionType.NotSupported || server == TDSPreLoginTokenEncryptionType.Off)
-                {
-                    // This is an error case, however existing client stacks treat this as login-only encryption
-                    return TDSEncryptionType.LoginOnly;
-                }
-            }
-
-            // Full encryption is required
-            return TDSEncryptionType.Full;
-        }
-
-        /// <summary>
-        /// Log object content into destination
-        /// </summary>
-        /// <param name="log">Destination</param>
-        /// <param name="prefix">Prefix the output with</param>
-        /// <param name="instance">Object to log</param>
-        public static void Log(TextWriter log, string prefix, object instance)
-        {
-            // Check log validity
-            if (log == null)
-            {
-                // Don't log anything
-                return;
-            }
-
-            // Check if null
-            if (instance == null)
-            {
-                SerializedWriteLineToLog(log, string.Format("{0}: <null>", prefix));
-
-                return;
-            }
-
-            // Get object type
-            Type objectType = instance.GetType();
-
-            // Check if simple type
-            if (objectType.IsEnum
-                || instance is bool
-                || instance is string
-                || instance is int
-                || instance is uint
-                || instance is byte
-                || instance is sbyte
-                || instance is short
-                || instance is ushort
-                || instance is long
-                || instance is ulong
-                || instance is double
-                || instance is float
-                || instance is Version)
-            {
-                SerializedWriteLineToLog(log, string.Format("{0}: {1}", prefix, instance));
-
-                return;
-            }
-
-
-            // Check declaring type
-            if (objectType.IsGenericType || (objectType.BaseType != null && objectType.BaseType.IsGenericType))  // IList<T>
-            {
-                int index = 0;
-
-                // Log values
-                foreach (object o in (instance as System.Collections.IEnumerable))
-                {
-                    Log(log, string.Format("{0}[{1}]", prefix, index++), o);
-                }
-
-                // Check if we logged anything
-                if (index == 0)
-                {
-                    SerializedWriteLineToLog(log, string.Format("{0}: <empty>", prefix));
-                }
-            }
-            else if (objectType.IsArray)
-            {
-                // Prepare prefix
-                string preparedLine = string.Format("{0}: [", prefix);
-
-                // Log values
-                foreach (object o in (instance as Array))
-                {
-                    preparedLine += string.Format("{0:X} ", o);
-                }
-
-                // Finish the line
-                preparedLine += "]";
-
-                // Move to the next line
-                SerializedWriteLineToLog(log, preparedLine);
-            }
-
-            // Iterate all public properties
-            foreach (PropertyInfo info in objectType.GetProperties())
-            {
-                // Check if this is an indexer
-                if (info.GetIndexParameters().Length > 0 || !info.DeclaringType.Assembly.Equals(Assembly.GetExecutingAssembly()))
-                {
-                    // We ignore indexers
-                    continue;
-                }
-
-                // Get property value
-                object value = info.GetValue(instance, null);
-
-                // Log each property
-                Log(log, string.Format("{0}.{1}.{2}", prefix, objectType.Name, info.Name), value);
-            }
-
-            // Flush to destination
-            lock (s_logWriterLock)
-            {
-                log.Flush();
-            }
-        }
-
-        /// <summary>
-        /// Serialized write line to destination
-        /// </summary>
-        /// <param name="log">Destination</param>
-        /// <param name="text">Text to log</param>
-        public static void SerializedWriteLineToLog(TextWriter log, string text)
-        {
-            lock (s_logWriterLock)
-            {
-                log.WriteLine(string.Format("[{0}] {1}", DateTime.Now, text));
-            }
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSVersion.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TDSVersion.cs
deleted file mode 100644 (file)
index e9e9493..0000000
+++ /dev/null
@@ -1,88 +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;
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// TDS version routines
-    /// </summary>
-    public static class TDSVersion
-    {
-        /// <summary>
-        /// Yukon TDS version
-        /// </summary>
-        public static Version SqlServer2005 = new Version(7, 2, 9, 2);
-
-        /// <summary>
-        /// Katmai TDS version
-        /// </summary>
-        public static Version SqlServer2008 = new Version(7, 3, 11, 3);
-
-        /// <summary>
-        /// Denali TDS version
-        /// </summary>
-        public static Version SqlServer2010 = new Version(7, 4, 0, 4);
-
-        /// <summary>
-        /// Map SQL Server build version to TDS version
-        /// </summary>
-        /// <param name="buildVersion">Build version to analyze</param>
-        /// <returns>TDS version that corresponding build version supports</returns>
-        public static Version GetTDSVersion(Version buildVersion)
-        {
-            // Check build version Major part
-            if (buildVersion.Major == 11)
-            {
-                // Denali
-                return SqlServer2010;
-            }
-            else if (buildVersion.Major == 10)
-            {
-                // Katmai
-                return SqlServer2008;
-            }
-            else if (buildVersion.Major == 9)
-            {
-                // Yukon
-                return SqlServer2005;
-            }
-            else
-            {
-                // Not supported TDS version
-                throw new NotSupportedException("Specified build version is not supported");
-            }
-        }
-
-        /// <summary>
-        /// Resolve conflicts between client and server TDS version
-        /// </summary>
-        /// <param name="tdsServer">Version of the server</param>
-        /// <param name="tdsClient">Version of the client</param>
-        /// <returns>Resulting version that both parties can talk</returns>
-        public static Version Resolve(Version tdsServer, Version tdsClient)
-        {
-            // Pick the lowest TDS version between client and server
-            if (tdsServer > tdsClient)
-            {
-                // Client doesn't talk our TDS version - downgrade it to client's
-                return tdsClient;
-            }
-            else
-            {
-                // Client supports our TDS version
-                return tdsServer;
-            }
-        }
-
-        /// <summary>
-        /// Check whether TDS version is supported by server
-        /// </summary>
-        public static bool IsSupported(Version tdsVersion)
-        {
-            return tdsVersion >= SqlServer2005 && tdsVersion <= SqlServer2010;
-        }
-    }
-}
diff --git a/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TransactionIsolationLevelType.cs b/src/libraries/System.Data.SqlClient/tests/Tools/TDS/TDS/TransactionIsolationLevelType.cs
deleted file mode 100644 (file)
index f575372..0000000
+++ /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.
-
-namespace Microsoft.SqlServer.TDS
-{
-    /// <summary>
-    /// Transaction isolation level
-    /// </summary>
-    public enum TransactionIsolationLevelType : byte
-    {
-        /// <summary>
-        /// Specifies that statements can read rows that have been modified by other transactions but not yet committed
-        /// </summary>
-        ReadUncommited = 1,
-
-        /// <summary>
-        /// Specifies that statements cannot read data that has been modified but not committed by other transactions
-        /// </summary>
-        ReadCommited = 2,
-
-        /// <summary>
-        /// Specifies that statements cannot read data that has been modified but not yet committed by other transactions and that no other transactions can modify data that has been read by the current transaction until the current transaction completes.
-        /// </summary>
-        RepeatableRead = 3,
-
-        /// <summary>
-        /// Specifies that data read by any statement in a transaction will be the transactionally consistent version of the data that existed at the start of the transaction
-        /// </summary>
-        Serializable = 4,
-
-        /// <summary>
-        /// Statements cannot read data that has been modified but not yet committed by other transactions
-        /// </summary>
-        Snapshot = 5
-    }
-}
index 5a0cb0d..bf9322b 100644 (file)
@@ -32,4 +32,7 @@
   <ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
     <Reference Include="System.Text.Json" />
   </ItemGroup>
+  <ItemGroup>
+    <PackageReference Include="System.Data.SqlClient" Version="$(SystemDataSqlClientVersion)" />
+  </ItemGroup>
 </Project>
index d5b1bf1..4129362 100644 (file)
@@ -22,7 +22,6 @@
     <PrereleaseLibraryPackage Include="System.Configuration.ConfigurationManager" />
     <PrereleaseLibraryPackage Include="System.Data.Odbc" />
     <PrereleaseLibraryPackage Include="System.Data.OleDb" />
-    <PrereleaseLibraryPackage Include="System.Data.SqlClient" />
     <PrereleaseLibraryPackage Include="System.Drawing.Common" />
     <PrereleaseLibraryPackage Include="System.Diagnostics.EventLog" />
     <PrereleaseLibraryPackage Include="System.Diagnostics.PerformanceCounter" />
@@ -59,6 +58,9 @@
     <LibraryPackage Include="System.Data.DataSetExtensions">
       <Version>4.5.0</Version>
     </LibraryPackage>
+    <LibraryPackage Include="System.Data.SqlClient">
+      <Version>4.8.0</Version>
+    </LibraryPackage>
 
     <!-- Service model packages -->
     <ExternalLibraryPackage Include="System.ServiceModel.Primitives">
index 2fddfa5..44b22ba 100644 (file)
     <PackageReference Include="System.Memory" Version="4.5.3" Condition="'$(TargetFramework)' == 'netcoreapp2.0' or '$(TargetsNetfx)' == 'true' or ('$(TargetsNetStandard)' == 'true' and '$(NETStandardVersion)' &gt;= 1.1)" />
     <PackageReference Include="System.Numerics.Vectors" Version="4.5.0" Condition="'$(TargetsNetStandardLowerThan21)' == 'true' or '$(TargetsNetfx)' == 'true'" />
     <PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.2" Condition="'$(TargetFramework)' == 'netcoreapp2.0' or '$(TargetsNetfx)' == 'true' or '$(TargetsNetStandard)' == 'true'" />
-    <PackageReference Include="System.Data.SqlClient" Version="4.7.0" Condition="'$(TargetsNetfx)' == 'true'" />
   </ItemGroup>
   
   <ItemGroup>
     <PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="1.0.0" Condition="'$(TargetsNetStandard)' != 'true' or '$(NETStandardVersion)' &gt;= 2.0" />
+    <PackageReference Include="System.Data.SqlClient" Version="$(SystemDataSqlClientVersion)" Condition="'$(TargetsNetStandard)' != 'true' or '$(NETStandardVersion)' &gt;= 2.0" />
     <!-- Only include the assets from the direct packages we reference in the output -->
     <PackageToInclude Include="@(PackageReference)" />
   </ItemGroup>
index 8f605de..e42d5ec 100644 (file)
@@ -21,6 +21,8 @@
     <GenFacadesIgnoreMissingTypes>true</GenFacadesIgnoreMissingTypes>
     <IncludeDefaultReferences>false</IncludeDefaultReferences>
     <HasMatchingContract>true</HasMatchingContract>
+    <!-- Shims have no code in them. No point in running IL linker over them -->
+    <ILLinkTrimAssembly>false</ILLinkTrimAssembly>
   </PropertyGroup>
 
   <ItemGroup Condition="'$(MSBuildProjectName)' == 'System.Runtime' or '$(MSBuildProjectName)' == 'mscorlib' or '$(MSBuildProjectName)' == 'netstandard'">
index 9d964c8..aafe7e5 100644 (file)
@@ -2,4 +2,9 @@
   <ItemGroup>
     <Compile Include="System.Data.forwards.cs" />
   </ItemGroup>
-</Project>
\ No newline at end of file
+  <ItemGroup>
+    <!-- System.Data.SqlClient is not live built anymore, make sure to use reference assembly for it -->
+    <ReferencePath Remove="$(RefPath)\System.Data.SqlClient.dll" />
+    <ReferencePath Include="$(ArtifactsBinDir)ref\$(NetCoreAppCurrent)\System.Data.SqlClient.dll" />
+  </ItemGroup>
+</Project>
index 7d4cf24..21ace5d 100644 (file)
 -nomethod System.Security.Cryptography.Encoding.Tests.OidTests.LookupOidByFriendlyName_Ctor
 
 -nomethod System.Tests.StringComparerTests.CreateCultureOptions_InvalidArguments_Throws
+
+####################################################################
+##  System.Data.SqlClient
+####################################################################
+
+# The tests are loading wrong System.Data.SqlClient - https://github.com/dotnet/runtime/issues/31799
+-nomethod System.Runtime.Serialization.Formatters.Tests.BinaryFormatterTests.RoundtripManyObjectsInOneStream
+-nomethod System.Runtime.Serialization.Formatters.Tests.BinaryFormatterTests.ValidateBasicObjectsRoundtrip
+-noclass System.Data.Common.DbProviderFactoriesTests
index d9e7365..dd20822 100644 (file)
@@ -27,7 +27,6 @@
 -nonamespace System.Security.Cryptography.Pkcs
 -nonamespace System.Runtime.InteropServices.WindowsRuntime
 -nonamespace System.Management.Tests
--nonamespace System.Data.SqlClient.Tests
 -nonamespace System.Threading.Overlapped.Tests
 -nonamespace System.ComponentModel.Composition
 -nonamespace BasicEventSourceTests
@@ -70,4 +69,4 @@
 -nomethod System.Globalization.Tests.StringNormalizationTests.IsNormalized
 
 # * Assertion at method-to-ir.c:12425, condition `var->opcode == OP_REGOFFSET' not met
--nomethod System.Runtime.Tests.NullableMetadataTests.ShimsHaveOnlyTypeForwards
\ No newline at end of file
+-nomethod System.Runtime.Tests.NullableMetadataTests.ShimsHaveOnlyTypeForwards