diff --git a/BUILDGUIDE.md b/BUILDGUIDE.md
index dcb2257745..a4e0b16e00 100644
--- a/BUILDGUIDE.md
+++ b/BUILDGUIDE.md
@@ -5,7 +5,6 @@ This document provides all the necessary details to build the driver and run tes
## Visual Studio Pre-Requisites
This project should be built with Visual Studio 2019+ for the best compatibility. The required set of components are provided in the below file:
-
- **Visual Studio 2019** with imported components: [VS19Components](/tools/vsconfig/VS19Components.vsconfig)
Once the environment is setup properly, execute the desired set of commands below from the _root_ folder to perform the respective operations:
@@ -20,11 +19,6 @@ msbuild
# Both .NET Framework (NetFx) and .NET Core drivers are built by default (as supported by Client OS).
```
-```bash
-msbuild -t:clean
-# Cleans all build directories.
-```
-
```bash
msbuild -p:Configuration=Release
# Builds the driver in 'Release' Configuration for `AnyCPU` platform.
@@ -35,6 +29,11 @@ msbuild -p:Platform=Win32
# Builds the .NET Framework (NetFx) driver for Win32 (x86) platform on Windows in 'Debug' Configuration.
```
+```bash
+msbuild -t:clean
+# Cleans all build directories.
+```
+
```bash
msbuild -t:restore
# Restores Nuget Packages.
@@ -73,63 +72,14 @@ msbuild -t:BuildTestsNetFx
# Build the tests for the .NET Framework (NetFx) driver in 'Debug' Configuration. Default .NET Framework version is 4.6.1.
```
-```bash
-msbuild -t:BuildTestsNetCore -p:TestSet=1
-# Build a subset of the manual tests. Valid values: '1', '2', '3', 'AE'. Omit to build all tests.
-```
-
-## Running Tests
-
-There are 2 ways to run tests, using MsBuild or Dotnet SDK.
-
-### Running from Build.proj
-
-```bash
-msbuild -t:RunFunctionalTests
-# Run all functional tests for *default* target framework (.NET Core 3.1).
-```
-
-```bash
-msbuild -t:RunManualTests
-# Run all manual tests for *default* target framework (.NET Core 3.1).
-```
-
-```bash
-msbuild -t:RunTests -p:configuration=Release
-# Run both functional and manual tests for *default* target framework (.NET Core 3.1).
-```
-
-To specify custom target framework, use `TF` property:
-
-```bash
-msbuild -t:RunTests -p:configuration=Release -p:TF=net5.0
-msbuild -t:RunTests -p:configuration=Release -p:TF=net48
-# Runs tests for specified target framework.
-# TargetNetCoreVersion and TargetNetFxVersion are not to be used with TF property, they will take precedence over TF if provided.
-```
-
-To capture test and code coverage results in a custom directory:
-
-```bash
-msbuild -t:RunTests -p:ResultsDirectory=MyDirectory
-# Runs tests with test and code coverage results placed in provided results directory.
-# Default results directory is "TestResults".
-```
-
-Other properties can be set alongside as needed.
-
-### Running using Dotnet SDK (traditional)
-
-#### Run Functional Tests
+## Run Functional Tests
- Windows (`netfx x86`):
-
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.SqlClient.Tests.csproj" -p:Platform="Win32" -p:Configuration="Release" -p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests"
```
- Windows (`netfx x64`):
-
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.SqlClient.Tests.csproj" -p:Platform="x64" -p:Configuration="Release" -p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests"
```
@@ -137,26 +87,22 @@ dotnet test "src\Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.S
- AnyCPU:
Windows (`netcoreapp`):
-
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.SqlClient.Tests.csproj" -p:Platform="AnyCPU" -p:Configuration="Release" -p:TestTargetOS="Windowsnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonwindowstests"
```
Unix (`netcoreapp`):
-
```bash
dotnet test "src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj" -p:Platform="AnyCPU" -p:Configuration="Release" -p:TestTargetOS="Unixnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonlinuxtests&category!=nonuaptests"
```
-#### Run Manual Tests
-
-### Pre-Requisites for running Manual tests
+## Run Manual Tests
+### Pre-Requisites for running Manual tests:
Manual Tests require the below setup to run:
-
-- SQL Server with enabled Shared Memory, TCP and Named Pipes Protocols and access to the Client OS.
-- Databases "NORTHWIND" and "UdtTestDb" present in SQL Server, created using SQL scripts [createNorthwindDb.sql](tools/testsql/createNorthwindDb.sql) and [createUdtTestDb.sql](tools/testsql/createUdtTestDb.sql). To setup an Azure Database with "NORTHWIND" tables, use SQL Script: [createNorthwindAzureDb.sql](tools/testsql/createNorthwindAzureDb.sql).
-- Make a copy of the configuration file [config.default.json](src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json) and rename it to `config.json`. Update the values in `config.json`:
+* SQL Server with enabled Shared Memory, TCP and Named Pipes Protocols and access to the Client OS.
+* Databases "NORTHWIND" and "UdtTestDb" present in SQL Server, created using SQL scripts [createNorthwindDb.sql](tools/testsql/createNorthwindDb.sql) and [createUdtTestDb.sql](tools/testsql/createUdtTestDb.sql). To setup an Azure Database with "NORTHWIND" tables, use SQL Script: [createNorthwindAzureDb.sql](tools/testsql/createNorthwindAzureDb.sql).
+* Make a copy of the configuration file [config.default.json](src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json) and rename it to `config.json`. Update the values in `config.json`:
|Property|Description|Value|
|------|--------|-------------------|
@@ -179,40 +125,36 @@ Manual Tests require the below setup to run:
|IsAzureSynpase | (Optional) When set to 'true', test suite runs compatible tests for Azure Synapse/Parallel Data Warehouse. | `true` OR `false`|
|MakecertPath | The full path to makecert.exe. This is not required if the path is present in the PATH environment variable. | `D:\\escaped\\absolute\\path\\to\\makecert.exe` |
-### Commands to run Manual Tests
-
-- Windows (`netfx x86`):
+### Commands to run Manual Tests:
+ - Windows (`netfx x86`):
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" -p:Platform="Win32" -p:Configuration="Release" -p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests"
```
-- Windows (`netfx x64`):
-
+ - Windows (`netfx x64`):
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" -p:Platform="x64" -p:Configuration="Release" -p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests"
```
-- Windows (`netfx`):
+ - AnyCPU:
+ Windows (`netfx`):
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" -p:Platform="AnyCPU" -p:Configuration="Release" -p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests"
```
-- Windows (`netcoreapp`):
-
+ Windows (`netcoreapp`):
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" -p:Platform="AnyCPU" -p:Configuration="Release" -p:TestTargetOS="Windowsnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonwindowstests"
```
-- Unix (`netcoreapp`):
-
+ Unix (`netcoreapp`):
```bash
dotnet test "src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" -p:Platform="AnyCPU" -p:Configuration="Release" -p:TestTargetOS="Unixnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonlinuxtests&category!=nonuaptests"
```
## Run A Single Test
-
```bash
dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" -p:Platform="AnyCPU" -p:Configuration="Release" -p:TestTargetOS="Windowsnetcoreapp" --no-build -v n --filter "FullyQualifiedName=Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.CspProviderExt.TestKeysFromCertificatesCreatedWithMultipleCryptoProviders"
```
@@ -228,12 +170,11 @@ Tests can be built and run with custom "Reference Type" property that enables di
> ************** IMPORTANT NOTE BEFORE PROCEEDING WITH "PACKAGE" AND "NETSTANDARDPACKAGE" REFERENCE TYPES ***************
> CREATE A NUGET PACKAGE WITH BELOW COMMAND AND ADD TO LOCAL FOLDER + UPDATE NUGET CONFIG FILE TO READ FROM THAT LOCATION
->
-> ```bash
+> ```
> msbuild -p:configuration=Release
> ```
-### Building Tests with Reference Type
+### Building Tests:
For .NET Core, all 4 reference types are supported:
@@ -257,19 +198,18 @@ msbuild -t:BuildTestsNetFx -p:ReferenceType=Project
msbuild -t:BuildTestsNetFx -p:ReferenceType=Package
```
-### Running Tests with Reference Type
+### Running Tests:
Provide property to `dotnet test` commands for testing desired reference type.
-
-```bash
+```
dotnet test -p:ReferenceType=Project ...
```
-## Testing with Custom TargetFramework (traditional)
+## Testing with Custom TargetFramework
Tests can be built and run with custom Target Frameworks. See the below examples.
-### Building Tests with custom target framework
+### Building Tests:
```bash
msbuild -t:BuildTestsNetFx -p:TargetNetFxVersion=net462
@@ -283,7 +223,7 @@ msbuild -t:BuildTestsNetCore -p:TargetNetCoreVersion=netcoreapp3.1
# Applicable values: netcoreapp3.1 | net5.0 | net6.0
```
-### Running Tests with custom target framework (traditional)
+### Running Tests:
```bash
dotnet test -p:TargetNetFxVersion=net462 ...
@@ -299,31 +239,25 @@ dotnet test -p:TargetNetCoreVersion=netcoreapp3.1 ...
Managed SNI can be enabled on Windows by enabling the below AppContext switch:
-`Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows`
+**"Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows"**
## Set truncation on for scaled decimal parameters
Scaled decimal parameter truncation can be enabled by enabling the below AppContext switch:
-`Switch.Microsoft.Data.SqlClient.TruncateScaledDecimal`
+**"Switch.Microsoft.Data.SqlClient.TruncateScaledDecimal"**
## Enabling row version null behavior
`SqlDataReader` returns a `DBNull` value instead of an empty `byte[]`. To enable the legacy behavior, you must enable the following AppContext switch on application startup:
-`Switch.Microsoft.Data.SqlClient.LegacyRowVersionNullBehavior`
+**"Switch.Microsoft.Data.SqlClient.LegacyRowVersionNullBehavior"**
## Enabling OS secure protocols preference
TLS 1.3 has been excluded due to the fact that the driver lacks full support. To enable OS preferences as before, enable the following AppContext switch on application startup:
-`Switch.Microsoft.Data.SqlClient.EnableSecureProtocolsByOS`
-
-## Suppressing TLS security warning
-
-When connecting to a server, if a protocol lower than TLS 1.2 is negotiated, a security warning is output to the console. This warning can be suppressed on SQL connections with `Encrypt = false` by enabling the following AppContext switch on application startup:
-
-`Switch.Microsoft.Data.SqlClient.SuppressInsecureTLSWarning`
+**"Switch.Microsoft.Data.SqlClient.EnableSecureProtocolsByOS"**
## Debugging SqlClient on Linux from Windows
@@ -332,17 +266,14 @@ For enhanced developer experience, we support debugging SqlClient on Linux from
This project is also included in `docker-compose.yml` to demonstrate connectivity with SQL Server docker image.
To run the same:
-
1. Build the Solution in Visual Studio
2. Set `docker-compose` as Startup Project
3. Run "Docker-Compose" launch configuration.
4. You will see similar message in Debug window:
-
```log
Connected to SQL Server v15.00.4023 from Unix 4.19.76.0
The program 'dotnet' has exited with code 0 (0x0).
```
-
5. Now you can write code in [Program.cs](/src/Microsoft.Data.SqlClient/tests/DockerLinuxTest/Program.cs) to debug SqlClient on Linux!
### Troubleshooting Docker issues
@@ -352,7 +283,6 @@ There may be times where connection cannot be made to SQL Server, we found below
- Clear Docker images to create clean image from time-to-time, and clear docker cache if needed by running `docker system prune` in Command Prompt.
- If you face `Microsoft.Data.SqlClient.SNI.dll not found` errors when debugging, try updating the below properties in the netcore\Microsoft.Data.SqlClient.csproj file and try again:
-
```xml
Unixfalse
@@ -375,14 +305,13 @@ dotnet test --collect:"XPlat Code Coverage"
## Run Performance Tests
-### Running Performance test project directly
+### Running Performance test project directly:
Project location from Root: `src\Microsoft.Data.SqlClient\tests\PerformanceTests\Microsoft.Data.SqlClient.PerformanceTests.csproj`
Configure `runnerconfig.json` file with connection string and preferred settings to run Benchmark Jobs.
-```bash
+```
cd src\Microsoft.Data.SqlClient\tests\PerformanceTests
dotnet run -c Release -f netcoreapp3.1|net5.0
```
-
_Only "**Release** Configuration" applies to Performance Tests_
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f6bc177c49..900703d501 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,29 +3,6 @@
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
-## [Stable release 4.0.1] - 2022-01-17
-
-### Added
-
-Added AppContext switch `SuppressInsecureTLSWarning` to allow suppression of TLS security warning when using `Encrypt=false` in the connection string. [#1457](https://github.com/dotnet/SqlClient/pull/1457)
-
-### Fixed
-
-- Fixed Kerberos authentication failure when using .NET 6. [#1411](https://github.com/dotnet/SqlClient/pull/1411)
-- Fixed connection failure when using `SqlLocalDB` instance pipe name. [#1433](https://github.com/dotnet/SqlClient/pull/1433)
-- Fixed a failure when executing concurrent queries requiring enclaves. [#1451](https://github.com/dotnet/SqlClient/pull/1451)
-- Updated obsolete API calls targeting .NET 6. [#1401](https://github.com/dotnet/SqlClient/pull/1401)
-
-## [Stable Release 4.0.0] - 2021-11-18
-
-### Added
-
-- Added missing `SqlClientLogger` class to .NET Core refs and missing `SqlClientLogger.LogWarning` method in .NET Framework refs [#1392](https://github.com/dotnet/SqlClient/pull/1392)
-
-### Changed
-
-- Avoid throwing unnecessary exception when an invalid `SqlNotificationInfo` value is received from SQL Server [#1378](https://github.com/dotnet/SqlClient/pull/1378)
-- Updated `Microsoft.Data.SqlClient.SNI` (.NET Framework dependency) and `Microsoft.Data.SqlClient.SNI.runtime` (.NET Core/Standard dependency) version to `v4.0.0` [#1391](https://github.com/dotnet/SqlClient/pull/1391)
## [Preview Release 4.0.0-preview3.21293.2] - 2021-10-20
diff --git a/build.proj b/build.proj
index 2aa4ee019b..790ef246b4 100644
--- a/build.proj
+++ b/build.proj
@@ -16,17 +16,9 @@
falseWindowsUnix
- netcoreapp3.1
- netfx
- netcore
- netfx
- netcoreapp
- $(TF)
- $(TF)trueConfiguration=$(Configuration);AssemblyFileVersion=$(AssemblyFileVersion);TargetsWindows=$(TargetsWindows);TargetsUnix=$(TargetsUnix);
- BuildProjectReferences=false;$(ProjectProperties);BuildForRelease=false;TargetNetCoreVersion=$(TargetNetCoreVersion);TargetNetFxVersion=$(TargetNetFxVersion)
- TestResults
+ BuildProjectReferences=false;$(ProjectProperties);BuildForRelease=false;
@@ -49,7 +41,6 @@
-
@@ -61,33 +52,31 @@
-
-
-
-
+
+
-
-
+
+
-
+
-
-
-
+
+
+
@@ -123,30 +112,14 @@
-
+
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -180,10 +153,11 @@
-
+
+
diff --git a/doc/samples/AzureKeyVaultProviderExample.cs b/doc/samples/AzureKeyVaultProviderExample.cs
index e16a9a63a7..84c9ffb2da 100644
--- a/doc/samples/AzureKeyVaultProviderExample.cs
+++ b/doc/samples/AzureKeyVaultProviderExample.cs
@@ -130,8 +130,8 @@ WITH VALUES (
private static string GetEncryptedValue(SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider)
{
byte[] plainTextColumnEncryptionKey = new byte[32];
- RandomNumberGenerator rng = RandomNumberGenerator.Create();
- rng.GetBytes(plainTextColumnEncryptionKey);
+ RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
+ rngCsp.GetBytes(plainTextColumnEncryptionKey);
byte[] encryptedColumnEncryptionKey = sqlColumnEncryptionAzureKeyVaultProvider.EncryptColumnEncryptionKey(s_akvUrl, s_algorithm, plainTextColumnEncryptionKey);
string EncryptedValue = string.Concat("0x", BitConverter.ToString(encryptedColumnEncryptionKey).Replace("-", string.Empty));
diff --git a/doc/samples/AzureKeyVaultProviderExample_2_0.cs b/doc/samples/AzureKeyVaultProviderExample_2_0.cs
index d4c64f9684..f241966458 100644
--- a/doc/samples/AzureKeyVaultProviderExample_2_0.cs
+++ b/doc/samples/AzureKeyVaultProviderExample_2_0.cs
@@ -118,8 +118,8 @@ WITH VALUES (
private static string GetEncryptedValue(SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider)
{
byte[] plainTextColumnEncryptionKey = new byte[32];
- RandomNumberGenerator rng = RandomNumberGenerator.Create();
- rng.GetBytes(plainTextColumnEncryptionKey);
+ RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
+ rngCsp.GetBytes(plainTextColumnEncryptionKey);
byte[] encryptedColumnEncryptionKey = sqlColumnEncryptionAzureKeyVaultProvider.EncryptColumnEncryptionKey(s_akvUrl, s_algorithm, plainTextColumnEncryptionKey);
string EncryptedValue = string.Concat("0x", BitConverter.ToString(encryptedColumnEncryptionKey).Replace("-", string.Empty));
diff --git a/doc/samples/AzureKeyVaultProviderLegacyExample_2_0.cs b/doc/samples/AzureKeyVaultProviderLegacyExample_2_0.cs
index d691455f06..e55e1f18c7 100644
--- a/doc/samples/AzureKeyVaultProviderLegacyExample_2_0.cs
+++ b/doc/samples/AzureKeyVaultProviderLegacyExample_2_0.cs
@@ -116,8 +116,8 @@ WITH VALUES (
private static string GetEncryptedValue(SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider)
{
byte[] plainTextColumnEncryptionKey = new byte[32];
- RandomNumberGenerator rng = RandomNumberGenerator.Create();
- rng.GetBytes(plainTextColumnEncryptionKey);
+ RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
+ rngCsp.GetBytes(plainTextColumnEncryptionKey);
byte[] encryptedColumnEncryptionKey = sqlColumnEncryptionAzureKeyVaultProvider.EncryptColumnEncryptionKey(s_akvUrl, s_algorithm, plainTextColumnEncryptionKey);
string EncryptedValue = string.Concat("0x", BitConverter.ToString(encryptedColumnEncryptionKey).Replace("-", string.Empty));
diff --git a/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample.cs b/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample.cs
index 2091dab322..628a2e663b 100644
--- a/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample.cs
+++ b/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample.cs
@@ -136,8 +136,8 @@ WITH VALUES (
private static string GetEncryptedValue(SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider)
{
byte[] plainTextColumnEncryptionKey = new byte[32];
- RandomNumberGenerator rng = RandomNumberGenerator.Create();
- rng.GetBytes(plainTextColumnEncryptionKey);
+ RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
+ rngCsp.GetBytes(plainTextColumnEncryptionKey);
byte[] encryptedColumnEncryptionKey = sqlColumnEncryptionAzureKeyVaultProvider.EncryptColumnEncryptionKey(s_akvUrl, s_algorithm, plainTextColumnEncryptionKey);
string EncryptedValue = string.Concat("0x", BitConverter.ToString(encryptedColumnEncryptionKey).Replace("-", string.Empty));
diff --git a/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample_2_0.cs b/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample_2_0.cs
index 27f97dac38..4328be2958 100644
--- a/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample_2_0.cs
+++ b/doc/samples/AzureKeyVaultProviderWithEnclaveProviderExample_2_0.cs
@@ -123,8 +123,8 @@ WITH VALUES (
private static string GetEncryptedValue(SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider)
{
byte[] plainTextColumnEncryptionKey = new byte[32];
- RandomNumberGenerator rng = RandomNumberGenerator.Create();
- rng.GetBytes(plainTextColumnEncryptionKey);
+ RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
+ rngCsp.GetBytes(plainTextColumnEncryptionKey);
byte[] encryptedColumnEncryptionKey = sqlColumnEncryptionAzureKeyVaultProvider.EncryptColumnEncryptionKey(s_akvUrl, s_algorithm, plainTextColumnEncryptionKey);
string EncryptedValue = string.Concat("0x", BitConverter.ToString(encryptedColumnEncryptionKey).Replace("-", string.Empty));
diff --git a/doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml b/doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml
index 5a69be7478..081e22dcd6 100644
--- a/doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml
+++ b/doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml
@@ -95,16 +95,13 @@ The following example demonstrates providing a custom device flow callback to Sq
are:
+ The supported authentication modes with are:
- Active Directory Password
- Active Directory Integrated
- Active Directory Interactive
- Active Directory Service Principal
- Active Directory Device Code Flow
-- Active Directory Managed Identity
-- Active Directory MSI
-- Active Directory Default
]]>
diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml
index 44a5fbab63..4388f98172 100644
--- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml
+++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopy.xml
@@ -8,11 +8,11 @@
class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but offers a significant performance advantage over them. The class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. will fail when bulk loading a column of type into a SQL Server column whose type is one of the date/time types added in SQL Server 2008.
+Microsoft SQL Server includes a popular command-prompt utility named **bcp** for moving data from one table to another, whether on a single server or between servers. The class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but offers a significant performance advantage over them. The class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. will fail when bulk loading a column of type into a SQL Server column whose type is one of the date/time types added in SQL Server 2008.
## Examples
-The following console application demonstrates how to load data using the class.
-In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database.
+The following console application demonstrates how to load data using the class.
+In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml
index 5b360dfb97..d0cebe8712 100644
--- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml
+++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml
@@ -177,7 +177,7 @@ Modified: Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security
@@ -408,17 +408,14 @@ If the value of the **Network** key is specified, the prefixes "tcp:" and "np:"
Gets or sets a Boolean value that indicates whether SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed.
- The value of the property, or if none has been supplied.
+ The value of the property, or if none has been supplied. [!NOTE]
-> Starting from **version 4.0**, the default value of the property `Encrypt` is set to `true`.
+When `TrustServerCertificate` is false and `Encrypt` is true, the server name (or IP address) in a SQL Server SSL certificate must exactly match the server name (or IP address) specified in the connection string. Otherwise, the connection attempt will fail. For information about support for certificates whose subject starts with a wildcard character (*), see [Enable encrypted connections to the Database Engine](sql/database-engine/configure-windows/enable-encrypted-connections-to-the-database-engine#certificate-requirements).|
]]>
diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlDataReader.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlDataReader.xml
index 8a789962d3..3d1ad11722 100644
--- a/doc/snippets/Microsoft.Data.SqlClient/SqlDataReader.xml
+++ b/doc/snippets/Microsoft.Data.SqlClient/SqlDataReader.xml
@@ -532,7 +532,7 @@
method returns the following metadata about each column:
+ For the method returns metadata about each column in the following order:
|DataReader column|Description|
|-----------------------|-----------------|
diff --git a/release-notes/4.0/4.0.0.md b/release-notes/4.0/4.0.0.md
deleted file mode 100644
index 6059c27983..0000000000
--- a/release-notes/4.0/4.0.0.md
+++ /dev/null
@@ -1,196 +0,0 @@
-# Release Notes
-
-## Microsoft.Data.SqlClient 4.0.0 released 18 November 2021
-
-This update brings the below changes over the previous preview release:
-
-### Added
-
-- Added missing `SqlClientLogger` class to .NET Core refs and missing `SqlClientLogger.LogWarning` method in .NET Framework refs [#1392](https://github.com/dotnet/SqlClient/pull/1392)
-
-### Changed
-
-- Avoid throwing unnecessary exception when an invalid `SqlNotificationInfo` value is received from SQL Server [#1378](https://github.com/dotnet/SqlClient/pull/1378)
-- Updated `Microsoft.Data.SqlClient.SNI` (.NET Framework dependency) and `Microsoft.Data.SqlClient.SNI.runtime` (.NET Core/Standard dependency) version to `v4.0.0` [#1391](https://github.com/dotnet/SqlClient/pull/1391)
-
-## Summary of changes in 4.0
-
-All changes in Microsoft.Data.SqlClient v4.0 over v3.0:
-
-### New Additions
-
-- Added `SqlCommand.EnableOptimizedParameterBinding` property that when enabled increases performance for commands with very large numbers of parameters. [#1041](https://github.com/dotnet/SqlClient/pull/1041) [Read more](#enable-optimized-parameter-binding)
-- Included `42108` and `42109` error codes to retriable transient errors list. [#1215](https://github.com/dotnet/SqlClient/pull/1215)
-- Added new App Context switch to use OS enabled client protocols only. [#1168](https://github.com/dotnet/SqlClient/pull/1168). [Read more](#app-context-switch-for-using-system-default-protocols)
-- Added `PoolBlockingPeriod` connection property support in .NET Standard. [#1181](https://github.com/dotnet/SqlClient/pull/1181)
-- Added support for `SqlDataReader.GetColumnSchema()` in .NET Standard. [#1181](https://github.com/dotnet/SqlClient/pull/1181)
-- Added PropertyGrid support with component model annotations to `SqlConnectionStringBuilder` properties for .NET Core. [#1152](https://github.com/dotnet/SqlClient/pull/1152)
-- Added support for `SqlFileStream` on Windows using .NET Standard 2.0 and above. [#1240](https://github.com/dotnet/SqlClient/pull/1240)
-- Added support for **localdb** `shared instance` using managed SNI. [#1237](https://github.com/dotnet/SqlClient/pull/1237). [Read more](#sqllocaldb-shared-instance-support)
-- Added `GetFieldValueAsync` and `GetFieldValue` support for `XmlReader`, `TextReader`, `Stream` [#1019](https://github.com/dotnet/SqlClient/pull/1019). [Read more](#getfieldvalueasynct-and-getfieldvaluet-support-for-xmlreader-textreader-stream-types)
-- Added missing `SqlClientLogger` class to .NET Core refs and missing 'SqlClientLogger.LogWarning' method in .NET Framework refs [#1392](https://github.com/dotnet/SqlClient/pull/1392)
-
-### Bug Fixes
-
-- Fixed issue with connectivity when TLS 1.3 is enabled on client and server. [#1168](https://github.com/dotnet/SqlClient/pull/1168)
-- Fixed issue with connection encryption to ensure connections fail when encryption is required. [#1210](https://github.com/dotnet/SqlClient/pull/1210) [Read more](#ensure-connections-fail-when-encryption-is-required)
-- Fixed issue where connection goes to unusable state. [#1128](https://github.com/dotnet/SqlClient/pull/1128)
-- Fixed recursive calls to `RetryLogicProvider` when calling `SqlCommand.ExecuteScalarAsync`. [#1220](https://github.com/dotnet/SqlClient/pull/1220)
-- Fixed async deadlock scenarios in web contexts with configurable retry logic provider. [#1220](https://github.com/dotnet/SqlClient/pull/1220)
-- Fixed `EntryPointNotFoundException` in `InOutOfProcHelper` constructor. [#1120](https://github.com/dotnet/SqlClient/pull/1120)
-- Fixed async thread blocking issues on `SqlConnection.Open()` for active directory authentication modes. [#1213](https://github.com/dotnet/SqlClient/pull/1213)
-- Fixed driver behavior for Always Encrypted with secure enclaves to not fail when no user parameters have been provided. [#1115](https://github.com/dotnet/SqlClient/pull/1115)
-- Fixed bug with `LegacyRowVersionNullBehavior` App Context switch. [#1182](https://github.com/dotnet/SqlClient/pull/1182)
-- Fixed issues in Strings.resx file containing error messages. [#1136](https://github.com/dotnet/SqlClient/pull/1136) [#1178](https://github.com/dotnet/SqlClient/pull/1178)
-- Fixed `.NET decimal` conversion from `SqlDecimal`. [#1179](https://github.com/dotnet/SqlClient/pull/1179)
-- Fixed `Event Source` changes on **TryBeginExecuteEvent** and **WriteEndExecuteEvent** to address the failure on other MS products such as OpenTelemetry and Application Insight. [#1258](https://github.com/dotnet/SqlClient/pull/1258)
-- Fixed deadlock in transaction using .NET Framework. [#1242](https://github.com/dotnet/SqlClient/pull/1242)
-- Fixed unknown transaction state issues when prompting delegated transaction. [1216](https://github.com/dotnet/SqlClient/pull/1216)
-- Fixed `FormatException` when opening a connection with event tracing enabled [#1291](https://github.com/dotnet/SqlClient/pull/1291)
-- Fixed improper initialization of `ActiveDirectoryAuthenticationProvider` [#1328](https://github.com/dotnet/SqlClient/pull/1328)
-- Fixed `MissingMethodException` when accessing `SqlAuthenticationParameters.ConnectionTimeout` [#1336](https://github.com/dotnet/SqlClient/pull/1336)
-- Fixed bug where environment variables are ignored when using `Active Directory Default` authentication [#1360](https://github.com/dotnet/SqlClient/pull/1360)
-
-### Improvements and Changes
-
-- Updated error code to match with Windows when certificate validation fails in non-Windows client environments. [#1130](https://github.com/dotnet/SqlClient/pull/1130)
-- Removed designer attributes from `SqlCommand` and `SqlDataAdapter`. [#1132](https://github.com/dotnet/SqlClient/pull/1132)
-- Updated configurable retry logic default retriable error list. [#1125](https://github.com/dotnet/SqlClient/pull/1125)
-- Improved performance by changing `SqlParameter` bool fields to flags. [#1064](https://github.com/dotnet/SqlClient/pull/1064)
-- Improved performance by implementing static delegates. [#1060](https://github.com/dotnet/SqlClient/pull/1060)
-- Optimized async method allocations in .NET Framework by porting changes from .NET Core. [#1084](https://github.com/dotnet/SqlClient/pull/1084)
-- Various code improvements [#902](https://github.com/dotnet/SqlClient/pull/902) [#925](https://github.com/dotnet/SqlClient/pull/925) [#933](https://github.com/dotnet/SqlClient/pull/933) [#934](https://github.com/dotnet/SqlClient/pull/934) [#1024](https://github.com/dotnet/SqlClient/pull/1024) [#1057](https://github.com/dotnet/SqlClient/pull/1057) [#1122](https://github.com/dotnet/SqlClient/pull/1122) [#1133](https://github.com/dotnet/SqlClient/pull/1133) [#1134](https://github.com/dotnet/SqlClient/pull/1134) [#1141](https://github.com/dotnet/SqlClient/pull/1141) [#1155](https://github.com/dotnet/SqlClient/pull/1155) [#1187](https://github.com/dotnet/SqlClient/pull/1187) [#1188](https://github.com/dotnet/SqlClient/pull/1188) [#1223](https://github.com/dotnet/SqlClient/pull/1223) [#1225](https://github.com/dotnet/SqlClient/pull/1225) [#1226](https://github.com/dotnet/SqlClient/pull/1226) [#1236](https://github.com/dotnet/SqlClient/pull/1236) [#1251](https://github.com/dotnet/SqlClient/pull/1251) [#1266](https://github.com/dotnet/SqlClient/pull/1266)
-- Removed attributes for classes used in Microsoft.VSDesigner due to lack of support for Microsoft.Data.SqlClient [#1296](https://github.com/dotnet/SqlClient/pull/1296)
-- Disable encryption when connecting to SQL LocalDB [#1312](https://github.com/dotnet/SqlClient/pull/1312)
-- Avoid throwing unnecessary exception when an invalid SqlNotificationInfo value is received from SQL Server [#1378](https://github.com/dotnet/SqlClient/pull/1378)
-- Updated `Microsoft.Data.SqlClient.SNI` (.NET Framework dependency) and `Microsoft.Data.SqlClient.SNI.runtime` (.NET Core/Standard dependency) version to `v4.0.0` [#1391](https://github.com/dotnet/SqlClient/pull/1391)
-- Various code health and performance improvements. See [milestone](https://github.com/dotnet/SqlClient/milestone/31?closed=1) for more info.
-
-### Breaking Changes
-- Changed `Encrypt` connection string property to be `true` by default. [#1210](https://github.com/dotnet/SqlClient/pull/1210) [Read more](#encrypt-default-value-set-to-true)
-- The driver now throws `SqlException` replacing `AggregateException` for active directory authentication modes. [#1213](https://github.com/dotnet/SqlClient/pull/1213)
-- Dropped obsolete `Asynchronous Processing` connection property from .NET Framework. [#1148](https://github.com/dotnet/SqlClient/pull/1148)
-- Removed `Configurable Retry Logic` safety switch. [#1254](https://github.com/dotnet/SqlClient/pull/1254) [Read more](#remove-configurable-retry-logic-safety-switch)
-- Dropped support for .NET Core 2.1 [#1272](https://github.com/dotnet/SqlClient/pull/1272)
-- [.NET Framework] Exception will not be thrown if a User ID is provided in the connection string when using `Active Directory Integrated` authentication [#1359](https://github.com/dotnet/SqlClient/pull/1359)
-
-### Encrypt default value set to true
-The default value of the `Encrypt` connection setting has been changed from `false` to `true`. With the growing use of cloud databases and the need to ensure those connections are secure, it's time for this backwards-compatibility-breaking change.
-
-### Ensure connections fail when encryption is required
-In scenarios where client encryption libraries were disabled or unavailable, it was possible for unencrypted connections to be made when Encrypt was set to true or the server required encryption.
-
-### App Context Switch for using System default protocols
-TLS 1.3 is not supported by the driver; therefore, it has been removed from the supported protocols list by default. Users can switch back to forcing use of the Operating System's client protocols, by enabling the App Context switch below:
-
- `Switch.Microsoft.Data.SqlClient.UseSystemDefaultSecureProtocols`
-
-### Enable optimized parameter binding
-Microsoft.Data.SqlClient introduces a new `SqlCommand` API, `EnableOptimizedParameterBinding` to improve performance of queries with a large number of parameters. This property is disabled by default. When set to `true`, parameter names will not be sent to the SQL server when the command is executed.
-
-```cs
-public class SqlCommand
-{
- public bool EnableOptimizedParameterBinding { get; set; }
-}
-```
-
-### Remove configurable retry logic safety switch
-
-The App Context switch "Switch.Microsoft.Data.SqlClient.EnableRetryLogic" will no longer be required to use the configurable retry logic feature. The feature is now supported in production. The default behavior of the feature will continue to be a non-retry policy, which will need to be overridden by client applications to enable retries.
-
-### SqlLocalDb shared instance support
-
-SqlLocalDb shared instances are now supported when using Managed SNI.
-
-- Possible scenarios:
- - `(localdb)\.` (connects to default instance of SqlLocalDb)
- - `(localdb)\`
- - `(localdb)\.\` (*newly added support)
-
-### `GetFieldValueAsync` and `GetFieldValue` support for `XmlReader`, `TextReader`, `Stream` types
-
-`XmlReader`, `TextReader`, `Stream` types are now supported when using `GetFieldValueAsync` and `GetFieldValue`.
-
-Example usage:
-
-```cs
-using (SqlConnection connection = new SqlConnection(connectionString))
-{
- using (SqlCommand command = new SqlCommand(query, connection))
- {
- connection.Open();
- using (SqlDataReader reader = await command.ExecuteReaderAsync())
- {
- if (await reader.ReadAsync())
- {
- using (Stream stream = await reader.GetFieldValueAsync(1))
- {
- // Continue to read from stream
- }
- }
- }
- }
-}
-```
-
-## Target Platform Support
-
-- .NET Framework 4.6.1+ (Windows x86, Windows x64)
-- .NET Core 3.1+ (Windows x86, Windows x64, Windows ARM64, Windows ARM, Linux, macOS)
-- .NET Standard 2.0+ (Windows x86, Windows x64, Windows ARM64, Windows ARM, Linux, macOS)
-
-### Dependencies
-
-#### .NET Framework
-
-- Microsoft.Data.SqlClient.SNI 4.0.0
-- Azure.Identity 1.3.0
-- Microsoft.Identity.Client 4.22.0
-- Microsoft.IdentityModel.JsonWebTokens 6.8.0
-- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0
-- System.Buffers 4.5.1
-- System.Configuration.ConfigurationManager 5.0.0
-- System.IO 4.3.0
-- System.Runtime.InteropServices.RuntimeInformation 4.3.0
-- System.Security.Cryptography.Algorithms 4.3.1
-- System.Security.Cryptography.Primitives 4.3.0
-- System.Text.Encodings.Web 4.7.2
-
-#### .NET Core
-
-- Microsoft.Data.SqlClient.SNI.runtime 4.0.0
-- Azure.Identity 1.3.0
-- Microsoft.Identity.Client 4.22.0
-- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0
-- Microsoft.IdentityModel.JsonWebTokens 6.8.0
-- Microsoft.Win32.Registry 5.0.0
-- System.Buffers 4.5.1
-- System.Configuration.ConfigurationManager 5.0.0
-- System.Diagnostics.DiagnosticSource 5.0.0
-- System.IO 4.3.0
-- System.Runtime.Caching 5.0.0
-- System.Text.Encoding.CodePages 5.0.0
-- System.Text.Encodings.Web 4.7.2
-- System.Resources.ResourceManager 4.3.0
-- System.Security.Cryptography.Cng 5.0.0
-- System.Security.Principal.Windows 5.0.0
-
-#### .NET Standard
-
-- Microsoft.Data.SqlClient.SNI.runtime 4.0.0
-- Azure.Identity 1.3.0
-- Microsoft.Identity.Client 4.22.0
-- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0
-- Microsoft.IdentityModel.JsonWebTokens 6.8.0
-- Microsoft.Win32.Registry 5.0.0
-- System.Buffers 4.5.1
-- System.Configuration.ConfigurationManager 5.0.0
-- System.IO 4.3.0
-- System.Runtime.Caching 5.0.0
-- System.Text.Encoding.CodePages 5.0.0
-- System.Text.Encodings.Web 4.7.2
-- System.Resources.ResourceManager 4.3.0
-- System.Runtime.Loader 4.3.0
-- System.Security.Cryptography.Cng 5.0.0
-- System.Security.Principal.Windows 5.0.0
diff --git a/release-notes/4.0/4.0.1.md b/release-notes/4.0/4.0.1.md
deleted file mode 100644
index 7e43a9bcc8..0000000000
--- a/release-notes/4.0/4.0.1.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# Release Notes
-
-## Microsoft.Data.SqlClient 4.0.1 released 17 January 2022
-
-This update brings the below changes over the previous preview release:
-
-### Added
-
-- Added AppContext switch `SuppressInsecureTLSWarning` to allow suppression of TLS security warning when using `Encrypt=false` in the connection string. [#1457](https://github.com/dotnet/SqlClient/pull/1457) [Read more](#suppress-tls-security-warnings)
-
-### Fixed
-
-- Fixed Kerberos authentication failure when using .NET 6. [#1411](https://github.com/dotnet/SqlClient/pull/1411)
-- Fixed connection failure when using `SqlLocalDB` instance pipe name. [#1433](https://github.com/dotnet/SqlClient/pull/1433)
-- Fixed a failure when executing concurrent queries requiring enclaves. [#1451](https://github.com/dotnet/SqlClient/pull/1451)
-- Updated obsolete API calls targeting .NET 6. [#1401](https://github.com/dotnet/SqlClient/pull/1401)
-
-### Suppress TLS security warnings
-
-When connecting to a SQL Server, if a protocol lower than TLS 1.2 is negotiated, a security warning is printed out to the console. This warning can be suppressed by enabling the following `AppContext` switch on the application startup while `Encrypt` is set to `false` on connection string.
-
-`Switch.Microsoft.Data.SqlClient.SuppressInsecureTLSWarning`
-
-## Target Platform Support
-
-- .NET Framework 4.6.1+ (Windows x86, Windows x64)
-- .NET Core 3.1+ (Windows x86, Windows x64, Windows ARM64, Windows ARM, Linux, macOS)
-- .NET Standard 2.0+ (Windows x86, Windows x64, Windows ARM64, Windows ARM, Linux, macOS)
-
-### Dependencies
-
-#### .NET Framework
-
-- Microsoft.Data.SqlClient.SNI 4.0.0
-- Azure.Identity 1.3.0
-- Microsoft.Identity.Client 4.22.0
-- Microsoft.IdentityModel.JsonWebTokens 6.8.0
-- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0
-- System.Buffers 4.5.1
-- System.Configuration.ConfigurationManager 5.0.0
-- System.IO 4.3.0
-- System.Runtime.InteropServices.RuntimeInformation 4.3.0
-- System.Security.Cryptography.Algorithms 4.3.1
-- System.Security.Cryptography.Primitives 4.3.0
-- System.Text.Encodings.Web 4.7.2
-
-#### .NET Core
-
-- Microsoft.Data.SqlClient.SNI.runtime 4.0.0
-- Azure.Identity 1.3.0
-- Microsoft.Identity.Client 4.22.0
-- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0
-- Microsoft.IdentityModel.JsonWebTokens 6.8.0
-- Microsoft.Win32.Registry 5.0.0
-- System.Buffers 4.5.1
-- System.Configuration.ConfigurationManager 5.0.0
-- System.Diagnostics.DiagnosticSource 5.0.0
-- System.IO 4.3.0
-- System.Runtime.Caching 5.0.0
-- System.Text.Encoding.CodePages 5.0.0
-- System.Text.Encodings.Web 4.7.2
-- System.Resources.ResourceManager 4.3.0
-- System.Security.Cryptography.Cng 5.0.0
-- System.Security.Principal.Windows 5.0.0
-
-#### .NET Standard
-
-- Microsoft.Data.SqlClient.SNI.runtime 4.0.0
-- Azure.Identity 1.3.0
-- Microsoft.Identity.Client 4.22.0
-- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0
-- Microsoft.IdentityModel.JsonWebTokens 6.8.0
-- Microsoft.Win32.Registry 5.0.0
-- System.Buffers 4.5.1
-- System.Configuration.ConfigurationManager 5.0.0
-- System.IO 4.3.0
-- System.Runtime.Caching 5.0.0
-- System.Text.Encoding.CodePages 5.0.0
-- System.Text.Encodings.Web 4.7.2
-- System.Resources.ResourceManager 4.3.0
-- System.Runtime.Loader 4.3.0
-- System.Security.Cryptography.Cng 5.0.0
-- System.Security.Principal.Windows 5.0.0
\ No newline at end of file
diff --git a/release-notes/4.0/4.0.md b/release-notes/4.0/4.0.md
index c6a93a0724..d9f8ceac96 100644
--- a/release-notes/4.0/4.0.md
+++ b/release-notes/4.0/4.0.md
@@ -1,12 +1,5 @@
# Microsoft.Data.SqlClient 4.0 Releases
-The following Microsoft.Data.SqlClient 4.0 stable releases have been shipped:
-
-| Release Date | Version | Notes |
-| :-- | :-- | :--: |
-| 2022/01/17 | 4.0.1 | [release notes](4.0.1.md) |
-| 2021/11/18 | 4.0.0 | [release notes](4.0.0.md) |
-
The following Microsoft.Data.SqlClient 4.0 preview releases have been shipped:
| Release Date | Version | Notes |
diff --git a/release-notes/4.0/README.md b/release-notes/4.0/README.md
index c6a93a0724..d9f8ceac96 100644
--- a/release-notes/4.0/README.md
+++ b/release-notes/4.0/README.md
@@ -1,12 +1,5 @@
# Microsoft.Data.SqlClient 4.0 Releases
-The following Microsoft.Data.SqlClient 4.0 stable releases have been shipped:
-
-| Release Date | Version | Notes |
-| :-- | :-- | :--: |
-| 2022/01/17 | 4.0.1 | [release notes](4.0.1.md) |
-| 2021/11/18 | 4.0.0 | [release notes](4.0.0.md) |
-
The following Microsoft.Data.SqlClient 4.0 preview releases have been shipped:
| Release Date | Version | Notes |
diff --git a/release-notes/README.md b/release-notes/README.md
index ae992b42c4..4340d7838e 100644
--- a/release-notes/README.md
+++ b/release-notes/README.md
@@ -1,6 +1,6 @@
# Microsoft.Data.SqlClient Release Notes
-The latest stable release is [Microsoft.Data.SqlClient 4.0](4.0).
+The latest stable release is [Microsoft.Data.SqlClient 3.0](3.0).
## Release Information
diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs
index 22cbb29f6e..97c1347b10 100644
--- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs
@@ -414,22 +414,6 @@ internal SqlClientFactory() { }
///
public override System.Data.Common.DbParameter CreateParameter() { throw null; }
}
- ///
- public partial class SqlClientLogger
- {
- ///
- public SqlClientLogger() { }
- ///
- public bool IsLoggingEnabled { get { throw null; } }
- ///
- public void LogWarning(string type, string method, string message) { }
- ///
- public bool LogAssert(bool value, string type, string method, string message) { throw null; }
- ///
- public void LogError(string type, string method, string message) { }
- ///
- public void LogInfo(string type, string method, string message) { }
- }
///
public static partial class SqlClientMetaDataCollectionNames
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/.editorconfig b/src/Microsoft.Data.SqlClient/netcore/src/.editorconfig
deleted file mode 100644
index ecc808aa66..0000000000
--- a/src/Microsoft.Data.SqlClient/netcore/src/.editorconfig
+++ /dev/null
@@ -1,12 +0,0 @@
-# editorconfig.org
-
-# top-most EditorConfig file
-root = false
-
-[*.cs]
-
-# IDE0090: Use 'new(...)'
-csharp_style_implicit_object_creation_when_type_is_apparent = false
-
-# IDE0063: Use simple 'using' statement
-csharp_prefer_simple_using_statement = false
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs
index 489d1cf8a9..ab8338e796 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs
@@ -11,52 +11,49 @@ internal static partial class Interop
{
internal static partial class NetSecurityNative
{
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_ReleaseGssBuffer")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseGssBuffer")]
internal static extern void ReleaseGssBuffer(
IntPtr bufferPtr,
ulong length);
- [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_EnsureGssInitialized")]
- private static extern int EnsureGssInitialized();
-
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_DisplayMinorStatus")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DisplayMinorStatus")]
internal static extern Status DisplayMinorStatus(
out Status minorStatus,
Status statusValue,
ref GssBuffer buffer);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_DisplayMajorStatus")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DisplayMajorStatus")]
internal static extern Status DisplayMajorStatus(
out Status minorStatus,
Status statusValue,
ref GssBuffer buffer);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_ImportUserName")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ImportUserName")]
internal static extern Status ImportUserName(
out Status minorStatus,
string inputName,
int inputNameByteCount,
out SafeGssNameHandle outputName);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_ImportPrincipalName")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ImportPrincipalName")]
internal static extern Status ImportPrincipalName(
out Status minorStatus,
string inputName,
int inputNameByteCount,
out SafeGssNameHandle outputName);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_ReleaseName")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseName")]
internal static extern Status ReleaseName(
out Status minorStatus,
ref IntPtr inputName);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_InitiateCredSpNego")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitiateCredSpNego")]
internal static extern Status InitiateCredSpNego(
out Status minorStatus,
SafeGssNameHandle desiredName,
out SafeGssCredHandle outputCredHandle);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_InitiateCredWithPassword")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitiateCredWithPassword")]
internal static extern Status InitiateCredWithPassword(
out Status minorStatus,
bool isNtlm,
@@ -65,12 +62,12 @@ internal static extern Status InitiateCredWithPassword(
int passwordLen,
out SafeGssCredHandle outputCredHandle);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_ReleaseCred")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseCred")]
internal static extern Status ReleaseCred(
out Status minorStatus,
ref IntPtr credHandle);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_InitSecContext")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitSecContext")]
internal static extern Status InitSecContext(
out Status minorStatus,
SafeGssCredHandle initiatorCredHandle,
@@ -84,7 +81,7 @@ internal static extern Status InitSecContext(
out uint retFlags,
out int isNtlmUsed);
- [DllImport(Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_DeleteSecContext")]
+ [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DeleteSecContext")]
internal static extern Status DeleteSecContext(
out Status minorStatus,
ref IntPtr contextHandle);
@@ -112,17 +109,5 @@ internal enum GssFlags : uint
GSS_C_EXTENDED_ERROR_FLAG = 0x4000,
GSS_C_DELEG_POLICY_FLAG = 0x8000
}
-
- // This constructor is added to address the issue with net6 regarding
- // Shim gss api on Linux to delay loading libgssapi_krb5.so
- // issue https://github.com/dotnet/SqlClient/issues/1390
- // dotnet runtime issue https://github.com/dotnet/runtime/pull/55037
- static NetSecurityNative()
- {
- if (Environment.Version.Major >= 6)
- {
- EnsureGssInitialized();
- }
- }
}
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj
index e1483a26a8..3bf596e22c 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj
@@ -283,9 +283,6 @@
Microsoft\Data\SqlClient\SqlEnums.cs
-
- Microsoft\Data\SqlClient\SqlError.cs
-
Microsoft\Data\SqlClient\SqlErrorCollection.cs
@@ -367,12 +364,12 @@
Microsoft\Data\SqlClient\Server\ValueUtilsSmi.cs
-
- Microsoft\Data\SqlClient\Server\SqlSer.cs
-
Microsoft\Data\SqlClient\SignatureVerificationCache.cs
+
+ Microsoft\Data\SqlClient\TdsEnums.cs
+
Microsoft\Data\SqlClient\TdsValueSetter.cs
@@ -494,9 +491,6 @@
Microsoft\Data\SqlClient\VirtualSecureModeEnclaveProvider.cs
-
- Microsoft\Data\SqlClient\NoneAttestationEnclaveProvider.cs
-
Microsoft\Data\SqlClient\VirtualSecureModeEnclaveProviderBase.cs
@@ -516,6 +510,9 @@
+
+
+
Resources\StringsHelper.NetCore.cs
@@ -565,6 +562,7 @@
+
@@ -581,6 +579,7 @@
+
Microsoft\Data\SqlClient\SqlEnclaveSession.cs
@@ -598,7 +597,6 @@
Microsoft\Data\SqlClient\SqlUdtInfo.cs
-
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs
index 1b4679bfe4..6ec654e3bf 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs
@@ -22,13 +22,14 @@ private static IntPtr UserInstanceDLLHandle
if (s_userInstanceDLLHandle == IntPtr.Zero)
{
SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle);
- if (s_userInstanceDLLHandle != IntPtr.Zero)
+ if(s_userInstanceDLLHandle != IntPtr.Zero)
{
SqlClientEventSource.Log.TryTraceEvent("LocalDBAPI.UserInstanceDLLHandle | LocalDB - handle obtained");
}
else
{
- SNINativeMethodWrapper.SNIGetLastError(out SNINativeMethodWrapper.SNI_Error sniError);
+ SNINativeMethodWrapper.SNI_Error sniError;
+ SNINativeMethodWrapper.SNIGetLastError(out sniError);
throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_FailedGetDLLHandle"), sniError: (int)sniError.sniError);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
index ba2371c232..4f3fd13dce 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
@@ -10,37 +10,25 @@ namespace Microsoft.Data
{
internal static partial class LocalDBAPI
{
- private const string LocalDbPrefix = @"(localdb)\";
- private const string LocalDbPrefix_NP = @"np:\\.\pipe\LOCALDB#";
+ 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)\ and return instance name if it is
- // localDB can also have a format of np:\\.\pipe\LOCALDB#\tsql\query
internal static string GetLocalDbInstanceNameFromServerName(string serverName)
{
- if (serverName is not null)
- {
- // it can start with spaces if specified in quotes
- // Memory allocation is reduced by using ReadOnlySpan
- ReadOnlySpan input = serverName.AsSpan().Trim();
- if (input.StartsWith(LocalDbPrefix.AsSpan(), StringComparison.OrdinalIgnoreCase))
- {
- input = input.Slice(LocalDbPrefix.Length);
- if (!input.IsEmpty)
- {
- return input.ToString();
- }
- }
- else if (input.StartsWith(LocalDbPrefix_NP.AsSpan(), StringComparison.OrdinalIgnoreCase))
- {
- return input.ToString();
- }
-
- }
- return null;
+ 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/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs
index 501a68e401..0af8441333 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs
@@ -342,7 +342,8 @@ internal SNIError GetLastError()
private static string GetLocalDBDataSource(string fullServerName, out bool error)
{
string localDBConnectionString = null;
- string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out bool isBadLocalDBDataSource);
+ bool isBadLocalDBDataSource;
+ string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out isBadLocalDBDataSource);
if (isBadLocalDBDataSource)
{
@@ -380,7 +381,6 @@ internal class DataSource
private const string Slash = @"/";
private const string PipeToken = "pipe";
private const string LocalDbHost = "(localdb)";
- private const string LocalDbHost_NP = @"np:\\.\pipe\LOCALDB#";
private const string NamedPipeInstanceNameHeader = "mssql$";
private const string DefaultPipeName = "sql\\query";
@@ -482,9 +482,11 @@ private void PopulateProtocol()
internal static string GetLocalDBInstance(string dataSource, out bool error)
{
string instanceName = null;
+
// ReadOnlySpan is not supported in netstandard 2.0, but installing System.Memory solves the issue
ReadOnlySpan input = dataSource.AsSpan().TrimStart();
error = false;
+
// NetStandard 2.0 does not support passing a string to ReadOnlySpan
if (input.StartsWith(LocalDbHost.AsSpan().Trim(), StringComparison.InvariantCultureIgnoreCase))
{
@@ -505,11 +507,6 @@ internal static string GetLocalDBInstance(string dataSource, out bool error)
error = true;
}
}
- else if (input.StartsWith(LocalDbHost_NP.AsSpan().Trim(), StringComparison.InvariantCultureIgnoreCase))
- {
- instanceName = input.Trim().ToString();
- }
-
return instanceName;
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
index 85abc33550..3b42dbc6f7 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
@@ -391,8 +391,8 @@ internal static SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCod
return s_extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1];
}
- // Infer SqlDbType from Type in the general case. 2008-only (or later) features that need to
- // infer types should use InferSqlDbTypeFromType_2008.
+ // 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);
@@ -409,12 +409,12 @@ internal static SqlDbType InferSqlDbTypeFromType(Type type)
return returnType;
}
- // Inference rules changed for 2008-or-later-only cases. Only features that are guaranteed to be
- // running against 2008 and don't have backward compat issues should call this code path.
- // example: TVP's are a new 2008 feature (no back compat issues) so can infer DATETIME2
+ // 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_2008(Type type)
+ internal static SqlDbType InferSqlDbTypeFromType_Katmai(Type type)
{
SqlDbType returnType = InferSqlDbTypeFromType(type);
if (SqlDbType.DateTime == returnType)
@@ -533,7 +533,7 @@ internal static bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd)
// Extract metadata for a single DataColumn
internal static SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, DataTable parent)
{
- SqlDbType dbType = InferSqlDbTypeFromType_2008(column.DataType);
+ SqlDbType dbType = InferSqlDbTypeFromType_Katmai(column.DataType);
if (InvalidSqlDbType == dbType)
{
throw SQL.UnsupportedColumnTypeForSqlProvider(column.ColumnName, column.DataType.Name);
@@ -733,7 +733,7 @@ internal static SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
}
Type colType = (Type)temp;
- SqlDbType colDbType = InferSqlDbTypeFromType_2008(colType);
+ SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType);
if (InvalidSqlDbType == colDbType)
{
// Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise error
diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlSer.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlSer.cs
similarity index 89%
rename from src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlSer.cs
rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlSer.cs
index cf510834b6..c9f1536f50 100644
--- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlSer.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlSer.cs
@@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.
using System;
-using System.Collections.Concurrent;
+using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -11,7 +11,7 @@
namespace Microsoft.Data.SqlClient.Server
{
- internal sealed class SerializationHelperSql9
+ internal class SerializationHelperSql9
{
// Don't let anyone create an instance of this class.
private SerializationHelperSql9() { }
@@ -28,8 +28,7 @@ private SerializationHelperSql9() { }
internal static int SizeInBytes(object instance)
{
Type t = instance.GetType();
-
- _ = GetFormat(t);
+ Format k = GetFormat(t);
DummyStream stream = new DummyStream();
Serializer ser = GetSerializer(instance.GetType());
ser.Serialize(stream, instance);
@@ -51,22 +50,20 @@ internal static void Serialize(Stream s, object instance)
//
// Use a per-thread cache, so that there are no synchronization
// issues when accessing cache entries from multiple threads.
- private static ConcurrentDictionary s_types2Serializers;
+ [ThreadStatic]
+ private static Hashtable s_types2Serializers;
private static Serializer GetSerializer(Type t)
{
if (s_types2Serializers == null)
- {
- s_types2Serializers = new ConcurrentDictionary();
- }
+ s_types2Serializers = new Hashtable();
- Serializer s;
- if (!s_types2Serializers.TryGetValue(t, out s))
+ Serializer s = (Serializer)s_types2Serializers[t];
+ if (s == null)
{
s = GetNewSerializer(t);
s_types2Serializers[t] = s;
}
-
return s;
}
@@ -140,8 +137,9 @@ private static object[] GetCustomAttributes(Type t)
internal static SqlUserDefinedTypeAttribute GetUdtAttribute(Type t)
{
- SqlUserDefinedTypeAttribute udtAttr;
+ SqlUserDefinedTypeAttribute udtAttr = null;
object[] attr = GetCustomAttributes(t);
+
if (attr != null && attr.Length == 1)
{
udtAttr = (SqlUserDefinedTypeAttribute)attr[0];
@@ -157,8 +155,9 @@ internal static SqlUserDefinedTypeAttribute GetUdtAttribute(Type t)
private static Serializer GetNewSerializer(Type t)
{
SqlUserDefinedTypeAttribute udtAttr = GetUdtAttribute(t);
-
- switch (udtAttr.Format)
+ Format k = GetFormat(t);
+
+ switch (k)
{
case Format.Native:
return new NormalizedSerializer(t);
@@ -166,7 +165,7 @@ private static Serializer GetNewSerializer(Type t)
return new BinarySerializeSerializer(t);
case Format.Unknown: // should never happen, but fall through
default:
- throw ADP.InvalidUserDefinedTypeSerializationFormat(udtAttr.Format);
+ throw ADP.InvalidUserDefinedTypeSerializationFormat(k);
}
}
}
@@ -184,12 +183,16 @@ internal abstract class Serializer
internal sealed class NormalizedSerializer : Serializer
{
- private readonly BinaryOrderedUdtNormalizer _normalizer;
-
+ private BinaryOrderedUdtNormalizer _normalizer;
+ private bool _isFixedSize;
+ private int _maxSize;
+
internal NormalizedSerializer(Type t) : base(t)
{
- _ = SerializationHelperSql9.GetUdtAttribute(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);
@@ -206,16 +209,7 @@ internal BinarySerializeSerializer(Type t) : base(t)
public override void Serialize(Stream s, object o)
{
BinaryWriter w = new BinaryWriter(s);
-
-#if NETFRAMEWORK
- if (o is SqlServer.Server.IBinarySerialize bs)
- {
- (bs).Write(w);
- return;
- }
-#endif
((IBinarySerialize)o).Write(w);
-
}
// Prevent inlining so that reflection calls are not moved
@@ -226,17 +220,8 @@ public override object Deserialize(Stream s)
{
object instance = Activator.CreateInstance(_type);
BinaryReader r = new BinaryReader(s);
-
-#if NETFRAMEWORK
- if (instance is SqlServer.Server.IBinarySerialize bs)
- {
- bs.Read(r);
- return instance;
- }
-#endif
- ((IBinarySerialize)instance).Read(r);
+ ((IBinarySerialize)instance).Read(r);
return instance;
-
}
}
diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/NoneAttestationEnclaveProvider.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs
similarity index 86%
rename from src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/NoneAttestationEnclaveProvider.cs
rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs
index ff36d1604c..fdf6d67d54 100644
--- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/NoneAttestationEnclaveProvider.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs
@@ -3,17 +3,21 @@
// See the LICENSE file in the project root for more information.
using System;
+using System.Collections.Generic;
using System.Diagnostics;
+using System.Linq;
+using System.Runtime.Caching;
using System.Security.Cryptography;
+using System.Text;
using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Concurrent;
namespace Microsoft.Data.SqlClient
{
- internal class NoneAttestationEnclaveProvider : EnclaveProviderBase
+ internal class SimulatorEnclaveProvider : EnclaveProviderBase
{
private static readonly int EnclaveSessionHandleSize = 8;
- private const int DiffieHellmanKeySize = 384;
- private const int NoneAttestationProtocolId = 2;
// When overridden in a derived class, looks up an existing enclave session information in the enclave session cache.
// If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter.
@@ -25,15 +29,18 @@ internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSession
// Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave.
internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength)
{
- ECDiffieHellman clientDHKey = KeyConverter.CreateECDiffieHellman(DiffieHellmanKeySize);
- return new SqlEnclaveAttestationParameters(NoneAttestationProtocolId, Array.Empty(), clientDHKey);
+ // The key derivation function and hash algorithm name are specified when key derivation is performed
+ ECDiffieHellman clientDHKey = ECDiffieHellman.Create();
+ clientDHKey.KeySize = 384;
+
+ return new SqlEnclaveAttestationParameters(2, new byte[] { }, clientDHKey);
}
- // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates an enclave session and stores the session information in the cache.
+ // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache.
internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellman clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter)
{
- // for None attestation: enclave does not send public key, and sends an empty attestation info
- // The only non-trivial content it sends is the session setup info (DH pubkey of enclave)
+ ////for simulator: enclave does not send public key, and sends an empty attestation info
+ //// The only non-trivial content it sends is the session setup info (DH pubkey of enclave)
sqlEnclaveSession = null;
counter = 0;
@@ -46,14 +53,14 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell
{
if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl))
{
- // Read AttestationInfo
+ ////Read AttestationInfo
int attestationInfoOffset = 0;
uint sizeOfTrustedModuleAttestationInfoBuffer = BitConverter.ToUInt32(attestationInfo, attestationInfoOffset);
attestationInfoOffset += sizeof(UInt32);
int sizeOfTrustedModuleAttestationInfoBufferInt = checked((int)sizeOfTrustedModuleAttestationInfoBuffer);
Debug.Assert(sizeOfTrustedModuleAttestationInfoBuffer == 0);
- // read secure session info
+ ////read secure session info
uint sizeOfSecureSessionInfoResponse = BitConverter.ToUInt32(attestationInfo, attestationInfoOffset);
attestationInfoOffset += sizeof(UInt32);
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBuffer.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBuffer.cs
index 77c954b88f..725a59fb8d 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBuffer.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBuffer.cs
@@ -126,7 +126,7 @@ private SqlBuffer(SqlBuffer value)
_object = value._object;
}
- internal bool IsEmpty => _type == StorageType.Empty;
+ internal bool IsEmpty => (StorageType.Empty == _type);
internal bool IsNull => _isNull;
@@ -386,6 +386,7 @@ internal Guid Guid
return ((SqlGuid)_object).Value;
}
return (Guid)Value;
+
}
set
{
@@ -499,7 +500,7 @@ internal string String
}
// use static list of format strings indexed by scale for perf
- private static readonly string[] s_sql2008DateTimeOffsetFormatByScale = new string[] {
+ 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",
@@ -510,7 +511,7 @@ internal string String
"yyyy-MM-dd HH:mm:ss.fffffff zzz",
};
- private static readonly string[] s_sql2008DateTime2FormatByScale = new string[] {
+ 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",
@@ -521,7 +522,7 @@ internal string String
"yyyy-MM-dd HH:mm:ss.fffffff",
};
- private static readonly string[] s_sql2008TimeFormatByScale = new string[] {
+ private static readonly string[] s_katmaiTimeFormatByScale = new string[] {
"HH:mm:ss",
"HH:mm:ss.f",
"HH:mm:ss.ff",
@@ -532,7 +533,7 @@ internal string String
"HH:mm:ss.fffffff",
};
- internal string Sql2008DateTimeString
+ internal string KatmaiDateTimeString
{
get
{
@@ -545,24 +546,24 @@ internal string Sql2008DateTimeString
if (StorageType.Time == _type)
{
byte scale = _value._timeInfo._scale;
- return new DateTime(_value._timeInfo._ticks).ToString(s_sql2008TimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
+ return new DateTime(_value._timeInfo._ticks).ToString(s_katmaiTimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
if (StorageType.DateTime2 == _type)
{
byte scale = _value._dateTime2Info._timeInfo._scale;
- return DateTime.ToString(s_sql2008DateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
+ return DateTime.ToString(s_katmaiDateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
if (StorageType.DateTimeOffset == _type)
{
DateTimeOffset dto = DateTimeOffset;
byte scale = _value._dateTimeOffsetInfo._dateTime2Info._timeInfo._scale;
- return dto.ToString(s_sql2008DateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
+ return dto.ToString(s_katmaiDateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
return (string)Value; // anything else we haven't thought of goes through boxing.
}
}
- internal SqlString Sql2008DateTimeSqlString
+ internal SqlString KatmaiDateTimeSqlString
{
get
{
@@ -575,7 +576,7 @@ internal SqlString Sql2008DateTimeSqlString
{
return SqlString.Null;
}
- return new SqlString(Sql2008DateTimeString);
+ return new SqlString(KatmaiDateTimeString);
}
return (SqlString)SqlValue; // anything else we haven't thought of goes through boxing.
}
@@ -1335,13 +1336,13 @@ private void ThrowIfNull()
// where typeof(T) == typeof(field)
// 1) RyuJIT will recognize 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
- // generated assembly will be short and direct
+ // enerated assembly will be short and direct
// 2) another jit may not recognize 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 no conversions are used and this will generate the desired InvalidCastException
- // for example users cannot widen a short to an int preserving external expectations
+ // 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()
{
@@ -1385,4 +1386,4 @@ internal T SingleAs()
return (T)(object)_value._single;
}
}
-}
+}// namespace
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs
index d469427274..8d01563b37 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs
@@ -422,7 +422,7 @@ private string CreateInitialQuery()
TDSCommand = "select @@trancount; SET FMTONLY ON select * from " + ADP.BuildMultiPartName(parts) + " SET FMTONLY OFF ";
string TableCollationsStoredProc;
- if (_connection.Is2008OrNewer)
+ if (_connection.IsKatmaiOrNewer)
{
TableCollationsStoredProc = "sp_tablecollations_100";
}
@@ -2184,7 +2184,7 @@ private Task ReadWriteColumnValueAsync(int col)
// Target type shouldn't be encrypted
Debug.Assert(!metadata.isEncrypted, "Can't encrypt SQL Variant type");
SqlBuffer.StorageType variantInternalType = SqlBuffer.StorageType.Empty;
- if ((_sqlDataReaderRowSource != null) && (_connection.Is2008OrNewer))
+ if ((_sqlDataReaderRowSource != null) && (_connection.IsKatmaiOrNewer))
{
variantInternalType = _sqlDataReaderRowSource.GetVariantInternalStorageType(_sortedColumnMappings[col]._sourceColumnOrdinal);
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs
index aef1ab92b6..85fe6156ab 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs
@@ -2969,8 +2969,8 @@ private enum ProcParamsColIndex
{
ParameterName = 0,
ParameterType,
- DataType, // obsolete in 2008, use ManagedDataType instead
- ManagedDataType, // new in 2008
+ DataType, // obsolete in katmai, use ManagedDataType instead
+ ManagedDataType, // new in katmai
CharacterMaximumLength,
NumericPrecision,
NumericScale,
@@ -2980,16 +2980,16 @@ private enum ProcParamsColIndex
XmlSchemaCollectionCatalogName,
XmlSchemaCollectionSchemaName,
XmlSchemaCollectionName,
- UdtTypeName, // obsolete in 2008. Holds the actual typename if UDT, since TypeName didn't back then.
- DateTimeScale // new in 2008
+ UdtTypeName, // obsolete in Katmai. Holds the actual typename if UDT, since TypeName didn't back then.
+ DateTimeScale // new in Katmai
};
- // 2005- column ordinals (this array indexed by ProcParamsColIndex
- internal static readonly string[] PreSql2008ProcParamsNames = new string[] {
+ // 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 2008
+ null, // ManagedDataType, introduced in Katmai
"CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
"NUMERIC_PRECISION", // NumericPrecision,
"NUMERIC_SCALE", // NumericScale,
@@ -3000,14 +3000,14 @@ private enum ProcParamsColIndex
"XML_SCHEMANAME", // XmlSchemaCollectionSchemaName,
"XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
"UDT_NAME", // UdtTypeName
- null, // Scale for datetime types with scale, introduced in 2008
+ null, // Scale for datetime types with scale, introduced in Katmai
};
- // 2008+ column ordinals (this array indexed by ProcParamsColIndex
- internal static readonly string[] Sql2008ProcParamsNames = new string[] {
+ // 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 2008+
+ null, // DataType, removed from Katmai+
"MANAGED_DATA_TYPE", // ManagedDataType,
"CHARACTER_MAXIMUM_LENGTH", // CharacterMaximumLength,
"NUMERIC_PRECISION", // NumericPrecision,
@@ -3018,7 +3018,7 @@ private enum ProcParamsColIndex
"XML_CATALOGNAME", // XmlSchemaCollectionCatalogName,
"XML_SCHEMANAME", // XmlSchemaCollectionSchemaName,
"XML_SCHEMACOLLECTIONNAME", // XmlSchemaCollectionName
- null, // UdtTypeName, removed from 2008+
+ null, // UdtTypeName, removed from Katmai+
"SS_DATETIME_PRECISION", // Scale for datetime types with scale
};
@@ -3053,7 +3053,7 @@ internal void DeriveParameters()
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 2005, else blank].[sp_procedure_params_rowset]
+ // [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]))
@@ -3070,16 +3070,16 @@ internal void DeriveParameters()
SqlCommandSet.BuildStoredProcedureName(cmdText, parsedSProc[1]);
cmdText.Append(".");
- // Schema - only if 2005, and then only pass sys. Also - pass managed version of sproc
- // for 2005, else older sproc.
+ // 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.Is2008OrNewer)
+ if (Connection.IsKatmaiOrNewer)
{
// Procedure - [sp_procedure_params_managed]
cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MGD10).Append("]");
- colNames = Sql2008ProcParamsNames;
+ colNames = KatmaiProcParamsNames;
useManagedDataType = true;
}
else
@@ -3087,7 +3087,7 @@ internal void DeriveParameters()
// Procedure - [sp_procedure_params_managed]
cmdText.Append("[sys].[").Append(TdsEnums.SP_PARAMS_MANAGED).Append("]");
- colNames = PreSql2008ProcParamsNames;
+ colNames = PreKatmaiProcParamsNames;
useManagedDataType = false;
}
@@ -3143,7 +3143,7 @@ internal void DeriveParameters()
{
p.SqlDbType = (SqlDbType)(short)r[colNames[(int)ProcParamsColIndex.ManagedDataType]];
- // 2005 didn't have as accurate of information as we're getting for 2008, so re-map a couple of
+ // 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)
{
@@ -3177,9 +3177,9 @@ internal void DeriveParameters()
{
int size = (int)a;
- // Map MAX sizes correctly. The 2008 server-side proc sends 0 for these instead of -1.
- // Should be fixed on the 2008 side, but would likely hold up the RI, and is safer to fix here.
- // If we can get the server-side fixed before shipping 2008, we can remove this mapping.
+ // 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 ||
@@ -3221,7 +3221,7 @@ internal void DeriveParameters()
// 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.Is2008OrNewer, "Invalid datatype token received from pre-2008 server");
+ Debug.Assert(_activeConnection.IsKatmaiOrNewer, "Invalid datatype token received from pre-katmai server");
//read the type name
p.TypeName = r[colNames[(int)ProcParamsColIndex.TypeCatalogName]] + "." +
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs
index bcb9378643..3946a09f33 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs
@@ -1899,15 +1899,15 @@ internal bool HasLocalTransactionFromAPI
}
- internal bool Is2008OrNewer
+ 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 2008+
+ return true; // if CR is enabled, connection, if established, will be Katmai+
}
- return GetOpenTdsConnection().Is2008OrNewer;
+ return GetOpenTdsConnection().IsKatmaiOrNewer;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs
index a801697d8f..f691da0e7a 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs
@@ -87,9 +87,14 @@ internal class SharedState
private Task _currentTask;
private Snapshot _snapshot;
+
private CancellationTokenSource _cancelAsyncOnCloseTokenSource;
private CancellationToken _cancelAsyncOnCloseToken;
+ // Used for checking if the Type parameter provided to GetValue is an INullable
+ internal static readonly Type _typeofINullable = typeof(INullable);
+ private static readonly Type s_typeofSqlString = typeof(SqlString);
+
private SqlSequentialStream _currentStream;
private SqlSequentialTextReader _currentTextReader;
@@ -552,7 +557,7 @@ internal DataTable BuildSchemaTable()
schemaRow[nonVersionedProviderType] = (int)(col.cipherMD != null ? col.baseTI.type : col.type); // SqlDbType enum value - does not change with TypeSystem.
schemaRow[dataTypeName] = GetDataTypeNameInternal(col);
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType)
{
schemaRow[providerType] = SqlDbType.NVarChar;
switch (col.type)
@@ -595,12 +600,12 @@ internal DataTable BuildSchemaTable()
if (col.type == SqlDbType.Udt)
{ // Additional metadata for UDTs.
- Debug.Assert(Connection.Is2008OrNewer, "Invalid Column type received from the server");
+ 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.Is2008OrNewer, "Invalid DataType (Xml) for the column");
+ 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;
@@ -635,7 +640,7 @@ internal DataTable BuildSchemaTable()
schemaRow[precision] = col.metaType.Precision;
}
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType)
{
schemaRow[scale] = MetaType.MetaNVarChar.Scale;
}
@@ -1170,7 +1175,7 @@ private string GetDataTypeNameInternal(_SqlMetaData metaData)
{
string dataTypeName = null;
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
{
dataTypeName = MetaType.MetaNVarChar.TypeName;
}
@@ -1252,9 +1257,9 @@ private Type GetFieldTypeInternal(_SqlMetaData metaData)
{
Type fieldType = null;
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
{
- // Return 2008 types as string
+ // Return katmai types as string
fieldType = MetaType.MetaNVarChar.ClassType;
}
else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
@@ -1360,7 +1365,7 @@ private Type GetProviderSpecificFieldTypeInternal(_SqlMetaData metaData)
{
Type providerSpecificFieldType = null;
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
{
providerSpecificFieldType = MetaType.MetaNVarChar.SqlType;
}
@@ -2284,7 +2289,7 @@ override public DateTime GetDateTime(int 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].Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
{
// TypeSystem.SQLServer2005 or less
@@ -2382,10 +2387,10 @@ virtual public SqlChars GetSqlChars(int i)
{
ReadColumn(i);
SqlString data;
- // Convert 2008 types to string
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].Is2008DateTimeType)
+ // Convert Katmai types to string
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
{
- data = _data[i].Sql2008DateTimeSqlString;
+ data = _data[i].KatmaiDateTimeSqlString;
}
else
{
@@ -2462,9 +2467,9 @@ virtual public SqlString GetSqlString(int i)
{
ReadColumn(i);
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
{
- return _data[i].Sql2008DateTimeSqlString;
+ return _data[i].KatmaiDateTimeSqlString;
}
return _data[i].SqlString;
@@ -2541,10 +2546,10 @@ private object GetSqlValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData met
{
Debug.Assert(!data.IsEmpty || data.IsNull || metaData.type == SqlDbType.Timestamp, "Data has been read, but the buffer is empty");
- // Convert 2008 types to string
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.Is2008DateTimeType)
+ // Convert Katmai types to string
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
{
- return data.Sql2008DateTimeSqlString;
+ return data.KatmaiDateTimeSqlString;
}
else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
{
@@ -2621,10 +2626,10 @@ override public string GetString(int i)
{
ReadColumn(i);
- // Convert 2008 value to string if type system knob is 2005 or earlier
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].Is2008DateTimeType)
+ // Convert katmai value to string if type system knob is 2005 or earlier
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
{
- return _data[i].Sql2008DateTimeString;
+ return _data[i].KatmaiDateTimeString;
}
return _data[i].String;
@@ -2731,7 +2736,7 @@ private object GetValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaDa
{
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.Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
{
if (data.IsNull)
{
@@ -2739,7 +2744,7 @@ private object GetValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaDa
}
else
{
- return data.Sql2008DateTimeString;
+ return data.KatmaiDateTimeString;
}
}
else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt)
@@ -2835,11 +2840,11 @@ private T GetFieldValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData met
{
return (T)(object)data.Decimal;
}
- else if (typeof(T) == typeof(DateTimeOffset) && dataType == typeof(DateTimeOffset) && _typeSystem > SqlConnectionString.TypeSystem.SQLServer2005 && metaData.Is2008DateTimeType)
+ 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.Is2008DateTimeType)
+ else if (typeof(T) == typeof(DateTime) && dataType == typeof(DateTime) && _typeSystem > SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType)
{
return (T)(object)data.DateTime;
}
@@ -2950,7 +2955,7 @@ private T GetFieldValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData met
{
// If its a SQL Type or Nullable UDT
object rawValue = GetSqlValueFromSqlBufferInternal(data, metaData);
- if (typeof(T) == typeof(SqlString))
+ if (typeof(T) == 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
@@ -2981,7 +2986,6 @@ private T GetFieldValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData met
}
catch (InvalidCastException) when (data.IsNull)
{
- // If the value was actually null, then we should throw a SqlNullValue instead
throw SQL.SqlNullValue();
}
@@ -5740,7 +5744,7 @@ private ReadOnlyCollection BuildColumnSchema()
_SqlMetaData col = md[i];
SqlDbColumn dbColumn = new SqlDbColumn(md[i]);
- if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.Is2008DateTimeType)
+ if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType)
{
dbColumn.SqlNumericScale = MetaType.MetaNVarChar.Scale;
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs
new file mode 100644
index 0000000000..967cf6acf8
--- /dev/null
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs
@@ -0,0 +1,72 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+namespace Microsoft.Data.SqlClient
+{
+ ///
+ public sealed class SqlError
+ {
+ 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;
+ Class = errorClass;
+ Server = server;
+ Message = errorMessage;
+ Procedure = procedure;
+ LineNumber = lineNumber;
+ Win32ErrorCode = 0;
+ Exception = exception;
+ if (errorClass != 0)
+ {
+ SqlClientEventSource.Log.TryTraceEvent("SqlError.ctor | ERR | Info Number {0}, Error State {1}, Error Class {2}, Error Message '{3}', Procedure '{4}', Line Number {5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber);
+ }
+ }
+
+ ///
+ // 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; private set; } = TdsEnums.SQL_PROVIDER_NAME;
+
+ ///
+ public int Number { get; private set; }
+
+ ///
+ public byte State { get; private set; }
+
+ ///
+ public byte Class { get; private set; }
+
+ ///
+ public string Server { get; private set; }
+
+ ///
+ public string Message { get; private set; }
+
+ ///
+ public string Procedure { get; private set; }
+
+ ///
+ public int LineNumber { get; private set; }
+
+ internal int Win32ErrorCode { get; private set; }
+
+ internal Exception Exception { get; private set; }
+ }
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs
index b863db3cba..fbc4d6f9b7 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs
@@ -145,7 +145,7 @@ abstract internal bool IsLockedForBulkCopy
}
- abstract internal bool Is2008OrNewer
+ abstract internal bool IsKatmaiOrNewer
{
get;
}
@@ -337,7 +337,7 @@ private void EnlistNonNull(Transaction tx)
SqlClientEventSource.Log.TryAdvancedTraceEvent("SqlInternalConnection.EnlistNonNull | ADV | Object {0}, Transaction Id {1}, attempting to delegate.", ObjectID, tx?.TransactionInformation?.LocalIdentifier);
bool hasDelegatedTransaction = false;
- // Promotable transactions are only supported on 2005
+ // Promotable transactions are only supported on Yukon
// servers or newer.
SqlDelegatedTransaction delegatedTransaction = new SqlDelegatedTransaction(this, tx);
@@ -469,17 +469,17 @@ private void EnlistNonNull(Transaction tx)
EnlistedTransaction = tx; // Tell the base class about our enlistment
- // If we're on a 2005 or newer server, and we delegate the
+ // 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 2005 or newer server will
+ // 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 2005 or newer server
+ // 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?");
@@ -511,7 +511,7 @@ internal void EnlistNull()
// which causes the TdsParser or SmiEventSink should to clear the
// current transaction.
//
- // In either case, when we're working with a 2005 or newer server
+ // 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!
@@ -539,7 +539,7 @@ override public void EnlistTransaction(Transaction transaction)
// 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 & 2005, when you enlist in a DTC transaction
+ // 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
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs
index dcbc62ef0d..484e2233a9 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs
@@ -636,15 +636,15 @@ internal protected override bool IsNonPoolableTransactionRoot
{
get
{
- return IsTransactionRoot && (!Is2008OrNewer || null == Pool);
+ return IsTransactionRoot && (!IsKatmaiOrNewer || null == Pool);
}
}
- internal override bool Is2008OrNewer
+ internal override bool IsKatmaiOrNewer
{
get
{
- return _parser.Is2008OrNewer;
+ return _parser.IsKatmaiOrNewer;
}
}
@@ -934,7 +934,7 @@ private void ResetConnection()
if (_fResetConnection)
{
- // Ensure we are either going against 2000, or we are not enlisted in a
+ // 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.
@@ -1001,11 +1001,11 @@ internal override void ExecuteTransaction(TransactionRequest transactionRequest,
string transactionName = (null == name) ? string.Empty : name;
- ExecuteTransaction2005(transactionRequest, transactionName, iso, internalTransaction, isDelegateControlRequest);
+ ExecuteTransactionYukon(transactionRequest, transactionName, iso, internalTransaction, isDelegateControlRequest);
}
- internal void ExecuteTransaction2005(
+ internal void ExecuteTransactionYukon(
TransactionRequest transactionRequest,
string transactionName,
System.Data.IsolationLevel iso,
@@ -1068,7 +1068,7 @@ bool isDelegateControlRequest
requestType = TdsEnums.TransactionManagerRequestType.Commit;
break;
case TransactionRequest.IfRollback:
- // Map IfRollback to Rollback since with 2005 and beyond we should never need
+ // 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:
@@ -1124,7 +1124,7 @@ bool isDelegateControlRequest
}
if (internalTransaction.OpenResultsCount != 0)
{
- SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection is marked to be doomed when closed. Transaction ended with OpenResultsCount {1} > 0, MARSOn {2}",
+ SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection is marked to be doomed when closed. Transaction ended with OpenResultsCount {1} > 0, MARSOn {2}",
ObjectID,
internalTransaction.OpenResultsCount,
_parser.MARSOn);
@@ -2065,7 +2065,7 @@ internal void OnEnvChange(SqlEnvChange rec)
break;
case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
- // For now we skip these 2005 only env change notifications
+ // For now we skip these Yukon only env change notifications
break;
case TdsEnums.ENV_SPRESETCONNECTIONACK:
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs
index 5d706c6c0a..408dba0645 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs
@@ -269,9 +269,9 @@ internal void CloseFromConnection()
{
if (processFinallyBlock)
{
- // Always ensure we're zombied; 2005 will send an EnvChange that
+ // Always ensure we're zombied; Yukon will send an EnvChange that
// will cause the zombie, but only if we actually go to the wire;
- // 7.0 and 2000 won't send the env change, so we have to handle
+ // Sphinx and Shiloh won't send the env change, so we have to handle
// them ourselves.
Zombie();
}
@@ -498,7 +498,7 @@ internal void Zombie()
// 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-2005
+ // 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.
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs
index 9845a03aa7..cc919a89e5 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs
@@ -1988,7 +1988,7 @@ internal MetaType ValidateTypeLengths()
else
{
// Notes:
- // Elevation from (n)(var)char (4001+) to (n)text succeeds without failure only with 2005 and greater.
+ // 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;
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs
index 2eecfdc8cc..f1852c24f4 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs
@@ -89,7 +89,7 @@ override public IsolationLevel IsolationLevel
}
}
- private bool Is2005PartialZombie
+ private bool IsYukonPartialZombie
{
get
{
@@ -182,7 +182,7 @@ protected override void Dispose(bool disposing)
{
if (disposing)
{
- if (!IsZombied && !Is2005PartialZombie)
+ if (!IsZombied && !IsYukonPartialZombie)
{
_internalTransaction.Dispose();
}
@@ -195,11 +195,11 @@ override public void Rollback()
{
using (DiagnosticTransactionScope diagnosticScope = s_diagnosticListener.CreateTransactionRollbackScope(_isolationLevel, _connection, InternalTransaction, null))
{
- if (Is2005PartialZombie)
+ if (IsYukonPartialZombie)
{
// Put something in the trace in case a customer has an issue
SqlClientEventSource.Log.TryAdvancedTraceEvent("SqlTransaction.Rollback | ADV | Object Id {0}, partial zombie no rollback required", ObjectID);
- _internalTransaction = null; // 2005 zombification
+ _internalTransaction = null; // yukon zombification
}
else
{
@@ -291,7 +291,7 @@ public void Save(string savePointName)
internal void Zombie()
{
- // For 2005, we have to defer "zombification" until
+ // 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,
@@ -299,11 +299,11 @@ internal void Zombie()
SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection);
if (null != internalConnection && !_isFromAPI)
{
- SqlClientEventSource.Log.TryAdvancedTraceEvent("SqlTransaction.Zombie | ADV | Object Id {0} 2005 deferred zombie", ObjectID);
+ SqlClientEventSource.Log.TryAdvancedTraceEvent("SqlTransaction.Zombie | ADV | Object Id {0} yukon deferred zombie", ObjectID);
}
else
{
- _internalTransaction = null; // pre-2005 zombification
+ _internalTransaction = null; // pre-yukon zombification
}
}
@@ -316,9 +316,9 @@ private void ZombieCheck()
// If this transaction has been completed, throw exception since it is unusable.
if (IsZombied)
{
- if (Is2005PartialZombie)
+ if (IsYukonPartialZombie)
{
- _internalTransaction = null; // 2005 zombification
+ _internalTransaction = null; // yukon zombification
}
throw ADP.TransactionZombied(this);
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs
index 8e9039a6aa..522092b988 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs
@@ -394,7 +394,7 @@ internal static Exception ChangePasswordConflictsWithSSPI()
{
return ADP.Argument(StringsHelper.GetString(Strings.SQL_ChangePasswordConflictsWithSSPI));
}
- internal static Exception ChangePasswordRequires2005()
+ internal static Exception ChangePasswordRequiresYukon()
{
return ADP.InvalidOperation(StringsHelper.GetString(Strings.SQL_ChangePasswordRequiresYukon));
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs
index 6b77e98c2e..44be90bb31 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs
@@ -10,6 +10,7 @@
using System.Diagnostics;
using System.Globalization;
using System.IO;
+using System.Reflection;
using System.Security.Authentication;
using System.Text;
using System.Threading;
@@ -41,6 +42,7 @@ internal sealed partial class TdsParser
{
private static int _objectTypeCount; // EventSource counter
private readonly SqlClientLogger _logger = new SqlClientLogger();
+ private readonly string _typeName;
internal readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
internal int ObjectID => _objectID;
@@ -88,7 +90,7 @@ internal sealed partial class TdsParser
private EncryptionOptions _encryptionOption = s_sniSupportedEncryptionOption;
private SqlInternalTransaction _currentTransaction;
- private SqlInternalTransaction _pendingTransaction; // pending transaction for 2005 and beyond.
+ 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;
@@ -111,11 +113,11 @@ internal sealed partial class TdsParser
// Version variables
- private bool _is2005 = false; // set to true if speaking to 2005 or later
+ private bool _isYukon = false; // set to true if speaking to Yukon or later
- private bool _is2008 = false;
+ private bool _isKatmai = false;
- private bool _is2012 = false;
+ private bool _isDenali = false;
private byte[][] _sniSpnBuffer = null;
@@ -188,10 +190,11 @@ internal sealed partial class TdsParser
internal TdsParser(bool MARS, bool fAsynchronous)
{
- _fMARS = MARS; // may change during Connect to pre 2005 servers
+ _fMARS = MARS; // may change during Connect to pre Yukon servers
_physicalStateObj = TdsParserStateObjectFactory.Singleton.CreateTdsParserStateObject(this);
DataClassificationVersion = TdsEnums.DATA_CLASSIFICATION_NOT_ENABLED;
+ _typeName = GetType().Name;
}
internal SqlInternalConnectionTds Connection
@@ -257,11 +260,11 @@ internal EncryptionOptions EncryptionOptions
}
}
- internal bool Is2008OrNewer
+ internal bool IsKatmaiOrNewer
{
get
{
- return _is2008;
+ return _isKatmai;
}
}
@@ -322,7 +325,7 @@ private bool IncludeTraceHeader
{
get
{
- return (_is2012 && SqlClientEventSource.Log.IsEnabled());
+ return (_isDenali && SqlClientEventSource.Log.IsEnabled());
}
}
@@ -529,8 +532,8 @@ internal void Connect(
SendPreLoginHandshake(instanceName, encrypt);
status = ConsumePreLoginHandshake(encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired);
- // Don't need to check for 7.0 failure, since we've already consumed
- // one pre-login packet and know we are connecting to 2000.
+ // 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)
{
SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Login failure");
@@ -804,7 +807,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus
{
marsCapable = _fMARS; // Assign default value
fedAuthRequired = false;
- bool is2005OrLater = false;
+ bool isYukonOrLater = false;
Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
bool result = _physicalStateObj.TryReadNetworkPacket();
if (!result)
@@ -863,10 +866,10 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus
int level = (payload[payloadOffset + 2] << 8) |
payload[payloadOffset + 3];
- is2005OrLater = majorVersion >= 9;
- if (!is2005OrLater)
+ isYukonOrLater = majorVersion >= 9;
+ if (!isYukonOrLater)
{
- marsCapable = false; // If pre-2005, MARS not supported.
+ marsCapable = false; // If pre-Yukon, MARS not supported.
}
break;
@@ -934,7 +937,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus
// Validate Certificate if Trust Server Certificate=false and Encryption forced (EncryptionOptions.ON) from Server.
bool shouldValidateServerCert = (_encryptionOption == EncryptionOptions.ON && !trustServerCert) || (_connHandler._accessTokenInBytes != null && !trustServerCert);
uint info = (shouldValidateServerCert ? TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE : 0)
- | (is2005OrLater ? TdsEnums.SNI_SSL_USE_SCHANNEL_CACHE : 0);
+ | (isYukonOrLater ? TdsEnums.SNI_SSL_USE_SCHANNEL_CACHE : 0);
if (encrypt && !integratedSecurity)
{
@@ -959,16 +962,8 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus
string warningMessage = protocol.GetProtocolWarning();
if (!string.IsNullOrEmpty(warningMessage))
{
- if (!encrypt && LocalAppContextSwitches.SuppressInsecureTLSWarning)
- {
- // Skip console warning
- SqlClientEventSource.Log.TryTraceEvent("{3}", nameof(TdsParser), nameof(ConsumePreLoginHandshake), SqlClientLogger.LogLevel.Warning, warningMessage);
- }
- else
- {
- // This logs console warning of insecure protocol in use.
- _logger.LogWarning(nameof(TdsParser), nameof(ConsumePreLoginHandshake), warningMessage);
- }
+ // This logs console warning of insecure protocol in use.
+ _logger.LogWarning(_typeName, MethodBase.GetCurrentMethod().Name, warningMessage);
}
// create a new packet encryption changes the internal packet size
@@ -1534,7 +1529,7 @@ internal void CheckResetConnection(TdsParserStateObject stateObj)
{
Debug.Assert(!stateObj._fResetConnectionSent, "Unexpected state on WritePacket ResetConnection");
- // Otherwise if 2005 and we grabbed the event, free it. Another execute grabbed the event and
+ // 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!");
@@ -1544,7 +1539,7 @@ internal void CheckResetConnection(TdsParserStateObject stateObj)
{
if (_fMARS && stateObj._fResetEventOwned)
{
- // If exception thrown, and we are on 2005 and own the event, release it!
+ // 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!");
@@ -1817,7 +1812,7 @@ internal void WriteDouble(double v, TdsParserStateObject stateObj)
internal void PrepareResetConnection(bool preserveTransaction)
{
- // Set flag to reset connection upon next use - only for use on 2000!
+ // Set flag to reset connection upon next use - only for use on shiloh!
_fResetConnection = true;
_fPreserveTransaction = preserveTransaction;
}
@@ -3597,40 +3592,41 @@ private bool TryProcessLoginAck(TdsParserStateObject stateObj, out SqlLoginAck s
uint increment = (a.tdsVersion >> 16) & 0xff;
// Server responds:
- // 0x07000000 -> 7.0 // Notice server response format is different for bwd compat
- // 0x07010000 -> 2000 RTM // Notice server response format is different for bwd compat
- // 0x71000001 -> 2000 SP1
- // 0x72xx0002 -> 2005 RTM
+ // 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.SQL2005_MAJOR << 24 | TdsEnums.SQL2005_RTM_MINOR: // 2005
- if (increment != TdsEnums.SQL2005_INCREMENT)
+ case TdsEnums.YUKON_MAJOR << 24 | TdsEnums.YUKON_RTM_MINOR: // Yukon
+ if (increment != TdsEnums.YUKON_INCREMENT)
{
throw SQL.InvalidTDSVersion();
}
- _is2005 = true;
+ _isYukon = true;
break;
- case TdsEnums.SQL2008_MAJOR << 24 | TdsEnums.SQL2008_MINOR:
- if (increment != TdsEnums.SQL2008_INCREMENT)
+ case TdsEnums.KATMAI_MAJOR << 24 | TdsEnums.KATMAI_MINOR:
+ if (increment != TdsEnums.KATMAI_INCREMENT)
{
throw SQL.InvalidTDSVersion();
}
- _is2008 = true;
+ _isKatmai = true;
break;
- case TdsEnums.SQl2012_MAJOR << 24 | TdsEnums.SQL2012_MINOR:
- if (increment != TdsEnums.SQL2012_INCREMENT)
+ case TdsEnums.DENALI_MAJOR << 24 | TdsEnums.DENALI_MINOR:
+ if (increment != TdsEnums.DENALI_INCREMENT)
{
throw SQL.InvalidTDSVersion();
}
- _is2012 = true;
+ _isDenali = true;
break;
default:
throw SQL.InvalidTDSVersion();
}
- _is2008 |= _is2012;
- _is2005 |= _is2008;
+ _isKatmai |= _isDenali;
+ _isYukon |= _isKatmai;
stateObj._outBytesUsed = stateObj._outputHeaderLen;
byte len;
@@ -3898,7 +3894,7 @@ internal bool TryProcessReturnValue(int length, TdsParserStateObject stateObj, o
{
returnValue = null;
SqlReturnValue rec = new SqlReturnValue();
- rec.length = length; // In 2005 this length is -1
+ rec.length = length; // In Yukon this length is -1
ushort parameterIndex;
if (!stateObj.TryReadUInt16(out parameterIndex))
{
@@ -3928,7 +3924,7 @@ internal bool TryProcessReturnValue(int length, TdsParserStateObject stateObj, o
uint userType;
- // read user type - 4 bytes 2005, 2 backwards
+ // read user type - 4 bytes Yukon, 2 backwards
if (!stateObj.TryReadUInt32(out userType))
{
return false;
@@ -3985,8 +3981,8 @@ internal bool TryProcessReturnValue(int length, TdsParserStateObject stateObj, o
rec.metaType = MetaType.GetSqlDataType(tdsType, userType, tdsLen);
rec.type = rec.metaType.SqlDbType;
- // always use the nullable type for parameters if 2000 or later
- // 7.0 sometimes sends fixed length return values
+ // 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)
@@ -4898,7 +4894,7 @@ private bool TryCommonProcessMetaData(TdsParserStateObject stateObj, _SqlMetaDat
byte byteLen;
uint userType;
- // read user type - 4 bytes 2005, 2 backwards
+ // read user type - 4 bytes Yukon, 2 backwards
if (!stateObj.TryReadUInt32(out userType))
{
return false;
@@ -7478,7 +7474,7 @@ internal int GetEncodingCharLength(string value, int numChars, int charOffset, E
//
internal bool TryGetDataLength(SqlMetaDataPriv colmeta, TdsParserStateObject stateObj, out ulong length)
{
- // Handle 2005 specific tokens
+ // Handle Yukon specific tokens
if (colmeta.metaType.IsPlp)
{
Debug.Assert(colmeta.tdsType == TdsEnums.SQLXMLTYPE ||
@@ -7532,7 +7528,7 @@ internal bool TryGetTokenLength(byte token, TdsParserStateObject stateObj, out i
}
else if (token == TdsEnums.SQLRETURNVALUE)
{
- tokenLength = -1; // In 2005, the RETURNVALUE token stream no longer has length
+ tokenLength = -1; // In Yukon, the RETURNVALUE token stream no longer has length
return true;
}
else if (token == TdsEnums.SQLXMLTYPE)
@@ -7992,7 +7988,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures
_physicalStateObj._outputMessageType = TdsEnums.MT_LOGIN7;
// length in bytes
- int length = TdsEnums.SQL2005_LOG_REC_FIXED_LEN;
+ 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");
@@ -8098,7 +8094,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures
WriteInt(length, _physicalStateObj);
if (recoverySessionData == null)
{
- WriteInt((TdsEnums.SQl2012_MAJOR << 24) | (TdsEnums.SQL2012_INCREMENT << 16) | TdsEnums.SQL2012_MINOR, _physicalStateObj);
+ WriteInt((TdsEnums.DENALI_MAJOR << 24) | (TdsEnums.DENALI_INCREMENT << 16) | TdsEnums.DENALI_MINOR, _physicalStateObj);
}
else
{
@@ -8182,7 +8178,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures
WriteInt(0, _physicalStateObj); // LCID is unused by server
// Start writing offset and length of variable length portions
- int offset = TdsEnums.SQL2005_LOG_REC_FIXED_LEN;
+ int offset = TdsEnums.YUKON_LOG_REC_FIXED_LEN;
// write offset/length pairs
@@ -9000,7 +8996,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo
{
if (rpcext.ProcID != 0)
{
- // Perf optimization for 2000 and later,
+ // 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);
@@ -9065,14 +9061,14 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo
// 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.Is2008Type)
+ if (mt.IsNewKatmaiType)
{
WriteSmiParameter(param, i, 0 != (options & TdsEnums.RPC_PARAM_DEFAULT), stateObj, enableOptimizedParameterBinding, isAdvancedTraceOn);
continue;
}
- if ((!_is2005 && !mt.Is80Supported) ||
- (!_is2008 && !mt.Is90Supported))
+ if ((!_isYukon && !mt.Is80Supported) ||
+ (!_isKatmai && !mt.Is90Supported))
{
throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
}
@@ -9135,7 +9131,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo
// If this is not the last RPC we are sending, add the batch flag
if (ii < (rpcArray.Length - 1))
{
- stateObj.WriteByte(TdsEnums.SQL2005_RPCBATCHFLAG);
+ stateObj.WriteByte(TdsEnums.YUKON_RPCBATCHFLAG);
}
} // rpc for loop
@@ -9411,7 +9407,7 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet
maxsize = (size > codePageByteSize) ? size : codePageByteSize;
if (maxsize == 0)
{
- // 2005 doesn't like 0 as MaxSize. Change it to 2 for unicode types
+ // Yukon doesn't like 0 as MaxSize. Change it to 2 for unicode types
if (mt.IsNCharType)
maxsize = 2;
else
@@ -9436,9 +9432,9 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet
}
else if (mt.SqlDbType == SqlDbType.Udt)
{
- Debug.Assert(_is2005, "Invalid DataType UDT for non-2005 or later server!");
+ Debug.Assert(_isYukon, "Invalid DataType UDT for non-Yukon or later server!");
- int maxSupportedSize = Is2008OrNewer ? int.MaxValue : short.MaxValue;
+ int maxSupportedSize = IsKatmaiOrNewer ? int.MaxValue : short.MaxValue;
byte[] udtVal = null;
Format format = Format.Native;
@@ -9528,9 +9524,9 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet
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 && _is2005)
+ if (maxsize == 0 && _isYukon)
{
- // 2005 doesn't like 0 as MaxSize. Change it to 2 for unicode types (SQL9 - 682322)
+ // Yukon doesn't like 0 as MaxSize. Change it to 2 for unicode types (SQL9 - 682322)
if (mt.IsNCharType)
maxsize = 2;
else
@@ -9562,7 +9558,7 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet
// write out collation or xml metadata
- if (_is2005 && (mt.SqlDbType == SqlDbType.Xml))
+ if (_isYukon && (mt.SqlDbType == SqlDbType.Xml))
{
if (!string.IsNullOrEmpty(param.XmlSchemaCollectionDatabase) ||
!string.IsNullOrEmpty(param.XmlSchemaCollectionOwningSchema) ||
@@ -9766,7 +9762,7 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa
ParameterPeekAheadValue peekAhead;
SmiParameterMetaData metaData = param.MetaDataForSmi(out peekAhead);
- if (!_is2008)
+ if (!_isKatmai)
{
MetaType mt = MetaType.GetMetaTypeFromSqlDbType(metaData.SqlDbType, metaData.IsMultiValued);
throw ADP.VersionDoesNotSupportDataType(mt.TypeName);
@@ -10356,7 +10352,7 @@ internal void WriteBulkCopyMetaData(_SqlMetaDataSet metadataCollection, int coun
{
_SqlMetaData md = metadataCollection[i];
- // read user type - 4 bytes 2005, 2 backwards
+ // read user type - 4 bytes Yukon, 2 backwards
WriteInt(0x0, stateObj);
// Write the flags
@@ -10759,7 +10755,7 @@ private Task WriteBulkCopyValueSetupContinuation(Task internalWriteTask, Encodin
// 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 2005 and beyond only.
+ // 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!");
@@ -10835,7 +10831,7 @@ private int GetNotificationHeaderSize(SqlNotificationRequest notificationRequest
// Write query notificaiton header data, not including the notificaiton header length
private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj)
{
- Debug.Assert(_is2005, "WriteQueryNotificationHeaderData called on a non-2005 server");
+ 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
@@ -10866,7 +10862,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio
private void WriteTraceHeaderData(TdsParserStateObject stateObj)
{
- Debug.Assert(this.IncludeTraceHeader, "WriteTraceHeaderData can only be called on a 2012 or higher version server and bid trace with the control bit are on");
+ Debug.Assert(this.IncludeTraceHeader, "WriteTraceHeaderData can only be called on a Denali or higher version server and bid trace with the control bit are on");
// We may need to update the trace header length if trace header is changed in the future
@@ -11098,21 +11094,15 @@ private Task WriteUnterminatedSqlValue(object value, MetaType type, int actualLe
{
Debug.Assert(actualLength == 16, "Invalid length for guid type in com+ object");
Span b = stackalloc byte[16];
- if (value is Guid guid)
+ SqlGuid sqlGuid = (SqlGuid)value;
+
+ if (sqlGuid.IsNull)
{
- FillGuidBytes(guid, b);
+ b.Clear(); // this is needed because initlocals may be supressed in framework assemblies meaning the memory is not automaticaly zeroed
}
else
{
- 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);
- }
+ FillGuidBytes(sqlGuid.Value, b);
}
stateObj.WriteByteSpan(b);
break;
@@ -12808,7 +12798,7 @@ private bool TryProcessUDTMetaData(SqlMetaDataPriv metaData, TdsParserStateObjec
+ " _connHandler = {14}\n\t"
+ " _fMARS = {15}\n\t"
+ " _sessionPool = {16}\n\t"
- + " _is2005 = {17}\n\t"
+ + " _isYukon = {17}\n\t"
+ " _sniSpnBuffer = {18}\n\t"
+ " _errors = {19}\n\t"
+ " _warnings = {20}\n\t"
@@ -12840,7 +12830,7 @@ internal string TraceString()
null == _connHandler ? "(null)" : _connHandler.ObjectID.ToString((IFormatProvider)null),
_fMARS ? bool.TrueString : bool.FalseString,
null == _sessionPool ? "(null)" : _sessionPool.TraceString(),
- _is2005 ? bool.TrueString : bool.FalseString,
+ _isYukon ? bool.TrueString : bool.FalseString,
null == _sniSpnBuffer ? "(null)" : _sniSpnBuffer.Length.ToString((IFormatProvider)null),
_physicalStateObj != null ? "(null)" : _physicalStateObj.ErrorCount.ToString((IFormatProvider)null),
_physicalStateObj != null ? "(null)" : _physicalStateObj.WarningCount.ToString((IFormatProvider)null),
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs
index 6daecb969c..428c03b676 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs
@@ -324,7 +324,7 @@ private void Set(_SqlMetadataFlags flag, bool value)
flags = value ? flags | flag : flags & ~flag;
}
- internal bool Is2008DateTimeType
+ internal bool IsNewKatmaiDateTimeType
{
get
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs
index cbeb228ab9..7e06c3df98 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs
@@ -174,7 +174,7 @@ public TimeoutState(int value)
internal ulong _longlen; // plp data length indicator
internal ulong _longlenleft; // Length of data left to read (64 bit lengths)
internal int[] _decimalBits; // scratch buffer for decimal/numeric data
- internal byte[] _bTmp = new byte[TdsEnums.SQL2005_HEADER_LEN]; // Scratch buffer for misc use
+ internal byte[] _bTmp = new byte[TdsEnums.YUKON_HEADER_LEN]; // Scratch buffer for misc use
internal int _bTmpRead; // Counter for number of temporary bytes read
internal Decoder _plpdecoder; // Decoder object to process plp character data
internal bool _accumulateInfoEvents; // TRUE - accumulate info messages during TdsParser.Run, FALSE - fire them
@@ -494,8 +494,8 @@ internal bool TryStartNewRow(bool isNullCompressed, int nullBitmapColumnsCount =
// initialize or unset null bitmap information for the current row
if (isNullCompressed)
{
- // assert that NBCROW is not in use by 2005 or before
- Debug.Assert(_parser.Is2008OrNewer, "NBCROW is sent by pre-2008 server");
+ // 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))
{
@@ -3336,9 +3336,9 @@ internal Task WritePacket(byte flushMode, bool canAccumulate = false)
}
if (
- // This appears to be an optimization to avoid writing empty packets in 2005
- // However, since we don't know the version prior to login Is2005OrNewer was always false prior to login
- // So removing the Is2005OrNewer check causes issues since the login packet happens to meet the rest of the conditions below
+ // 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
diff --git a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs
index eca9091a58..e078631f4e 100644
--- a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs
@@ -384,8 +384,6 @@ public partial class SqlClientLogger
public SqlClientLogger() { }
///
public bool IsLoggingEnabled { get { throw null; } }
- ///
- public void LogWarning(string type, string method, string message) { }
///
public bool LogAssert(bool value, string type, string method, string message) { throw null; }
///
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/.editorconfig b/src/Microsoft.Data.SqlClient/netfx/src/.editorconfig
deleted file mode 100644
index f3238bb87b..0000000000
--- a/src/Microsoft.Data.SqlClient/netfx/src/.editorconfig
+++ /dev/null
@@ -1,9 +0,0 @@
-# editorconfig.org
-
-# top-most EditorConfig file
-root = false
-
-[*.cs]
-
-# IDE0090: Use 'new(...)'
-csharp_style_implicit_object_creation_when_type_is_apparent = false
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj
index c4265b350b..dc4e369dfc 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj
@@ -165,9 +165,6 @@
Microsoft\Data\SqlClient\AzureAttestationBasedEnclaveProvider.cs
-
- Microsoft\Data\SqlClient\NoneAttestationEnclaveProvider.cs
-
Microsoft\Data\SqlClient\EnclaveDelegate.cs
@@ -249,9 +246,6 @@
Microsoft\Data\SqlClient\Server\SmiMetaDataProperty.cs
-
- Microsoft\Data\SqlClient\Server\SqlSer.cs
-
Microsoft\Data\SqlClient\ColumnEncryptionKeyInfo.cs
@@ -378,9 +372,6 @@
Microsoft\Data\SqlClient\SqlEnums.cs
-
- Microsoft\Data\SqlClient\SqlError.cs
-
Microsoft\Data\SqlClient\SqlErrorCollection.cs
@@ -435,6 +426,9 @@
Microsoft\Data\SqlClient\SqlSymmetricKeyCache.cs
+
+ Microsoft\Data\SqlClient\TdsEnums.cs
+
Microsoft\Data\SqlClient\VirtualSecureModeEnclaveProvider.cs
@@ -579,6 +573,7 @@
+
@@ -596,7 +591,6 @@
Microsoft\Data\SqlClient\SqlUdtInfo.cs
-
@@ -634,8 +628,12 @@
+
+
+
+
@@ -709,4 +707,4 @@
-
+
\ No newline at end of file
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
index e3b4ea2ef4..f1f4c955af 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
@@ -16,11 +16,11 @@
namespace Microsoft.Data
{
+
internal static class LocalDBAPI
{
- private const string LocalDbPrefix = @"(localdb)\";
- private const string LocalDbPrefix_NP = @"np:\\.\pipe\LOCALDB#";
- const string Const_partialTrustFlagKey = "ALLOW_LOCALDB_IN_PARTIAL_TRUST";
+ const string const_localDbPrefix = @"(localdb)\";
+ const string const_partialTrustFlagKey = "ALLOW_LOCALDB_IN_PARTIAL_TRUST";
static PermissionSet _fullTrust = null;
static bool _partialTrustFlagChecked = false;
@@ -30,28 +30,19 @@ internal static class LocalDBAPI
// check if name is in format (localdb)\ and return instance name if it is
internal static string GetLocalDbInstanceNameFromServerName(string serverName)
{
- if (serverName is not null)
- {
- // it can start with spaces if specified in quotes
- // Memory allocation is reduced by using ReadOnlySpan
- ReadOnlySpan input = serverName.AsSpan().Trim();
- if (input.StartsWith(LocalDbPrefix.AsSpan(), StringComparison.OrdinalIgnoreCase))
- {
- input = input.Slice(LocalDbPrefix.Length);
- if (!input.IsEmpty)
- {
- return input.ToString();
- }
- }
- else if (input.StartsWith(LocalDbPrefix_NP.AsSpan(), StringComparison.OrdinalIgnoreCase))
- {
- return input.ToString();
- }
-
- }
- return null;
+ 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;
}
+
internal static void ReleaseDLLHandles()
{
s_userInstanceDLLHandle = IntPtr.Zero;
@@ -270,7 +261,7 @@ internal static void DemandLocalDBPermissions()
{
if (!_partialTrustFlagChecked)
{
- object partialTrustFlagValue = AppDomain.CurrentDomain.GetData(Const_partialTrustFlagKey);
+ object partialTrustFlagValue = AppDomain.CurrentDomain.GetData(const_partialTrustFlagKey);
if (partialTrustFlagValue != null && partialTrustFlagValue is bool)
{
_partialTrustAllowed = (bool)partialTrustFlagValue;
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
index 92baf05ff2..94edcab2d3 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
@@ -262,7 +262,7 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
break;
case SqlDbType.Date:
case SqlDbType.DateTime2:
- if (smiVersion >= SmiContextFactory.Sql2008Version)
+ if (smiVersion >= SmiContextFactory.KatmaiVersion)
{
goto case SqlDbType.DateTime;
}
@@ -364,11 +364,11 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
}
break;
case SqlDbType.Time:
- if (value.GetType() == typeof(TimeSpan) && smiVersion >= SmiContextFactory.Sql2008Version)
+ if (value.GetType() == typeof(TimeSpan) && smiVersion >= SmiContextFactory.KatmaiVersion)
extendedCode = ExtendedClrTypeCode.TimeSpan;
break;
case SqlDbType.DateTimeOffset:
- if (value.GetType() == typeof(DateTimeOffset) && smiVersion >= SmiContextFactory.Sql2008Version)
+ if (value.GetType() == typeof(DateTimeOffset) && smiVersion >= SmiContextFactory.KatmaiVersion)
extendedCode = ExtendedClrTypeCode.DateTimeOffset;
break;
case SqlDbType.Xml:
@@ -462,8 +462,8 @@ static internal SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCod
return __extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1];
}
- // Infer SqlDbType from Type in the general case. 2008-only (or later) features that need to
- // infer types should use InferSqlDbTypeFromType_2008.
+ // Infer SqlDbType from Type in the general case. Katmai-only (or later) features that need to
+ // infer types should use InferSqlDbTypeFromType_Katmai.
static internal SqlDbType InferSqlDbTypeFromType(Type type)
{
ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type);
@@ -480,12 +480,12 @@ static internal SqlDbType InferSqlDbTypeFromType(Type type)
return returnType;
}
- // Inference rules changed for 2008-or-later-only cases. Only features that are guaranteed to be
- // running against 2008 and don't have backward compat issues should call this code path.
- // example: TVP's are a new 2008 feature (no back compat issues) so can infer DATETIME2
+ // 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.
- static internal SqlDbType InferSqlDbTypeFromType_2008(Type type)
+ static internal SqlDbType InferSqlDbTypeFromType_Katmai(Type type)
{
SqlDbType returnType = InferSqlDbTypeFromType(type);
if (SqlDbType.DateTime == returnType)
@@ -503,8 +503,8 @@ static internal bool IsValidForSmiVersion(SmiExtendedMetaData md, ulong smiVersi
}
else
{
- // 2005 doesn't support Structured nor the new time types
- Debug.Assert(SmiContextFactory.Sql2005Version == smiVersion, "Other versions should have been eliminated during link stage");
+ // Yukon doesn't support Structured nor the new time types
+ Debug.Assert(SmiContextFactory.YukonVersion == smiVersion, "Other versions should have been eliminated during link stage");
return md.SqlDbType != SqlDbType.Structured &&
md.SqlDbType != SqlDbType.Date &&
md.SqlDbType != SqlDbType.DateTime2 &&
@@ -697,7 +697,7 @@ private static CultureInfo GetColumnLocale(DataColumn column)
// Extract metadata for a single DataColumn
static internal SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, DataTable parent)
{
- SqlDbType dbType = InferSqlDbTypeFromType_2008(column.DataType);
+ SqlDbType dbType = InferSqlDbTypeFromType_Katmai(column.DataType);
if (InvalidSqlDbType == dbType)
{
throw SQL.UnsupportedColumnTypeForSqlProvider(column.ColumnName, column.DataType.Name);
@@ -837,7 +837,7 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
throw SQL.NullSchemaTableDataTypeNotSupported(colName);
}
Type colType = (Type)temp;
- SqlDbType colDbType = InferSqlDbTypeFromType_2008(colType);
+ SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType);
if (InvalidSqlDbType == colDbType)
{
// Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise error
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs
index d231fe861a..aadbc0d4b1 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs
@@ -20,11 +20,11 @@ sealed internal class SmiContextFactory
private readonly string _serverVersion;
private readonly SmiEventSink_Default _eventSinkForGetCurrentContext;
- internal const ulong Sql2005Version = 100;
- internal const ulong Sql2008Version = 210;
- internal const ulong LatestVersion = Sql2008Version;
+ internal const ulong YukonVersion = 100;
+ internal const ulong KatmaiVersion = 210;
+ internal const ulong LatestVersion = KatmaiVersion;
- private readonly ulong[] __supportedSmiVersions = new ulong[] { Sql2005Version, Sql2008Version };
+ private readonly ulong[] __supportedSmiVersions = new ulong[] { YukonVersion, KatmaiVersion };
// Used as the key for SmiContext.GetContextValue()
internal enum ContextKey
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/TriggerAction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/TriggerAction.cs
index 1f1b011ee1..bf5a789125 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/TriggerAction.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/TriggerAction.cs
@@ -106,161 +106,161 @@ internal enum EMDEventType
// WHEN ADDING, PLEASE CHECK WITH FILE-OWNER FOR WHICH NUMBERS TO USE. THANKS!
};
- ///
+ ///
public enum TriggerAction
{
- ///
+ ///
Invalid = EMDEventType.x_eet_Invalid,
- ///
+ ///
Insert = EMDEventType.x_eet_Insert,
- ///
+ ///
Update = EMDEventType.x_eet_Update,
- ///
+ ///
Delete = EMDEventType.x_eet_Delete,
- ///
+ ///
CreateTable = EMDEventType.x_eet_Create_Table,
- ///
+ ///
AlterTable = EMDEventType.x_eet_Alter_Table,
- ///
+ ///
DropTable = EMDEventType.x_eet_Drop_Table,
- ///
+ ///
CreateIndex = EMDEventType.x_eet_Create_Index,
- ///
+ ///
AlterIndex = EMDEventType.x_eet_Alter_Index,
- ///
+ ///
DropIndex = EMDEventType.x_eet_Drop_Index,
- ///
+ ///
CreateSynonym = EMDEventType.x_eet_Create_Synonym,
- ///
+ ///
DropSynonym = EMDEventType.x_eet_Drop_Synonym,
- ///
+ ///
CreateSecurityExpression = EMDEventType.x_eet_Create_Secexpr,
- ///
+ ///
DropSecurityExpression = EMDEventType.x_eet_Drop_Secexpr,
- ///
+ ///
CreateView = EMDEventType.x_eet_Create_View,
- ///
+ ///
AlterView = EMDEventType.x_eet_Alter_View,
- ///
+ ///
DropView = EMDEventType.x_eet_Drop_View,
- ///
+ ///
CreateProcedure = EMDEventType.x_eet_Create_Procedure,
- ///
+ ///
AlterProcedure = EMDEventType.x_eet_Alter_Procedure,
- ///
+ ///
DropProcedure = EMDEventType.x_eet_Drop_Procedure,
- ///
+ ///
CreateFunction = EMDEventType.x_eet_Create_Function,
- ///
+ ///
AlterFunction = EMDEventType.x_eet_Alter_Function,
- ///
+ ///
DropFunction = EMDEventType.x_eet_Drop_Function,
- ///
+ ///
CreateTrigger = EMDEventType.x_eet_Create_Trigger,
- ///
+ ///
AlterTrigger = EMDEventType.x_eet_Alter_Trigger,
- ///
+ ///
DropTrigger = EMDEventType.x_eet_Drop_Trigger,
- ///
+ ///
CreateEventNotification = EMDEventType.x_eet_Create_Event_Notification,
- ///
+ ///
DropEventNotification = EMDEventType.x_eet_Drop_Event_Notification,
- ///
+ ///
CreateType = EMDEventType.x_eet_Create_Type,
// Alter_Type = EMDEventType.x_eet_Alter_Type,
- ///
+ ///
DropType = EMDEventType.x_eet_Drop_Type,
- ///
+ ///
CreateAssembly = EMDEventType.x_eet_Create_Assembly,
- ///
+ ///
AlterAssembly = EMDEventType.x_eet_Alter_Assembly,
- ///
+ ///
DropAssembly = EMDEventType.x_eet_Drop_Assembly,
- ///
+ ///
CreateUser = EMDEventType.x_eet_Create_User,
- ///
+ ///
AlterUser = EMDEventType.x_eet_Alter_User,
- ///
+ ///
DropUser = EMDEventType.x_eet_Drop_User,
- ///
+ ///
CreateRole = EMDEventType.x_eet_Create_Role,
- ///
+ ///
AlterRole = EMDEventType.x_eet_Alter_Role,
- ///
+ ///
DropRole = EMDEventType.x_eet_Drop_Role,
- ///
+ ///
CreateAppRole = EMDEventType.x_eet_Create_AppRole,
- ///
+ ///
AlterAppRole = EMDEventType.x_eet_Alter_AppRole,
- ///
+ ///
DropAppRole = EMDEventType.x_eet_Drop_AppRole,
- ///
+ ///
CreateSchema = EMDEventType.x_eet_Create_Schema,
- ///
+ ///
AlterSchema = EMDEventType.x_eet_Alter_Schema,
- ///
+ ///
DropSchema = EMDEventType.x_eet_Drop_Schema,
- ///
+ ///
CreateLogin = EMDEventType.x_eet_Create_Login,
- ///
+ ///
AlterLogin = EMDEventType.x_eet_Alter_Login,
- ///
+ ///
DropLogin = EMDEventType.x_eet_Drop_Login,
- ///
+ ///
CreateMsgType = EMDEventType.x_eet_Create_MsgType,
- ///
+ ///
DropMsgType = EMDEventType.x_eet_Drop_MsgType,
- ///
+ ///
CreateContract = EMDEventType.x_eet_Create_Contract,
- ///
+ ///
DropContract = EMDEventType.x_eet_Drop_Contract,
- ///
+ ///
CreateQueue = EMDEventType.x_eet_Create_Queue,
- ///
+ ///
AlterQueue = EMDEventType.x_eet_Alter_Queue,
- ///
+ ///
DropQueue = EMDEventType.x_eet_Drop_Queue,
- ///
+ ///
CreateService = EMDEventType.x_eet_Create_Service,
- ///
+ ///
AlterService = EMDEventType.x_eet_Alter_Service,
- ///
+ ///
DropService = EMDEventType.x_eet_Drop_Service,
- ///
+ ///
CreateRoute = EMDEventType.x_eet_Create_Route,
- ///
+ ///
AlterRoute = EMDEventType.x_eet_Alter_Route,
- ///
+ ///
DropRoute = EMDEventType.x_eet_Drop_Route,
- ///
+ ///
GrantStatement = EMDEventType.x_eet_Grant_Statement,
- ///
+ ///
DenyStatement = EMDEventType.x_eet_Deny_Statement,
- ///
+ ///
RevokeStatement = EMDEventType.x_eet_Revoke_Statement,
- ///
+ ///
GrantObject = EMDEventType.x_eet_Grant_Object,
- ///
+ ///
DenyObject = EMDEventType.x_eet_Deny_Object,
- ///
+ ///
RevokeObject = EMDEventType.x_eet_Revoke_Object,
- ///
+ ///
CreateBinding = EMDEventType.x_eet_Create_Binding,
- ///
+ ///
AlterBinding = EMDEventType.x_eet_Alter_Binding,
- ///
+ ///
DropBinding = EMDEventType.x_eet_Drop_Binding,
- ///
+ ///
CreatePartitionFunction = EMDEventType.x_eet_Create_Partition_Function,
- ///
+ ///
AlterPartitionFunction = EMDEventType.x_eet_Alter_Partition_Function,
- ///
+ ///
DropPartitionFunction = EMDEventType.x_eet_Drop_Partition_Function,
- ///
+ ///
CreatePartitionScheme = EMDEventType.x_eet_Create_Partition_Scheme,
- ///
+ ///
AlterPartitionScheme = EMDEventType.x_eet_Alter_Partition_Scheme,
- ///
+ ///
DropPartitionScheme = EMDEventType.x_eet_Drop_Partition_Scheme,
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/sqlser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/sqlser.cs
new file mode 100644
index 0000000000..2967aaaa55
--- /dev/null
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/sqlser.cs
@@ -0,0 +1,295 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation 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.IO;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using Microsoft.Data.Common;
+
+namespace Microsoft.Data.SqlClient.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 SerializationHelperSql9.SizeInBytes(t);
+ }
+ else
+ {
+ // In all other formats, the user specifies the maximum size in bytes.
+ return udtInfo.MaxByteSize;
+ }
+ }
+
+ private static object[] GetCustomAttributes(Type t)
+ {
+ object[] attrs = t.GetCustomAttributes(typeof(SqlUserDefinedTypeAttribute), false);
+
+ // If we don't find a Microsoft.Data.SqlClient.Server.SqlUserDefinedTypeAttribute,
+ // search for a Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute from the
+ // old System.Data.SqlClient assembly and copy it to our
+ // Microsoft.Data.SqlClient.Server.SqlUserDefinedTypeAttribute for reference.
+ if (attrs == null || attrs.Length == 0)
+ {
+ object[] attr = t.GetCustomAttributes(false);
+ attrs = new object[0];
+ if (attr != null && attr.Length > 0)
+ {
+ for (int i = 0; i < attr.Length; i++)
+ {
+ if (attr[i].GetType().FullName.Equals("Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute"))
+ {
+ SqlUserDefinedTypeAttribute newAttr = null;
+ PropertyInfo[] sourceProps = attr[i].GetType().GetProperties();
+
+ foreach (PropertyInfo sourceProp in sourceProps)
+ {
+ if (sourceProp.Name.Equals("Format"))
+ {
+ newAttr = new SqlUserDefinedTypeAttribute((Format)sourceProp.GetValue(attr[i], null));
+ break;
+ }
+ }
+ if (newAttr != null)
+ {
+ foreach (PropertyInfo targetProp in newAttr.GetType().GetProperties())
+ {
+ if (targetProp.CanRead && targetProp.CanWrite)
+ {
+ object copyValue = attr[i].GetType().GetProperty(targetProp.Name).GetValue(attr[i]);
+ targetProp.SetValue(newAttr, copyValue);
+ }
+ }
+ }
+
+ attrs = new object[1] { newAttr };
+ break;
+ }
+ }
+ }
+ }
+
+ return attrs;
+ }
+
+ internal static SqlUserDefinedTypeAttribute GetUdtAttribute(Type t)
+ {
+ SqlUserDefinedTypeAttribute udtAttr = null;
+ object[] attr = GetCustomAttributes(t);
+
+ if (attr != null && attr.Length == 1)
+ {
+ udtAttr = (SqlUserDefinedTypeAttribute)attr[0];
+ }
+ else
+ {
+ Type InvalidUdtExceptionType = typeof(InvalidUdtException);
+ var arguments = new Type[] { typeof(Type), typeof(String) };
+ MethodInfo Create = InvalidUdtExceptionType.GetMethod("Create", arguments);
+ Create.Invoke(null, new object[] { t, Strings.SqlUdtReason_NoUdtAttribute });
+ }
+ return udtAttr;
+ }
+
+ // Create a new serializer for the given type.
+ private static Serializer GetNewSerializer(Type t)
+ {
+ SqlUserDefinedTypeAttribute udtAttr = GetUdtAttribute(t);
+
+ switch (udtAttr.Format)
+ {
+ 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(udtAttr.Format);
+ }
+ }
+ }
+
+ // 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 BinaryOrderedUdtNormalizer _normalizer;
+ private bool _isFixedSize;
+ private 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);
+ if (o is Microsoft.SqlServer.Server.IBinarySerialize)
+ {
+ ((SqlServer.Server.IBinarySerialize)o).Write(w);
+ }
+ else
+ {
+ ((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);
+ if (instance is Microsoft.SqlServer.Server.IBinarySerialize)
+ {
+ ((SqlServer.Server.IBinarySerialize)instance).Read(r);
+ }
+ else
+ {
+ ((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(StringsHelper.GetString(Strings.Sql_InternalError));
+ }
+
+ public override bool CanRead => false;
+
+ public override bool CanWrite => true;
+
+ public override bool CanSeek => false;
+
+ public override long Position
+ {
+ get => _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;
+ }
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.cs
new file mode 100644
index 0000000000..9a8550934c
--- /dev/null
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.cs
@@ -0,0 +1,114 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation 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.Linq;
+using System.Runtime.Caching;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Concurrent;
+
+namespace Microsoft.Data.SqlClient
+{
+ internal class SimulatorEnclaveProvider : EnclaveProviderBase
+ {
+ private static readonly int EnclaveSessionHandleSize = 8;
+
+ // When overridden in a derived class, looks up an existing enclave session information in the enclave session cache.
+ // If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter.
+ internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength)
+ {
+ GetEnclaveSessionHelper(enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out customData, out customDataLength);
+ }
+
+ // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave.
+ internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength)
+ {
+ ECDiffieHellmanCng clientDHKey = new ECDiffieHellmanCng(384);
+ clientDHKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
+ clientDHKey.HashAlgorithm = CngAlgorithm.Sha256;
+
+ return new SqlEnclaveAttestationParameters(2, new byte[] { }, clientDHKey);
+ }
+
+ // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache.
+ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellman clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter)
+ {
+ ////for simulator: enclave does not send public key, and sends an empty attestation info
+ //// The only non-trivial content it sends is the session setup info (DH pubkey of enclave)
+
+ sqlEnclaveSession = null;
+ counter = 0;
+ try
+ {
+ ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString());
+ sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter);
+
+ if (sqlEnclaveSession == null)
+ {
+ if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl))
+ {
+ ////Read AttestationInfo
+ int attestationInfoOffset = 0;
+ uint sizeOfTrustedModuleAttestationInfoBuffer = BitConverter.ToUInt32(attestationInfo, attestationInfoOffset);
+ attestationInfoOffset += sizeof(UInt32);
+ int sizeOfTrustedModuleAttestationInfoBufferInt = checked((int)sizeOfTrustedModuleAttestationInfoBuffer);
+ Debug.Assert(sizeOfTrustedModuleAttestationInfoBuffer == 0);
+
+ ////read secure session info
+ uint sizeOfSecureSessionInfoResponse = BitConverter.ToUInt32(attestationInfo, attestationInfoOffset);
+ attestationInfoOffset += sizeof(UInt32);
+
+ byte[] enclaveSessionHandle = new byte[EnclaveSessionHandleSize];
+ Buffer.BlockCopy(attestationInfo, attestationInfoOffset, enclaveSessionHandle, 0, EnclaveSessionHandleSize);
+ attestationInfoOffset += EnclaveSessionHandleSize;
+
+ uint sizeOfTrustedModuleDHPublicKeyBuffer = BitConverter.ToUInt32(attestationInfo, attestationInfoOffset);
+ attestationInfoOffset += sizeof(UInt32);
+ uint sizeOfTrustedModuleDHPublicKeySignatureBuffer = BitConverter.ToUInt32(attestationInfo, attestationInfoOffset);
+ attestationInfoOffset += sizeof(UInt32);
+ int sizeOfTrustedModuleDHPublicKeyBufferInt = checked((int)sizeOfTrustedModuleDHPublicKeyBuffer);
+
+ byte[] trustedModuleDHPublicKey = new byte[sizeOfTrustedModuleDHPublicKeyBuffer];
+ Buffer.BlockCopy(attestationInfo, attestationInfoOffset, trustedModuleDHPublicKey, 0,
+ sizeOfTrustedModuleDHPublicKeyBufferInt);
+ attestationInfoOffset += sizeOfTrustedModuleDHPublicKeyBufferInt;
+
+ byte[] trustedModuleDHPublicKeySignature = new byte[sizeOfTrustedModuleDHPublicKeySignatureBuffer];
+ Buffer.BlockCopy(attestationInfo, attestationInfoOffset, trustedModuleDHPublicKeySignature, 0,
+ checked((int)sizeOfTrustedModuleDHPublicKeySignatureBuffer));
+
+ byte[] sharedSecret;
+ using ECDiffieHellman ecdh = KeyConverter.CreateECDiffieHellmanFromPublicKeyBlob(trustedModuleDHPublicKey);
+ sharedSecret = KeyConverter.DeriveKey(clientDHKey, ecdh.PublicKey);
+ long sessionId = BitConverter.ToInt64(enclaveSessionHandle, 0);
+ sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, sessionId, out counter);
+ }
+ else
+ {
+ throw new AlwaysEncryptedAttestationException(Strings.FailToCreateEnclaveSession);
+ }
+ }
+ }
+ finally
+ {
+ UpdateEnclaveSessionLockStatus(sqlEnclaveSession);
+ }
+ }
+
+ ///
+ /// When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching.
+ ///
+ /// The set of parameters required for enclave session.
+ /// The session to be invalidated.
+ internal override void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate)
+ {
+ InvalidateEnclaveSessionHelper(enclaveSessionParameters, enclaveSessionToInvalidate);
+ }
+ }
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBuffer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBuffer.cs
index f2d332c95f..36c0df16d3 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBuffer.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBuffer.cs
@@ -24,7 +24,6 @@ internal enum StorageType
Int16,
Int32,
Int64,
- Guid,
Money,
Single,
String,
@@ -95,8 +94,6 @@ internal struct Storage
[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;
@@ -126,7 +123,7 @@ private SqlBuffer(SqlBuffer value)
_object = value._object;
}
- internal bool IsEmpty => _type == StorageType.Empty;
+ internal bool IsEmpty => StorageType.Empty == _type;
internal bool IsNull => _isNull;
@@ -219,16 +216,16 @@ internal decimal Decimal
// Only removing trailing zeros from a decimal part won't hit its value!
if (_value._numericInfo._scale > 0)
{
- int zeroCnt = FindTrailingZerosAndPrec((uint)_value._numericInfo._data1, (uint)_value._numericInfo._data2,
- (uint)_value._numericInfo._data3, (uint)_value._numericInfo._data4,
+ int zeroCnt = FindTrailingZerosAndPrec((uint)_value._numericInfo._data1, (uint)_value._numericInfo._data2,
+ (uint)_value._numericInfo._data3, (uint)_value._numericInfo._data4,
_value._numericInfo._scale, out int precision);
int minScale = _value._numericInfo._scale - zeroCnt; // minimum possible sacle after removing the trailing zeros.
if (zeroCnt > 0 && minScale <= 28 && precision <= 29)
{
- SqlDecimal sqlValue = new(_value._numericInfo._precision, _value._numericInfo._scale, _value._numericInfo._positive,
- _value._numericInfo._data1, _value._numericInfo._data2,
+ SqlDecimal sqlValue = new(_value._numericInfo._precision, _value._numericInfo._scale, _value._numericInfo._positive,
+ _value._numericInfo._data1, _value._numericInfo._data2,
_value._numericInfo._data3, _value._numericInfo._data4);
int integral = precision - minScale;
@@ -376,23 +373,9 @@ internal Guid Guid
{
get
{
+ // TODO: It is possible to further optimize this, by storing the data from the wire without constructing a SqlGuid first, however we're already twice as fast!
ThrowIfNull();
- if (StorageType.Guid == _type)
- {
- return _value._guid;
- }
- else if (StorageType.SqlGuid == _type)
- {
- return ((SqlGuid)_object).Value;
- }
- return (Guid)Value;
- }
- set
- {
- Debug.Assert(IsEmpty, "setting value a second time?");
- _type = StorageType.Guid;
- _value._guid = value;
- _isNull = false;
+ return SqlGuid.Value;
}
}
@@ -498,8 +481,8 @@ internal string String
}
}
- // use static list of format strings indexed by scale for perf
- private static readonly string[] s_sql2008DateTimeOffsetFormatByScale = new string[] {
+ // 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",
@@ -510,7 +493,7 @@ internal string String
"yyyy-MM-dd HH:mm:ss.fffffff zzz",
};
- private static readonly string[] s_sql2008DateTime2FormatByScale = new string[] {
+ 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",
@@ -521,7 +504,7 @@ internal string String
"yyyy-MM-dd HH:mm:ss.fffffff",
};
- private static readonly string[] s_sql2008TimeFormatByScale = new string[] {
+ private static readonly string[] s_katmaiTimeFormatByScale = new string[] {
"HH:mm:ss",
"HH:mm:ss.f",
"HH:mm:ss.ff",
@@ -532,7 +515,7 @@ internal string String
"HH:mm:ss.fffffff",
};
- internal string Sql2008DateTimeString
+ internal string KatmaiDateTimeString
{
get
{
@@ -545,24 +528,24 @@ internal string Sql2008DateTimeString
if (StorageType.Time == _type)
{
byte scale = _value._timeInfo._scale;
- return new DateTime(_value._timeInfo._ticks).ToString(s_sql2008TimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
+ return new DateTime(_value._timeInfo._ticks).ToString(s_katmaiTimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
if (StorageType.DateTime2 == _type)
{
byte scale = _value._dateTime2Info._timeInfo._scale;
- return DateTime.ToString(s_sql2008DateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
+ return DateTime.ToString(s_katmaiDateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
if (StorageType.DateTimeOffset == _type)
{
DateTimeOffset dto = DateTimeOffset;
byte scale = _value._dateTimeOffsetInfo._dateTime2Info._timeInfo._scale;
- return dto.ToString(s_sql2008DateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
+ return dto.ToString(s_katmaiDateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
return (string)Value; // anything else we haven't thought of goes through boxing.
}
}
- internal SqlString Sql2008DateTimeSqlString
+ internal SqlString KatmaiDateTimeSqlString
{
get
{
@@ -575,7 +558,7 @@ internal SqlString Sql2008DateTimeSqlString
{
return SqlString.Null;
}
- return new SqlString(Sql2008DateTimeString);
+ return new SqlString(KatmaiDateTimeString);
}
return (SqlString)SqlValue; // anything else we haven't thought of goes through boxing.
}
@@ -774,13 +757,9 @@ internal SqlGuid SqlGuid
{
get
{
- if (StorageType.Guid == _type)
+ if (StorageType.SqlGuid == _type)
{
- return new SqlGuid(_value._guid);
- }
- else if (StorageType.SqlGuid == _type)
- {
- return IsNull ? SqlGuid.Null : (SqlGuid)_object;
+ return (SqlGuid)_object;
}
return (SqlGuid)SqlValue; // anything else we haven't thought of goes through boxing.
}
@@ -922,8 +901,6 @@ internal object SqlValue
return SqlInt32;
case StorageType.Int64:
return SqlInt64;
- case StorageType.Guid:
- return SqlGuid;
case StorageType.Money:
return SqlMoney;
case StorageType.Single:
@@ -979,10 +956,6 @@ internal object SqlValue
}
}
-
- // these variables store pre-boxed bool values to be used when returning a boolean
- // in a object typed location, if these are not used a new value is boxed each time
- // one is needed which leads to a lot of garbage which needs to be collected
private static readonly object s_cachedTrueObject = true;
private static readonly object s_cachedFalseObject = false;
@@ -999,7 +972,7 @@ internal object Value
case StorageType.Empty:
return DBNull.Value;
case StorageType.Boolean:
- return Boolean ? s_cachedTrueObject : s_cachedFalseObject; // return pre-boxed values for perf
+ return Boolean ? s_cachedTrueObject : s_cachedFalseObject;
case StorageType.Byte:
return Byte;
case StorageType.DateTime:
@@ -1014,8 +987,6 @@ internal object Value
return Int32;
case StorageType.Int64:
return Int64;
- case StorageType.Guid:
- return Guid;
case StorageType.Money:
return Decimal;
case StorageType.Single:
@@ -1077,8 +1048,6 @@ internal Type GetTypeFromStorageType(bool isSqlType)
return typeof(SqlInt32);
case StorageType.Int64:
return typeof(SqlInt64);
- case StorageType.Guid:
- return typeof(SqlGuid);
case StorageType.Money:
return typeof(SqlMoney);
case StorageType.Single:
@@ -1118,8 +1087,6 @@ internal Type GetTypeFromStorageType(bool isSqlType)
return typeof(int);
case StorageType.Int64:
return typeof(long);
- case StorageType.Guid:
- return typeof(Guid);
case StorageType.Money:
return typeof(decimal);
case StorageType.Single:
@@ -1342,59 +1309,5 @@ private void ThrowIfNull()
throw new SqlNullValueException();
}
}
- // [Field]As 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 recognize 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
- // generated assembly will be short and direct
- // 2) another jit may not recognize 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 no conversions are used and this will generate the desired InvalidCastException
- // for example users cannot widen a short to an int preserving external expectations
-
- internal T ByteAs()
- {
- ThrowIfNull();
- return (T)(object)_value._byte;
- }
-
- internal T BooleanAs()
- {
- ThrowIfNull();
- return (T)(object)_value._boolean;
- }
-
- internal T Int32As()
- {
- ThrowIfNull();
- return (T)(object)_value._int32;
- }
-
- internal T Int16As()
- {
- ThrowIfNull();
- return (T)(object)_value._int16;
- }
-
- internal T Int64As()
- {
- ThrowIfNull();
- return (T)(object)_value._int64;
- }
-
- internal T DoubleAs()
- {
- ThrowIfNull();
- return (T)(object)_value._double;
- }
-
- internal T SingleAs()
- {
- ThrowIfNull();
- return (T)(object)_value._single;
- }
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs
index 81ccfb570a..3a2f91e7e7 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs
@@ -436,16 +436,16 @@ private string CreateInitialQuery()
string TDSCommand;
TDSCommand = "select @@trancount; SET FMTONLY ON select * from " + ADP.BuildMultiPartName(parts) + " SET FMTONLY OFF ";
- if (_connection.Is2000)
+ if (_connection.IsShiloh)
{
// If its a temp DB then try to connect
string TableCollationsStoredProc;
- if (_connection.Is2008OrNewer)
+ if (_connection.IsKatmaiOrNewer)
{
TableCollationsStoredProc = "sp_tablecollations_100";
}
- else if (_connection.Is2005OrNewer)
+ else if (_connection.IsYukonOrNewer)
{
TableCollationsStoredProc = "sp_tablecollations_90";
}
@@ -546,7 +546,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i
StringBuilder updateBulkCommandText = new StringBuilder();
- if (_connection.Is2000 && 0 == internalResults[CollationResultId].Count)
+ if (_connection.IsShiloh && 0 == internalResults[CollationResultId].Count)
{
throw SQL.BulkLoadNoCollation();
}
@@ -559,7 +559,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i
bool isInTransaction;
- if (_parser.Is2005OrNewer)
+ if (_parser.IsYukonOrNewer)
{
isInTransaction = _connection.HasLocalTransaction;
}
@@ -683,9 +683,9 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i
}
}
- if (_connection.Is2000)
+ if (_connection.IsShiloh)
{
- // 2000 or above!
+ // Shiloh or above!
// get collation for column i
Result rowset = internalResults[CollationResultId];
@@ -2288,7 +2288,7 @@ private Task ReadWriteColumnValueAsync(int col)
// Target type shouldn't be encrypted
Debug.Assert(!metadata.isEncrypted, "Can't encrypt SQL Variant type");
SqlBuffer.StorageType variantInternalType = SqlBuffer.StorageType.Empty;
- if ((_sqlDataReaderRowSource != null) && (_connection.Is2008OrNewer))
+ if ((_sqlDataReaderRowSource != null) && (_connection.IsKatmaiOrNewer))
{
variantInternalType = _sqlDataReaderRowSource.GetVariantInternalStorageType(_sortedColumnMappings[col]._sourceColumnOrdinal);
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs
index 8c497f90d2..2d8b080be7 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs
@@ -15,23 +15,23 @@
namespace Microsoft.Data.SqlClient
{
- ///
+ ///
[Serializable]
public sealed class SqlClientPermission : System.Data.Common.DBDataPermission
{
- ///
+ ///
[Obsolete("SqlClientPermission() has been deprecated. Use the SqlClientPermission(PermissionState.None) constructor. http://go.microsoft.com/fwlink/?linkid=14202", true)] // MDAC 86034
public SqlClientPermission() : this(PermissionState.None)
{
}
- ///
+ ///
public SqlClientPermission(PermissionState state) : base(state)
{
}
- ///
+ ///
[Obsolete("SqlClientPermission(PermissionState state, Boolean allowBlankPassword) has been deprecated. Use the SqlClientPermission(PermissionState.None) constructor. http://go.microsoft.com/fwlink/?linkid=14202", true)] // MDAC 86034
public SqlClientPermission(PermissionState state, bool allowBlankPassword) : this(state)
{
@@ -61,14 +61,14 @@ internal SqlClientPermission(SqlConnectionString constr) : base(PermissionState.
}
}
- ///
+ ///
public override void Add(string connectionString, string restrictions, KeyRestrictionBehavior behavior)
{
DBConnectionString constr = new DBConnectionString(connectionString, restrictions, behavior, SqlConnectionString.GetParseSynonyms(), false);
AddPermissionEntry(constr);
}
- ///
+ ///
override public IPermission Copy()
{
return new SqlClientPermission(this);
@@ -126,7 +126,7 @@ private void CopyFrom(SqlClientPermission permission)
}
}
- ///
+ ///
override public IPermission Intersect(IPermission target)
{ // used during Deny actions
if (null == target)
@@ -179,7 +179,7 @@ private bool IsEmpty()
return flag;
}
- ///
+ ///
override public bool IsSubsetOf(IPermission target)
{
if (null == target)
@@ -218,7 +218,7 @@ override public bool IsSubsetOf(IPermission target)
return subset;
}
- ///
+ ///
override public IPermission Union(IPermission target)
{
if (null == target)
@@ -281,7 +281,7 @@ private string EncodeXmlValue(string value)
//
//
//
- ///
+ ///
override public void FromXml(SecurityElement securityElement)
{
// code derived from CodeAccessPermission.ValidateElement
@@ -344,7 +344,7 @@ override public void FromXml(SecurityElement securityElement)
//
//
//
- ///
+ ///
override public SecurityElement ToXml()
{
Type type = this.GetType();
@@ -410,18 +410,18 @@ private static class XmlStr
}
- ///
+ ///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
[Serializable]
public sealed class SqlClientPermissionAttribute : DBDataPermissionAttribute
{
- ///
+ ///
public SqlClientPermissionAttribute(SecurityAction action) : base(action)
{
}
- ///
+ ///
override public IPermission CreatePermission()
{
return new SqlClientPermission(this);
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.cs
index e8dca4c858..bbe7e2f76b 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.cs
@@ -10,7 +10,7 @@
namespace Microsoft.Data.SqlClient
{
- ///
+ ///
public class SqlColumnEncryptionCertificateStoreProvider : SqlColumnEncryptionKeyStoreProvider
{
// Constants
@@ -18,7 +18,7 @@ public class SqlColumnEncryptionCertificateStoreProvider : SqlColumnEncryptionKe
// Assumption: Certificate Locations (LocalMachine & CurrentUser), Certificate Store name "My"
// Certificate provider name (CertificateStore) dont need to be localized.
- ///
+ ///
public const string ProviderName = @"MSSQL_CERTIFICATE_STORE";
///
@@ -56,7 +56,7 @@ public class SqlColumnEncryptionCertificateStoreProvider : SqlColumnEncryptionKe
///
private readonly byte[] _version = new byte[] { 0x01 };
- ///
+ ///
public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string encryptionAlgorithm, byte[] encryptedColumnEncryptionKey)
{
// Validate the input parameters
@@ -150,7 +150,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e
return RSADecrypt(cipherText, certificate);
}
- ///
+ ///
public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string encryptionAlgorithm, byte[] columnEncryptionKey)
{
// Validate the input parameters
@@ -240,7 +240,7 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e
return encryptedColumnEncryptionKey;
}
- ///
+ ///
public override byte[] SignColumnMasterKeyMetadata(string masterKeyPath, bool allowEnclaveComputations)
{
var hash = ComputeMasterKeyMetadataHash(masterKeyPath, allowEnclaveComputations, isSystemOp: false);
@@ -253,7 +253,7 @@ public override byte[] SignColumnMasterKeyMetadata(string masterKeyPath, bool al
return signature;
}
- ///
+ ///
public override bool VerifyColumnMasterKeyMetadata(string masterKeyPath, bool allowEnclaveComputations, byte[] signature)
{
var hash = ComputeMasterKeyMetadataHash(masterKeyPath, allowEnclaveComputations, isSystemOp: true);
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs
index ad84233197..bded38eeee 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs
@@ -9,10 +9,10 @@
namespace Microsoft.Data.SqlClient
{
- ///
+ ///
public class SqlColumnEncryptionCngProvider : SqlColumnEncryptionKeyStoreProvider
{
- ///
+ ///
public const string ProviderName = @"MSSQL_CNG_STORE";
///
@@ -26,7 +26,7 @@ public class SqlColumnEncryptionCngProvider : SqlColumnEncryptionKeyStoreProvide
///
private readonly byte[] _version = new byte[] { 0x01 };
- ///
+ ///
public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string encryptionAlgorithm, byte[] encryptedColumnEncryptionKey)
{
// Validate the input parameters
@@ -120,7 +120,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e
return RSADecrypt(rsaCngProvider, cipherText);
}
- ///
+ ///
public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string encryptionAlgorithm, byte[] columnEncryptionKey)
{
// Validate the input parameters
@@ -210,13 +210,13 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e
return encryptedColumnEncryptionKey;
}
- ///
+ ///
public override byte[] SignColumnMasterKeyMetadata(string masterKeyPath, bool allowEnclaveComputations)
{
throw new NotSupportedException();
}
- ///
+ ///
public override bool VerifyColumnMasterKeyMetadata(string masterKeyPath, bool allowEnclaveComputations, byte[] signature)
{
throw new NotSupportedException();
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs
index 6296d4005d..33996913c2 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs
@@ -10,10 +10,10 @@
namespace Microsoft.Data.SqlClient
{
- ///
+ ///
public class SqlColumnEncryptionCspProvider : SqlColumnEncryptionKeyStoreProvider
{
- ///
+ ///
public const string ProviderName = @"MSSQL_CSP_PROVIDER";
///
@@ -30,7 +30,7 @@ public class SqlColumnEncryptionCspProvider : SqlColumnEncryptionKeyStoreProvide
///
private readonly byte[] _version = new byte[] { 0x01 };
- ///
+ ///
public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string encryptionAlgorithm, byte[] encryptedColumnEncryptionKey)
{
// Validate the input parameters
@@ -124,7 +124,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e
return RSADecrypt(rsaProvider, cipherText);
}
- ///
+ ///
public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string encryptionAlgorithm, byte[] columnEncryptionKey)
{
// Validate the input parameters
@@ -214,13 +214,13 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e
return encryptedColumnEncryptionKey;
}
- ///
+ ///
public override byte[] SignColumnMasterKeyMetadata(string masterKeyPath, bool allowEnclaveComputations)
{
throw new NotSupportedException();
}
- ///
+ ///
public override bool VerifyColumnMasterKeyMetadata(string masterKeyPath, bool allowEnclaveComputations, byte[] signature)
{
throw new NotSupportedException();
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs
index 1658944d87..35f5353f89 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs
@@ -86,9 +86,9 @@ public sealed class SqlCommand : DbCommand, ICloneable
internal static readonly Action