diff --git a/docs/core/compatibility/10.md b/docs/core/compatibility/10.md index 09f17c2d897e3..1e04f639dbd39 100644 --- a/docs/core/compatibility/10.md +++ b/docs/core/compatibility/10.md @@ -43,6 +43,7 @@ See [Breaking changes in ASP.NET Core 10](/aspnet/core/breaking-changes/10/overv | [GnuTarEntry and PaxTarEntry no longer includes atime and ctime by default](core-libraries/10.0/tar-atime-ctime-default.md) | Behavioral change | | [LDAP DirectoryControl parsing is now more stringent](core-libraries/10.0/ldap-directorycontrol-parsing.md) | Behavioral change | | [MacCatalyst version normalization](core-libraries/10.0/maccatalyst-version-normalization.md) | Behavioral change | +| [Named mutexes default to user scope on Unix](core-libraries/11/named-mutexes-unix-default-scope.md) | Behavioral change | | [.NET runtime no longer provides default termination signal handlers](core-libraries/10.0/sigterm-signal-handler.md) | Behavioral change | | [System.Linq.AsyncEnumerable included in core libraries](core-libraries/10.0/asyncenumerable.md) | Source incompatible | | [Type.MakeGenericSignatureType argument validation](reflection/10/makegeneric-signaturetype-validation.md) | Behavioral change | diff --git a/docs/core/compatibility/11.md b/docs/core/compatibility/11.md index 084299dc70493..4d9e13554d17a 100644 --- a/docs/core/compatibility/11.md +++ b/docs/core/compatibility/11.md @@ -32,6 +32,7 @@ See [Breaking changes in ASP.NET Core 11](/aspnet/core/breaking-changes/11/overv | [Environment.GetCommandLineArgs()[0] preserves the apphost invocation name](core-libraries/11/environment-getcommandlineargs-apphost-invocation-name.md) | Behavioral change | | [Environment.TickCount made consistent with Windows timeout behavior](core-libraries/11/environment-tickcount-windows-behavior.md) | Behavioral change | | [Math.Round and MathF.Round return correctly rounded results](core-libraries/11/math-round-digits.md) | Behavioral change | +| [Named mutexes default to user scope on Unix](core-libraries/11/named-mutexes-unix-default-scope.md) | Behavioral change | | [NamedPipeServerStream with PipeOptions.CurrentUserOnly tightens Unix socket file permissions](core-libraries/11/namedpipeserverstream-unix-permissions.md) | Behavioral change | | [Nullable.GetUnderlyingType throws for custom Type subclasses](core-libraries/11/nullable-getunderlyingtype-throws.md) | Behavioral change | | [PackagePart.GetStream() returns a non-seekable stream for compressed parts in ReadWrite packages](core-libraries/11/packagepart-getstream-non-seekable.md) | Behavioral change | diff --git a/docs/core/compatibility/8.0.md b/docs/core/compatibility/8.0.md index 61f1d47a9f262..d34632ad97067 100644 --- a/docs/core/compatibility/8.0.md +++ b/docs/core/compatibility/8.0.md @@ -49,6 +49,7 @@ See [Breaking changes in ASP.NET Core 8](/aspnet/core/breaking-changes/8/overvie | [LDAP APIs not available on .NET Standard / .NET Framework](core-libraries/8.0/ldap-netstandard-apis.md) | Binary incompatible | | [Legacy Console.ReadKey removed](core-libraries/8.0/console-readkey-legacy.md) | Behavioral change | | [Method builders generate parameters with HasDefaultValue set to false](core-libraries/8.0/parameterinfo-hasdefaultvalue.md) | Behavioral change | +| [Named mutexes default to user scope on Unix](core-libraries/11/named-mutexes-unix-default-scope.md) | Behavioral change | | [Package part URIs are now compared case-insensitively in System.IO.Packaging](core-libraries/8.0/system-io-packaging-case-insensitive-uri.md) | Behavioral change | | [ProcessStartInfo.WindowStyle honored when UseShellExecute is false](core-libraries/8.0/processstartinfo-windowstyle.md) | Behavioral change | | [RuntimeIdentifier returns platform for which runtime was built](core-libraries/8.0/runtimeidentifier.md) | Behavioral change | diff --git a/docs/core/compatibility/9.0.md b/docs/core/compatibility/9.0.md index 98a7ca278b8f4..85f6a3cff569d 100644 --- a/docs/core/compatibility/9.0.md +++ b/docs/core/compatibility/9.0.md @@ -40,6 +40,7 @@ See [Breaking changes in ASP.NET Core 9](/aspnet/core/breaking-changes/9/overvie | [IncrementingPollingCounter initial callback is asynchronous](core-libraries/9.0/async-callback.md) | Behavioral change | RC 1 | | [Inline array struct size limit is enforced](core-libraries/9.0/inlinearray-size.md) | Behavioral change | Preview 1 | | [InMemoryDirectoryInfo prepends rootDir to files](core-libraries/9.0/inmemorydirinfo-prepends-rootdir.md) | Behavioral change | Preview 1 | +| [Named mutexes default to user scope on Unix](core-libraries/11/named-mutexes-unix-default-scope.md) | Behavioral change | 9.0.21 | | [New TimeSpan.From*() overloads that take integers](core-libraries/9.0/timespan-from-overloads.md) | Source incompatible | Preview 3 | | [New version of some OOB packages](core-libraries/9.0/oob-packages.md) | Source incompatible | Preview 5 | | [RuntimeHelpers.GetSubArray returns different type](core-libraries/9.0/getsubarray-return.md) | Behavioral change | Preview 1 | diff --git a/docs/core/compatibility/core-libraries/11/named-mutexes-unix-default-scope.md b/docs/core/compatibility/core-libraries/11/named-mutexes-unix-default-scope.md new file mode 100644 index 0000000000000..cd633baa1de2f --- /dev/null +++ b/docs/core/compatibility/core-libraries/11/named-mutexes-unix-default-scope.md @@ -0,0 +1,46 @@ +--- +title: "Breaking change: Named mutexes default to user scope on Unix" +description: "Learn about the breaking change in .NET 8, .NET 9, .NET 10, and .NET 11 where named mutexes on Unix default to user scope." +ms.date: 10/14/2026 +ai-usage: ai-assisted +--- + +# Named mutexes default to user scope on Unix + +Named mutexes on Unix now default to user scope instead of global scope. This change affects .NET 8.0.32, .NET 9.0.21, .NET 10.0.13, and .NET 11 RC 2. + +## Version introduced + +.NET 11 RC 2, .NET 10.0.13, .NET 9.0.21, and .NET 8.0.32 + +## Previous behavior + +Previously, named mutexes on Unix were globally scoped by default, so processes run by different users could share them. User-scoped mutexes were available through constructors that accept , starting in .NET 10. Those mutexes were stored in a subdirectory of `/tmp/`. + +## New behavior + +Named mutexes on Unix now default to user scope. The runtime stores user-scoped mutex backing files in `$TMPDIR` on platforms where it's a per-user directory, such as macOS. Otherwise, it uses `$XDG_RUNTIME_DIR` if set. If neither directory is available, it uses a directory under the current user's home directory as defined in the user database, such as `/etc/passwd`; it doesn't use `$HOME`. + +## Type of breaking change + +This change is a [behavioral change](../../categories.md#behavioral-change). + +## Reason for change + +To improve security, named mutexes now default to a scope and storage location that restrict access to the current user. The previous `/tmp/` backing files could allow another user on the system to interfere with a named mutex. For more information, see [dotnet/docs issue #56396](https://github.com/dotnet/docs/issues/56396). + +## Recommended action + +If your named mutexes do not need cross-user access and your application can access the user-only directory for its platform, no change is required. + +If your named mutexes need cross-user access, use a constructor that accepts on .NET 10 or later and pass `NamedWaitHandleOptions.None` to opt into global scope. Alternatively, set the `System.Threading.Mutex.UnsafeDefaultMutexScopeGlobal` runtime configuration option to `true` in your `runtimeconfig.json`. This option applies on all affected platforms. + +If your process runs as a UID with no user database entry, named mutex creation fails. This situation is common in containers started with `docker run -u ` or Kubernetes `runAsUser`. Set `XDG_RUNTIME_DIR` to a writable directory owned by that user, or create a user account for the UID in the container image. + +## Affected APIs + +- +- +- +- +- diff --git a/docs/core/compatibility/toc.yml b/docs/core/compatibility/toc.yml index d9bc66bcea144..d39106c33dd8f 100644 --- a/docs/core/compatibility/toc.yml +++ b/docs/core/compatibility/toc.yml @@ -30,6 +30,8 @@ items: href: core-libraries/11/environment-tickcount-windows-behavior.md - name: Math.Round and MathF.Round return correctly rounded results href: core-libraries/11/math-round-digits.md + - name: Named mutexes default to user scope on Unix + href: core-libraries/11/named-mutexes-unix-default-scope.md - name: NamedPipeServerStream with PipeOptions.CurrentUserOnly tightens Unix socket file permissions href: core-libraries/11/namedpipeserverstream-unix-permissions.md - name: Nullable.GetUnderlyingType throws for custom Type subclasses @@ -168,6 +170,8 @@ items: href: core-libraries/10.0/ldap-directorycontrol-parsing.md - name: MacCatalyst version normalization href: core-libraries/10.0/maccatalyst-version-normalization.md + - name: Named mutexes default to user scope on Unix + href: core-libraries/11/named-mutexes-unix-default-scope.md - name: No default termination signal handlers href: core-libraries/10.0/sigterm-signal-handler.md - name: System.Linq.AsyncEnumerable included in core libraries @@ -358,6 +362,8 @@ items: href: core-libraries/9.0/inlinearray-size.md - name: InMemoryDirectoryInfo prepends rootDir to files href: core-libraries/9.0/inmemorydirinfo-prepends-rootdir.md + - name: Named mutexes default to user scope on Unix + href: core-libraries/11/named-mutexes-unix-default-scope.md - name: New TimeSpan.From*() overloads that take integers href: core-libraries/9.0/timespan-from-overloads.md - name: New version of some OOB packages @@ -524,6 +530,8 @@ items: href: core-libraries/8.0/ldap-netstandard-apis.md - name: Method builders generate parameters with HasDefaultValue=false href: core-libraries/8.0/parameterinfo-hasdefaultvalue.md + - name: Named mutexes default to user scope on Unix + href: core-libraries/11/named-mutexes-unix-default-scope.md - name: Package part URIs are now compared case-insensitively in System.IO.Packaging href: core-libraries/8.0/system-io-packaging-case-insensitive-uri.md - name: ProcessStartInfo.WindowStyle honored when UseShellExecute is false diff --git a/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md b/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md index 2ed5e3472a9a3..ebc06ba199ee5 100644 --- a/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md +++ b/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md @@ -279,7 +279,7 @@ public static void TestCars1() // used in the definition of ShowDetails in the ConvertibleCar // class. - Car car2 = new ConvertibleCar(); + ConvertibleCar car2 = new ConvertibleCar(); car2.DescribeCar(); System.Console.WriteLine("----------"); diff --git a/docs/framework/data/adonet/ado-net-code-examples.md b/docs/framework/data/adonet/ado-net-code-examples.md index 468056a94db0b..d6fff055dabce 100644 --- a/docs/framework/data/adonet/ado-net-code-examples.md +++ b/docs/framework/data/adonet/ado-net-code-examples.md @@ -1,7 +1,8 @@ --- -title: "Code examples" -description: "These examples show .NET Framework programmers how to retrieve data from a database by using ADO.NET data providers and ADO.NET Entity Framework." -ms.date: "03/30/2017" +title: "Code Examples" +description: "Retrieve data with ADO.NET data providers, including Microsoft.Data.SqlClient for SQL Server, and explore .NET Framework Entity Framework examples." +ms.date: "10/19/2026" +ai-usage: ai-assisted dev_langs: - "csharp" - "vb" @@ -13,7 +14,7 @@ The code listings on this page demonstrate how to retrieve data from a database - ADO.NET data providers: - - [SqlClient](#sqlclient) (`System.Data.SqlClient`) + - [SqlClient](#sqlclient) (`Microsoft.Data.SqlClient`) - [OleDb](#oledb) (`System.Data.OleDb`) @@ -37,12 +38,26 @@ The following code listings demonstrate how to retrieve data from a database usi ### SqlClient -The code in this example assumes that you can connect to the `Northwind` sample database on Microsoft SQL Server. The code creates a to select rows from the Products table, adding a to restrict the results to rows with a UnitPrice greater than the specified parameter value, in this case 5. The is opened inside a `using` block, which ensures that resources are closed and disposed when the code exits. The code executes the command by using a , and displays the results in the console window. If you're using `System.Data.SqlClient`, you should consider upgrading to `Microsoft.Data.SqlClient` as it's where future investments and new feature developments are being made. For more information, see [Introducing the new Microsoft.Data.SqlClient](https://devblogs.microsoft.com/dotnet/introducing-the-new-microsoftdatasqlclient). +To access SQL Server with ADO.NET, use the [Microsoft.Data.SqlClient](https://www.nuget.org/packages/Microsoft.Data.SqlClient) NuGet package. The following C# and Visual Basic projects target .NET 10 and .NET Framework 4.8.1 and reference this package. Use the .NET 10 SDK to build the projects. + +The examples query the `dbo.Products` table in the `Northwind` sample database. The selects products with `UnitPrice` greater than 5. The specifies the price as . The reads the product ID, unit price, and product name in descending order of unit price. The `using` blocks (`Using` in Visual Basic) dispose of the reader, command, and . + +Before you run either project, set the `SQL_CONNECTION_STRING` environment variable in the process that launches the example. For example, on Windows with integrated authentication, use the following PowerShell command. Replace `` with your server name and configure the server with a certificate that the client trusts. + +```powershell +$env:SQL_CONNECTION_STRING = 'Server=;Database=Northwind;Integrated Security=true;Encrypt=true;TrustServerCertificate=false' +``` + +For other authentication options, see [Connection string syntax](/sql/connect/ado-net/connection-string-syntax). [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] - [!code-csharp[DataWorks SampleApp.SqlClient#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs#1)] - [!code-vb[DataWorks SampleApp.SqlClient#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/VB/source.vb#1)] +To use the driver's Microsoft Entra ID authentication modes, including managed identity, also install the `Microsoft.Data.SqlClient.Extensions.Azure` NuGet package. For setup instructions, see [Microsoft Entra ID authentication](/sql/connect/ado-net/sql/azure-active-directory-authentication). + +:::code language="csharp" source="./snippets/ado-net-code-examples/csharp/Program.cs" id="SqlClient"::: +:::code language="vb" source="./snippets/ado-net-code-examples/vb/Program.vb" id="SqlClient"::: + +From either snippet project directory, run `dotnet run --framework net10.0`. On Windows with .NET Framework 4.8.1 installed, use `dotnet run --framework net481`. ### OleDb diff --git a/docs/framework/data/adonet/ado-net-overview.md b/docs/framework/data/adonet/ado-net-overview.md index a9c7b58111005..f04f4e872bb1a 100644 --- a/docs/framework/data/adonet/ado-net-overview.md +++ b/docs/framework/data/adonet/ado-net-overview.md @@ -1,16 +1,19 @@ --- title: "Overview" description: Read an overview of ADO.NET in .NET Framework and read about resources for more detailed explanations and examples. -ms.date: "03/30/2017" +ms.date: "10/19/2026" +ai-usage: ai-assisted ms.assetid: ee3bc1d8-11db-4be4-89eb-c708cf04117d --- # ADO.NET Overview ADO.NET provides consistent access to data sources such as SQL Server and XML, and to data sources exposed through OLE DB and ODBC. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, handle, and update the data that they contain. + +For new SQL Server applications, use the [Microsoft.Data.SqlClient](https://www.nuget.org/packages/Microsoft.Data.SqlClient) NuGet package. For runnable C# and Visual Basic examples, see [ADO.NET code examples](ado-net-code-examples.md#sqlclient). ADO.NET separates data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, placed in an ADO.NET object in order to be exposed to the user in an ad hoc manner, combined with data from multiple sources, or passed between tiers. The `DataSet` object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML. - The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. For sample code that connects to a database, retrieves data from it, and then displays that data in a console window, see [ADO.NET Code Examples](ado-net-code-examples.md). + The ADO.NET classes included in .NET Framework are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. The separately distributed SQL Server provider uses Microsoft.Data.SqlClient.dll. For sample code that connects to a database, retrieves data from it, and then displays that data in a console window, see [ADO.NET Code Examples](ado-net-code-examples.md). ADO.NET provides functionality to developers who write managed code similar to the functionality provided to native component object model (COM) developers by ActiveX Data Objects (ADO). We recommend that you use ADO.NET, not ADO, for accessing data in your .NET applications. diff --git a/docs/framework/data/adonet/asynchronous-programming.md b/docs/framework/data/adonet/asynchronous-programming.md index 615102b3d86a7..eeb6b4a283acd 100644 --- a/docs/framework/data/adonet/asynchronous-programming.md +++ b/docs/framework/data/adonet/asynchronous-programming.md @@ -1,16 +1,17 @@ --- title: "Asynchronous Programming" -description: Learn about asynchronous programming in .NET Framework Data Provider for SQL Server, including enhancements introduced in .NET Framework 4.5. -ms.date: "10/18/2018" +description: Learn about asynchronous programming with Microsoft.Data.SqlClient and the task-based APIs available for connections, commands, readers, and bulk copy. +ms.date: "10/20/2026" +ai-usage: ai-assisted --- # Asynchronous programming -This article discusses support for asynchronous programming in .NET Framework Data Provider for SQL Server (SqlClient), including enhancements made to support asynchronous programming functionality that was introduced in .NET Framework 4.5. +This article discusses asynchronous programming with [Microsoft.Data.SqlClient](https://www.nuget.org/packages/Microsoft.Data.SqlClient). Install the NuGet package and import the `Microsoft.Data.SqlClient` namespace for the SQL examples. Microsoft.Data.SqlClient supports task-based APIs on .NET Framework and modern .NET. ## Legacy asynchronous programming -Prior to .NET Framework 4.5, asynchronous programming with SqlClient was done with the following methods and the `Asynchronous Processing=true` connection property: +Prior to .NET Framework 4.5, asynchronous programming with System.Data.SqlClient was done with the following methods and the `Asynchronous Processing=true` connection property: - - @@ -19,7 +20,7 @@ Prior to .NET Framework 4.5, asynchronous programming with SqlClient was done wi This functionality remained in SqlClient in .NET Framework 4.5. > [!TIP] -> Beginning in .NET Framework 4.5, these legacy methods no longer require `Asynchronous Processing=true` in the connection string. +> Microsoft.Data.SqlClient also provides `BeginExecuteNonQuery`, `BeginExecuteReader`, and `BeginExecuteXmlReader` for compatibility. Remove `Asynchronous Processing` from connection strings when you migrate to Microsoft.Data.SqlClient. With either `true` or `false`, the keyword causes with the message `Keyword not supported: 'asynchronous processing'.` when you construct or assign its `ConnectionString` property, before you call `Open` or `OpenAsync`. The keyword isn't ignored and isn't required for asynchronous calls. ## Asynchronous programming features added in .NET Framework 4.5 @@ -36,12 +37,12 @@ You can now call into asynchronous methods without using callbacks, and without The `async` modifier specifies that a method is asynchronous. When calling an `async` method, a task is returned. When the `await` operator is applied to a task, the current method exits immediately. When the task finishes, execution resumes in the same method. -> [!WARNING] -> Asynchronous calls are not supported if an application also uses the `Context Connection` connection string keyword. +> [!NOTE] +> Microsoft.Data.SqlClient doesn't support `Context Connection=true`. When you construct or assign its `ConnectionString` property with that setting, the driver throws with the message `Connecting to the context connection using Microsoft.Data.SqlClient is not supported.` The exception occurs before you call `Open` or `OpenAsync`; the setting isn't ignored. Calling an `async` method does not allocate any additional threads. It might use the existing I/O completion thread briefly at the end. -The following methods were added in .NET Framework 4.5 to support asynchronous programming: +The following base-class and Microsoft.Data.SqlClient methods support asynchronous programming: - - @@ -52,19 +53,19 @@ The following methods were added in .NET Framework 4.5 to support asynchronous p - - - -- -- -- -- -- -- -- -- +- +- +- +- +- +- +- +- Other asynchronous members were added to support [SqlClient Streaming Support](sqlclient-streaming-support.md). > [!TIP] -> The newer asynchronous methods don't require `Asynchronous Processing=true` in the connection string. +> Task-based asynchronous methods don't require a connection string option to enable asynchronous operations. ### Synchronous to asynchronous connection open @@ -85,7 +86,7 @@ When converted to use the newer asynchronous functionality, the program would lo ```csharp using System; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Threading.Tasks; class A { @@ -124,9 +125,11 @@ IAsyncResult ia = cmd.BeginExecuteReader(productList, cmd); You can begin to use the new asynchronous pattern without substantially changing the existing algorithm. +The following template intentionally omits the `ProductList` callback body. In your callback, call , process and dispose the reader, and dispose the command and connection. Keep the application alive until the callback completes. The template isn't a standalone console application. + ```csharp using System; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Threading.Tasks; class A { @@ -150,10 +153,12 @@ You might need to create a tool that is able to connect to different databases a The Microsoft Distributed Transaction Controller (MSDTC) must be enabled on the server to use distributed transactions. For information on how to enable MSDTC, see [How to Enable MSDTC on a Web Server](/previous-versions/commerce-server/dd327979(v=cs.90)). +Before you run the factory example, register `Microsoft.Data.SqlClient` as described in [Obtaining a DbProviderFactory](obtaining-a-dbproviderfactory.md). Use application configuration on .NET Framework or `DbProviderFactories.RegisterFactory` on modern .NET. + ```csharp using System; using System.Data.Common; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Threading.Tasks; class A { @@ -185,7 +190,7 @@ class A { builder.DataSource = "your_server"; builder.InitialCatalog = "pubs"; builder.IntegratedSecurity = true; - string provider = "System.Data.SqlClient"; + string provider = "Microsoft.Data.SqlClient"; Task task = PerformDBOperationsUsingProviderModel(builder.ConnectionString, provider); task.Wait(); @@ -199,7 +204,7 @@ class A { ```csharp using System; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Threading.Tasks; class Program { @@ -264,9 +269,17 @@ class Program { In an enterprise application, you might need to add distributed transactions in some scenarios, to enable transactions between multiple database servers. You can use the namespace and enlist a distributed transaction, as follows: +On modern .NET, distributed transactions require Windows and .NET 7 and later versions. Configure Microsoft Distributed Transaction Coordinator (MSDTC) network access on the participating computers. Before you run the following example on modern .NET, enable transaction promotion at application startup, before you create any transactions: + +```csharp +TransactionManager.ImplicitDistributedTransactions = true; +``` + +The property defaults to `false`. Without this opt-in, promotion to a distributed transaction throws . On .NET Framework, omit this assignment because the property isn't available; MSDTC configuration is still required. + ```csharp using System; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Threading.Tasks; using System.Transactions; @@ -330,7 +343,7 @@ You can cancel an asynchronous request by using the with . +Use for asynchronous bulk copy with . + +Use separate connection strings for SqlClient and ODBC. Replace `` with your SQL Server instance, and install ODBC Driver 18 for SQL Server for the mixed-provider example. On modern .NET, also reference the [System.Data.Odbc package](https://www.nuget.org/packages/System.Data.Odbc). The SqlClient connection string enables multiple active result sets (MARS) for the final example. ```csharp using System; using System.Collections.Generic; using System.Data; using System.Data.Odbc; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Linq; using System.Text; using System.Threading; @@ -396,7 +413,10 @@ namespace SqlBulkCopyAsyncCodeSample { [notes] [varchar](200) NULL, [pubdate] [datetime] NOT NULL)"; - static string connectionString = "..."; + static string connectionString = + "Server=;Database=pubs;Integrated Security=true;Encrypt=true;MultipleActiveResultSets=true;"; + static string odbcConnectionString = + "Driver={ODBC Driver 18 for SQL Server};Server=;Database=pubs;Trusted_Connection=yes;Encrypt=yes;"; static void Main(string[] args) { SynchronousSqlBulkCopy(); @@ -407,7 +427,7 @@ namespace SqlBulkCopyAsyncCodeSample { AsyncSqlBulkCopyMARS().Wait(); } - // 3.1.1 Synchronous bulk copy in .NET Framework 4.5 + // 3.1.1 Synchronous bulk copy private static void SynchronousSqlBulkCopy() { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); @@ -429,7 +449,7 @@ namespace SqlBulkCopyAsyncCodeSample { } - // 3.1.2 Asynchronous bulk copy in .NET Framework 4.5 + // 3.1.2 Asynchronous bulk copy private static async Task AsyncSqlBulkCopy() { using (SqlConnection conn = new SqlConnection(connectionString)) { await conn.OpenAsync(); @@ -452,13 +472,13 @@ namespace SqlBulkCopyAsyncCodeSample { // 3.2 Add new Async.NET capabilities in an existing application (Mixing synchronous and asynchronous calls) private static async Task MixSyncAsyncSqlBulkCopy() { - using (OdbcConnection odbcconn = new OdbcConnection(connectionString)) { + using (OdbcConnection odbcconn = new OdbcConnection(odbcConnectionString)) { odbcconn.Open(); using (OdbcCommand odbccmd = new OdbcCommand(selectStatement, odbcconn)) { using (OdbcDataReader odbcreader = odbccmd.ExecuteReader()) { using (SqlConnection conn = new SqlConnection(connectionString)) { await conn.OpenAsync(); - string temptable = "temptable";//"[#" + Guid.NewGuid().ToString("N") + "]"; + string temptable = "[#" + Guid.NewGuid().ToString("N") + "]"; SqlCommand createCmd = new SqlCommand(string.Format(createDestTableStatement, temptable), conn); await createCmd.ExecuteNonQueryAsync(); using (SqlBulkCopy bcp = new SqlBulkCopy(conn)) { @@ -552,7 +572,7 @@ namespace SqlBulkCopyAsyncCodeSample { ## Asynchronously use multiple commands with MARS -The example opens a single connection to the `AdventureWorks` database. Using a object, a is created. As the reader is used, a second is opened, using data from the first as input to the WHERE clause for the second reader. +The example opens a single connection to the `AdventureWorks` database. Using a object, a is created. As the reader is used, a second is opened, using data from the first as input to the WHERE clause for the second reader. > [!NOTE] > The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. @@ -560,7 +580,7 @@ The example opens a single connection to the `AdventureWorks` database. Using a ```csharp using System; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Threading.Tasks; class Class1 { @@ -622,7 +642,7 @@ class Class1 { MARS allows a connection to be used for both read operations and data manipulation language (DML) operations with more than one pending operation. This feature eliminates the need for an application to deal with connection-busy errors. In addition, MARS can replace the user of server-side cursors, which generally consume more resources. Finally, because multiple operations can operate on a single connection, they can share the same transaction context, eliminating the need to use `sp_getbindtoken` and `sp_bindsession` system stored procedures. -The following Console application demonstrates how to use two objects with three objects and a single object with MARS enabled. The first command object retrieves a list of vendors whose credit rating is 5. The second command object uses the vendor ID provided from a to load the second with all of the products for the particular vendor. Each product record is visited by the second . A calculation is performed to determine what the new `OnOrderQty` should be. The third command object is then used to update the `ProductVendor` table with the new value. This entire process takes place within a single transaction, which is rolled back at the end. +The following Console application demonstrates how to use two objects with three objects and a single object with MARS enabled. The first command object retrieves a list of vendors whose credit rating is 5. The second command object uses the vendor ID provided from a to load the second with all of the products for the particular vendor. Each product record is visited by the second . A calculation is performed to determine what the new `OnOrderQty` should be. The third command object is then used to update the `ProductVendor` table with the new value. This entire process takes place within a single transaction, which is rolled back at the end. > [!NOTE] > The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. @@ -632,7 +652,7 @@ using System; using System.Collections.Generic; using System.Text; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Threading.Tasks; class Program { @@ -722,7 +742,7 @@ class Program { } } } - Console.WriteLine("Total Records Updated: ", totalRecordsUpdated.ToString()); + Console.WriteLine("Total Records Updated: {0}", totalRecordsUpdated); await Task.Run(() => updateTx.Rollback()); Console.WriteLine("Transaction Rolled Back"); } diff --git a/docs/framework/data/adonet/commands-and-parameters.md b/docs/framework/data/adonet/commands-and-parameters.md index 7ccb5ef2d79a6..7810b8dab5624 100644 --- a/docs/framework/data/adonet/commands-and-parameters.md +++ b/docs/framework/data/adonet/commands-and-parameters.md @@ -1,14 +1,14 @@ --- title: "Commands and Parameters" description: Learn how to use Command objects for each .NET Framework data provider to run commands and return results from a data source. -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: b623f810-d871-49a5-b0f5-078cc3c34db6 --- # Commands and Parameters After establishing a connection to a data source, you can execute commands and return results from the data source using a object. You can create a command using one of the command constructors for the .NET Framework data provider you are working with. Constructors can take optional arguments, such as an SQL statement to execute at the data source, a object, or a object. You can also configure those objects as properties of the command. You can also create a command for a particular connection using the method of a `DbConnection` object. The SQL statement being executed by the command can be configured using the property. - Each .NET Framework data provider included with the .NET Framework has a `Command` object. The .NET Framework Data Provider for OLE DB includes an object, the .NET Framework Data Provider for SQL Server includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. + Each ADO.NET data provider has a `Command` object. The .NET Framework Data Provider for OLE DB includes an object, Microsoft.Data.SqlClient includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. ## In This Section diff --git a/docs/framework/data/adonet/configuring-parameters-and-parameter-data-types.md b/docs/framework/data/adonet/configuring-parameters-and-parameter-data-types.md index 2b155f2e4d2d7..f538037d9c950 100644 --- a/docs/framework/data/adonet/configuring-parameters-and-parameter-data-types.md +++ b/docs/framework/data/adonet/configuring-parameters-and-parameter-data-types.md @@ -1,7 +1,7 @@ --- title: "Configuring parameters and parameter data types" description: Command objects use parameters to pass values to SQL statements or stored procedures, providing type checking and validation in ADO.NET. -ms.date: "03/30/2017" +ms.date: "10/19/2026" dev_langs: - "csharp" - "vb" @@ -31,7 +31,7 @@ The syntax for parameter placeholders depends on the data source. The .NET Frame |Data provider|Parameter naming syntax| |-------------------|-----------------------------| -||Uses named parameters in the format `@`*parametername*.| +||Uses named parameters in the format `@`*parametername*.| ||Uses positional parameter markers indicated by a question mark (`?`).| ||Uses positional parameter markers indicated by a question mark (`?`).| ||Uses named parameters in the format `:`*parmname* (or *parmname*).| @@ -95,7 +95,7 @@ Stored procedures offer many advantages in data-driven applications. By using st > [!NOTE] > Parameterized statements are executed on the server by using `sp_executesql`, which allows for query plan reuse. Local cursors or variables in the `sp_executesql` batch are not visible to the batch that calls `sp_executesql`. Changes in database context last only to the end of the `sp_executesql` statement. For more information, see [sp_executesql (Transact-SQL)](/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql). -When using parameters with a to execute a SQL Server stored procedure, the names of the parameters added to the collection must match the names of the parameter markers in the stored procedure. The .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to an SQL statement or a stored procedure. It treats parameters in the stored procedure as named parameters and searches for matching parameter markers. For example, the `CustOrderHist` stored procedure is defined by using a parameter named `@CustomerID`. When your code executes the stored procedure, it must also use a parameter named `@CustomerID`. +When using parameters with a to execute a SQL Server stored procedure, the names of the parameters added to the collection must match the names of the parameter markers in the stored procedure. Microsoft.Data.SqlClient does not support the question mark (?) placeholder for passing parameters to an SQL statement or a stored procedure. It treats parameters in the stored procedure as named parameters and searches for matching parameter markers. For example, the `CustOrderHist` stored procedure is defined by using a parameter named `@CustomerID`. When your code executes the stored procedure, it must also use a parameter named `@CustomerID`. ```sql CREATE PROCEDURE dbo.CustOrderHist @CustomerID varchar(5) @@ -103,7 +103,7 @@ CREATE PROCEDURE dbo.CustOrderHist @CustomerID varchar(5) ### Example -This example demonstrates how to call a SQL Server stored procedure in the `Northwind` sample database. The name of the stored procedure is `dbo.SalesByCategory` and it has an input parameter named `@CategoryName` with a data type of `nvarchar(15)`. The code creates a new inside a using block so that the connection is disposed when the procedure ends. The and objects are created, and their properties set. A executes the `SqlCommand` and returns the result set from the stored procedure, displaying the output in the console window. +This example demonstrates how to call a SQL Server stored procedure in the `Northwind` sample database. The name of the stored procedure is `dbo.SalesByCategory` and it has an input parameter named `@CategoryName` with a data type of `nvarchar(15)`. The code creates a new inside a using block so that the connection is disposed when the procedure ends. The and objects are created, and their properties set. A executes the `SqlCommand` and returns the result set from the stored procedure, displaying the output in the console window. > [!NOTE] > Instead of creating `SqlCommand` and `SqlParameter` objects and then setting properties in separate statements, you can instead elect to use one of the overloaded constructors to set multiple properties in a single statement. diff --git a/docs/framework/data/adonet/connecting-to-a-data-source.md b/docs/framework/data/adonet/connecting-to-a-data-source.md index 5c377e53168d0..a02eaf1a55455 100644 --- a/docs/framework/data/adonet/connecting-to-a-data-source.md +++ b/docs/framework/data/adonet/connecting-to-a-data-source.md @@ -1,14 +1,14 @@ --- title: "Connecting to a Data Source" description: Learn about Connection objects, used to connect to data sources in ADO.NET. The Connection object you choose depends on the type of data source. -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: 9abc3f92-1be3-4e1a-b360-762dc689650e --- # Connecting to a Data Source in ADO.NET In ADO.NET, you use a `Connection` object to connect to a specific data source by supplying necessary authentication information in a connection string. The `Connection` object you use depends on the type of data source. - Each .NET Framework data provider included with the .NET Framework has a object: the .NET Framework Data Provider for OLE DB includes an object, the .NET Framework Data Provider for SQL Server includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. + Each ADO.NET data provider has a object: the .NET Framework Data Provider for OLE DB includes an object, Microsoft.Data.SqlClient includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. ## In This Section diff --git a/docs/framework/data/adonet/connection-events.md b/docs/framework/data/adonet/connection-events.md index 3766d7563d8cd..320f3da41b154 100644 --- a/docs/framework/data/adonet/connection-events.md +++ b/docs/framework/data/adonet/connection-events.md @@ -1,7 +1,7 @@ --- description: "Learn more about: Connection Events" title: "Connection Events" -ms.date: "03/30/2017" +ms.date: "10/19/2026" dev_langs: - "csharp" - "vb" @@ -18,13 +18,13 @@ All of the .NET Framework data providers have `Connection` objects with two even ## Working with the InfoMessage Event - You can retrieve warnings and informational messages from a SQL Server data source using the event of the object. Errors returned from the data source with a severity level of 11 through 16 cause an exception to be thrown. However, the event can be used to obtain messages from the data source that are not associated with an error. In the case of Microsoft SQL Server, any error with a severity of 10 or less is considered to be an informational message, and can be captured by using the event. For more information, see the [Database Engine Error Severities](/sql/relational-databases/errors-events/database-engine-error-severities) article. + You can retrieve warnings and informational messages from a SQL Server data source using the event of the object. Errors returned from the data source with a severity level of 11 through 16 cause an exception to be thrown. However, the event can be used to obtain messages from the data source that are not associated with an error. In the case of Microsoft SQL Server, any error with a severity of 10 or less is considered to be an informational message, and can be captured by using the event. For more information, see the [Database Engine Error Severities](/sql/relational-databases/errors-events/database-engine-error-severities) article. - The event receives an object containing, in its `Errors` property, a collection of the messages from the data source. You can query the `Error` objects in this collection for the error number and message text, as well as the source of the error. The .NET Framework Data Provider for SQL Server also includes detail about the database, stored procedure, and line number that the message came from. + The event receives an object containing, in its `Errors` property, a collection of the messages from the data source. You can query the `Error` objects in this collection for the error number and message text, as well as the source of the error. Microsoft.Data.SqlClient also includes detail about the database, stored procedure, and line number that the message came from. ### Example - The following code example shows how to add an event handler for the event. + The following code example shows how to add an event handler for the event. ```vb ' Assumes that connection represents a SqlConnection object. @@ -65,12 +65,12 @@ protected static void OnInfoMessage( ## Handling Errors as InfoMessages - The event will normally fire only for informational and warning messages that are sent from the server. However, when an actual error occurs, the execution of the `ExecuteNonQuery` or `ExecuteReader` method that initiated the server operation is halted and an exception is thrown. + The event will normally fire only for informational and warning messages that are sent from the server. However, when an actual error occurs, the execution of the `ExecuteNonQuery` or `ExecuteReader` method that initiated the server operation is halted and an exception is thrown. - If you want to continue processing the rest of the statements in a command regardless of any errors produced by the server, set the property of the to `true`. Doing this causes the connection to fire the event for errors instead of throwing an exception and interrupting processing. The client application can then handle this event and respond to error conditions. + If you want to continue processing the rest of the statements in a command regardless of any errors produced by the server, set the property of the to `true`. Doing this causes the connection to fire the event for errors instead of throwing an exception and interrupting processing. The client application can then handle this event and respond to error conditions. > [!NOTE] -> An error with a severity level of 17 or above that causes the server to stop processing the command must be handled as an exception. In this case, an exception is thrown regardless of how the error is handled in the event. +> An error with a severity level of 17 or above that causes the server to stop processing the command must be handled as an exception. In this case, an exception is thrown regardless of how the error is handled in the event. ## Working with the StateChange Event diff --git a/docs/framework/data/adonet/connection-string-builders.md b/docs/framework/data/adonet/connection-string-builders.md index 7f351bcc4b9c0..03d90d13d9c2a 100644 --- a/docs/framework/data/adonet/connection-string-builders.md +++ b/docs/framework/data/adonet/connection-string-builders.md @@ -1,18 +1,18 @@ --- title: "Connection String Builders" description: Learn about the connection string builder classes used for different providers in ADO.NET, all of which inherit from DbConnectionStringBuilder. -ms.date: "03/30/2017" +ms.date: "10/19/2026" dev_langs: - "csharp" - "vb" --- # Connection string builders -In early versions of ADO.NET, compile-time checking of connection strings with concatenated string values did not occur, so that at runtime, an incorrect keyword generated an . Each of the .NET Framework data providers supported different syntax for connection string keywords, which made constructing valid connection strings difficult if done manually. To address this problem, ADO.NET 2.0 introduced new connection string builders for each .NET Framework data provider. Each data provider includes a strongly typed connection string builder class that inherits from . The following table lists the .NET Framework data providers and their associated connection string builder classes. +In early versions of ADO.NET, compile-time checking of connection strings with concatenated string values did not occur, so that at runtime, an incorrect keyword generated an . Each of the .NET Framework data providers supported different syntax for connection string keywords, which made constructing valid connection strings difficult if done manually. To address this problem, ADO.NET 2.0 introduced new connection string builders for each .NET Framework data provider. Each data provider includes a strongly typed connection string builder class that inherits from . The following table lists ADO.NET data providers and their associated connection string builder classes. | Provider | ConnectionStringBuilder class | |---------------------------------|--------------------------------------------------------------------------------------------| -| | | +| | | | | | | | | | | | @@ -23,10 +23,10 @@ In early versions of ADO.NET, compile-time checking of connection strings with c The connection string builder classes are designed to eliminate guesswork and protect against syntax errors and security vulnerabilities. They provide methods and properties corresponding to the known key/value pairs permitted by each data provider. Each class maintains a fixed collection of synonyms and can translate from a synonym to the corresponding well-known key name. Checks are performed for valid key/value pairs, and an invalid pair throws an exception. In addition, injected values are handled in a safe manner. - The following example demonstrates how handles an inserted extra value for the `Initial Catalog` setting. + The following example demonstrates how handles an inserted extra value for the `Initial Catalog` setting. ```vb -Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder +Dim builder As New Microsoft.Data.SqlClient.SqlConnectionStringBuilder builder("Data Source") = "(local)" builder("Integrated Security") = True builder("Initial Catalog") = "AdventureWorks;NewValue=Bad" @@ -34,8 +34,8 @@ Console.WriteLine(builder.ConnectionString) ``` ```csharp -System.Data.SqlClient.SqlConnectionStringBuilder builder = - new System.Data.SqlClient.SqlConnectionStringBuilder(); +Microsoft.Data.SqlClient.SqlConnectionStringBuilder builder = + new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(); builder["Data Source"] = "(local)"; builder["integrated Security"] = true; builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad"; @@ -44,7 +44,7 @@ Console.WriteLine(builder.ConnectionString); [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] -The output shows that the handled this correctly by escaping the extra value in double quotation marks instead of appending it to the connection string as a new key/value pair. +The output shows that the handled this correctly by escaping the extra value in double quotation marks instead of appending it to the connection string as a new key/value pair. ```output data source=(local);Integrated Security=True; diff --git a/docs/framework/data/adonet/connection-string-syntax.md b/docs/framework/data/adonet/connection-string-syntax.md index a908558a25b2e..0af5f9d68790f 100644 --- a/docs/framework/data/adonet/connection-string-syntax.md +++ b/docs/framework/data/adonet/connection-string-syntax.md @@ -1,24 +1,25 @@ --- title: "Connection String Syntax" description: Learn about syntax of connection strings in ADO.NET. The syntax for each provider is documented in its ConnectionString property. -ms.date: "05/22/2018" +ms.date: "10/19/2026" +ai-usage: ai-assisted --- # Connection string syntax -Each .NET Framework data provider has a `Connection` object that inherits from as well as a provider-specific property. The specific connection string syntax for each provider is documented in its `ConnectionString` property. The following table lists the four data providers that are included in .NET Framework. +Each ADO.NET data provider has a `Connection` object that inherits from as well as a provider-specific property. The specific connection string syntax for each provider is documented in its `ConnectionString` property. The following table lists Microsoft.Data.SqlClient and three providers included in .NET Framework. -| .NET Framework data provider | Description | +| Data provider | Description | |------------------------------|-------------| -||Provides data access for Microsoft SQL Server. For more information on connection string syntax, see .| +||Provides data access for Microsoft SQL Server through the [Microsoft.Data.SqlClient NuGet package](https://www.nuget.org/packages/Microsoft.Data.SqlClient). For more information on connection string syntax, see .| ||Provides data access for data sources exposed using OLE DB. For more information on connection string syntax, see .| ||Provides data access for data sources exposed using ODBC. For more information on connection string syntax, see .| ||Provides data access for Oracle version 8.1.7 or later. For more information on connection string syntax, see .| ## Connection string builders - ADO.NET 2.0 introduced the following connection string builders for the .NET Framework data providers. + Use the connection string builder for your data provider. -- +- - - - @@ -27,7 +28,7 @@ Each .NET Framework data provider has a `Connection` object that inherits from < ## Windows authentication -Windows Authentication (sometimes referred to as *integrated security*) can be used to connect to data sources that support it. The syntax employed in the connection string varies by provider. The following table shows the Windows Authentication syntax used with the .NET Framework data providers. +Windows Authentication (sometimes referred to as *integrated security*) can be used to connect to data sources that support it. The syntax employed in the connection string varies by provider. The following table shows the Windows Authentication syntax used with these data providers. | Provider | Syntax | |----------------|--------------------------------------------------------------------------------------------| @@ -43,22 +44,19 @@ Windows Authentication (sometimes referred to as *integrated security*) can be u ## SqlClient connection strings -The syntax for a connection string is documented in the property. You can use the property to get or set a connection string for a SQL Server database. If you need to connect to an earlier version of SQL Server, you must use the .NET Framework Data Provider for OleDb (). Most connection string keywords also map to properties in the . +The syntax for a connection string is documented in the property. You can use the property to get or set a connection string for a SQL Server database. Most connection string keywords also map to properties in the . > [!IMPORTANT] > The default setting for the `Persist Security Info` keyword is `false`. Setting it to `true` or `yes` allows security-sensitive information, including the user ID and password, to be obtained from the connection after the connection has been opened. Keep `Persist Security Info` set to `false` to ensure that an untrusted source does not have access to sensitive connection string information. ### Windows authentication with SqlClient - Each of the following forms of syntax uses Windows Authentication to connect to the `AdventureWorks` database on a local server. + Each of the following forms of syntax uses Windows Authentication to connect to the `AdventureWorks` database on the specified server. ```csharp -"Persist Security Info=False;Integrated Security=true; - Initial Catalog=AdventureWorks;Server=MSSQL1" -"Persist Security Info=False;Integrated Security=SSPI; - database=AdventureWorks;server=(local)" -"Persist Security Info=False;Trusted_Connection=True; - database=AdventureWorks;server=(local)" +"Persist Security Info=False;Integrated Security=true;Initial Catalog=AdventureWorks;Server=;Encrypt=true" +"Persist Security Info=False;Integrated Security=SSPI;database=AdventureWorks;server=;Encrypt=true" +"Persist Security Info=False;Trusted_Connection=True;database=AdventureWorks;server=;Encrypt=true" ``` [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] @@ -83,14 +81,14 @@ When you connect to Azure SQL Database or to Azure SQL Data Warehouse and provid To connect to a named instance of SQL Server, use the *server name\instance name* syntax. ```csharp -"Data Source=MySqlServer\\MSSQL1;" +"Data Source=\\;Encrypt=true;" ``` -You can also set the property of the `SqlConnectionStringBuilder` to the instance name when building a connection string. The property of a object is read-only. +You can also set the property of the `SqlConnectionStringBuilder` to the instance name when building a connection string. The property of a object is read-only. ### Type system version changes - The `Type System Version` keyword in a specifies the client-side representation of SQL Server types. See for more information about the `Type System Version` keyword. + The `Type System Version` keyword in a specifies the client-side representation of SQL Server types. For more information about the `Type System Version` keyword, see . ## Connect and attach to SQL Server Express user instances @@ -100,34 +98,20 @@ You can also set the [!NOTE] -> If `TrustServerCertificate` is set to `true` and encryption is turned on, the encryption level specified on the server will be used even if `Encrypt` is set to `false` in the connection string. The connection will fail otherwise. +> [!CAUTION] +> If you bypass certificate validation, the client can't verify the server's identity. With `Encrypt=Strict`, Microsoft.Data.SqlClient always validates the server certificate and ignores `TrustServerCertificate`. ### Enable encryption - To enable encryption when a certificate has not been provisioned on the server, the **Force Protocol Encryption** and the **Trust Server Certificate** options must be set in SQL Server Configuration Manager. In this case, encryption will use a self-signed server certificate without validation if no verifiable certificate has been provisioned on the server. - - Application settings cannot reduce the level of security configured in SQL Server, but can optionally strengthen it. An application can request encryption by setting the `TrustServerCertificate` and `Encrypt` keywords to `true`, guaranteeing that encryption takes place even when a server certificate has not been provisioned and **Force Protocol Encryption** has not been configured for the client. However, if `TrustServerCertificate` is not enabled in the client configuration, a provisioned server certificate is still required. - - The following table describes all cases. - -|Force Protocol Encryption client setting|Trust Server Certificate client setting|Encrypt/Use Encryption for Data connection string/attribute|Trust Server Certificate connection string/attribute|Result| -|----------------------------------------------|---------------------------------------------|-------------------------------------------------------------------|-----------------------------------------------------------|------------| -|No|N/A|No (default)|Ignored|No encryption occurs.| -|No|N/A|Yes|No (default)|Encryption occurs only if there is a verifiable server certificate, otherwise the connection attempt fails.| -|No|N/A|Yes|Yes|Encryption always occurs, but may use a self-signed server certificate.| -|Yes|No|Ignored|Ignored|Encryption occurs only if there is a verifiable server certificate; otherwise, the connection attempt fails.| -|Yes|Yes|No (default)|Ignored|Encryption always occurs, but may use a self-signed server certificate.| -|Yes|Yes|Yes|No (default)|Encryption occurs only if there is a verifiable server certificate; otherwise, the connection attempt fails.| -|Yes|Yes|Yes|Yes|Encryption always occurs, but may use a self-signed server certificate.| + Microsoft.Data.SqlClient defaults to `Encrypt=Mandatory`, equivalent to `Encrypt=true`, and `TrustServerCertificate=false`. The client requires encryption and validates the server certificate. If the certificate isn't trusted or doesn't match the server name, the connection fails. - For more information, see [Using Encryption Without Validation](/sql/relational-databases/native-client/features/using-encryption-without-validation). + For remote connections, specify `Encrypt=true` and configure a server certificate that the client trusts. If you migrate from System.Data.SqlClient, don't assume its encryption defaults apply to Microsoft.Data.SqlClient. For more information, see [Encryption and certificate validation in Microsoft.Data.SqlClient](/sql/connect/ado-net/encryption-and-certificate-validation). ## OleDb connection strings diff --git a/docs/framework/data/adonet/connection-strings.md b/docs/framework/data/adonet/connection-strings.md index 3b85ba85756d0..a6ecf7e46e061 100644 --- a/docs/framework/data/adonet/connection-strings.md +++ b/docs/framework/data/adonet/connection-strings.md @@ -1,7 +1,7 @@ --- title: "Connection Strings" description: Learn about connection strings in ADO.NET, which contain initialization information passed as a parameter from a data provider to a data source. -ms.date: "10/10/2018" +ms.date: "10/19/2026" ms.custom: sfi-ropc-nochange --- @@ -49,7 +49,7 @@ Keyword=a=b=c Since each value is read till the next semicolon or the end of string, the value in the latter example is `a=b=c`, and the final semicolon is optional. -All connection strings share the same basic syntax described previously. The set of recognized keywords depends on the provider, however, and has evolved over the years from earlier APIs such as *ODBC*. The *.NET Framework* data provider for *SQL Server* (`SqlClient`) supports many keywords from older APIs, but is generally more flexible and accepts synonyms for many of the common connection string keywords. +All connection strings share the same basic syntax described previously. The set of recognized keywords depends on the provider, however, and has evolved over the years from earlier APIs such as *ODBC*. Microsoft.Data.SqlClient supports many keywords from older APIs, but is generally more flexible and accepts synonyms for many of the common connection string keywords. Typing mistakes can cause errors. For example, `Integrated Security=true` is valid, but `IntegratedSecurity=true` causes an error. diff --git a/docs/framework/data/adonet/data-providers.md b/docs/framework/data/adonet/data-providers.md index 67b413a9b8574..0aed2741dbe0a 100644 --- a/docs/framework/data/adonet/data-providers.md +++ b/docs/framework/data/adonet/data-providers.md @@ -1,7 +1,8 @@ --- title: ".NET Framework Data Providers" description: Learn how a .NET Framework data provider is used to connect to a database, run commands, and retrieve results in ADO.NET. -ms.date: "03/30/2017" +ms.date: "10/19/2026" +ai-usage: ai-assisted dev_langs: - "csharp" - "vb" @@ -11,6 +12,26 @@ ms.custom: sfi-ropc-nochange A .NET Framework data provider is used for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, placed in a in order to be exposed to the user as needed, combined with data from multiple sources, or remoted between tiers. .NET Framework data providers are lightweight, creating a minimal layer between the data source and code, increasing performance without sacrificing functionality. +For new SQL Server applications, use [Microsoft.Data.SqlClient](https://www.nuget.org/packages/Microsoft.Data.SqlClient). Install this provider as a NuGet package rather than use the `System.Data.SqlClient` provider built into .NET Framework. For an existing application, follow the [migration guide](/sql/connect/ado-net/migrate-system-data-sql-client-to-microsoft-data-sql-client). + +## Microsoft.Data.SqlClient + +The Microsoft.Data.SqlClient provider supports .NET and .NET Framework applications. For installation instructions and supported target frameworks, see [Download Microsoft.Data.SqlClient](/sql/connect/ado-net/download-microsoft-sqlclient-data-provider). + +After you install the package, import its namespace: + +```vb +Imports Microsoft.Data.SqlClient +``` + +```csharp +using Microsoft.Data.SqlClient; +``` + +For runnable C# and Visual Basic examples, see [ADO.NET code examples](ado-net-code-examples.md#sqlclient). + +## Providers included in .NET Framework + The following table lists the data providers that are included in .NET Framework. | .NET Framework data provider | Description | @@ -58,15 +79,7 @@ A .NET Framework data provider is used for connecting to a database, executing c The .NET Framework Data Provider for SQL Server supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for SQL Server, by default, automatically enlists in a transaction and obtains transaction details from Windows Component Services or . For more information, see [Transactions and Concurrency](transactions-and-concurrency.md). - The following code example shows how to include the `System.Data.SqlClient` namespace in your applications. - -```vb -Imports System.Data.SqlClient -``` - -```csharp -using System.Data.SqlClient; -``` + For new applications, use the separately distributed `Microsoft.Data.SqlClient` package described in [Microsoft.Data.SqlClient](#microsoftdatasqlclient), rather than the built-in provider. ## .NET Framework Data Provider for OLE DB @@ -150,8 +163,8 @@ using System.Data.OracleClient; |Provider|Notes| |--------------|-----------| -|.NET Framework Data Provider for SQL Server|Recommended for middle-tier applications that use Microsoft SQL Server.

Recommended for single-tier applications that use Microsoft Database Engine (MSDE) or SQL Server.

Recommended over use of the OLE DB provider for SQL Server (SQLOLEDB) with the .NET Framework Data Provider for OLE DB.| -|.NET Framework Data Provider for OLE DB|For SQL Server, the .NET Framework Data Provider for SQL Server is recommended instead of this provider.

Recommended for single-tier applications that use Microsoft Access databases. Use of an Access database for a middle-tier application is not recommended.| +|Microsoft.Data.SqlClient|Use for new SQL Server applications. Install the Microsoft.Data.SqlClient NuGet package.| +|.NET Framework Data Provider for OLE DB|For SQL Server, use Microsoft.Data.SqlClient instead of this provider.

Recommended for single-tier applications that use Microsoft Access databases. Use of an Access database for a middle-tier application is not recommended.| |.NET Framework Data Provider for ODBC|Recommended for middle and single-tier applications that use ODBC data sources.| |.NET Framework Data Provider for Oracle|Recommended for middle and single-tier applications that use Oracle data sources.| diff --git a/docs/framework/data/adonet/data-tracing.md b/docs/framework/data/adonet/data-tracing.md index 57153c76b4486..d9c239ccc728f 100644 --- a/docs/framework/data/adonet/data-tracing.md +++ b/docs/framework/data/adonet/data-tracing.md @@ -1,13 +1,14 @@ --- description: "Learn more about: Data Tracing in ADO.NET" title: "Data Tracing" -ms.date: "03/30/2017" +ms.date: "10/19/2026" +ai-usage: ai-assisted ms.assetid: a6a752a5-d2a9-4335-a382-b58690ccb79f --- # Data Tracing in ADO.NET -ADO.NET features built-in data tracing functionality that is supported by the .NET data providers for SQL Server, Oracle, OLE DB and ODBC, as well as the ADO.NET , and the SQL Server network protocols. +Microsoft.Data.SqlClient exposes data access tracing through the `Microsoft.Data.SqlClient.EventSource` event source. Other ADO.NET components, such as the .NET Framework providers for Oracle, OLE DB, and ODBC, and , have their own tracing facilities. Tracing data access API calls can help diagnose the following problems: @@ -23,19 +24,19 @@ Tracing data access API calls can help diagnose the following problems: To support different trace technologies, tracing is extensible, so a developer can trace a problem at any level of the application stack. Although tracing is not an ADO.NET-only feature, Microsoft providers take advantage of generalized tracing and instrumentation APIs. -For more information about setting and configuring managed tracing in ADO.NET, see [Tracing Data Access](/previous-versions/sql/sql-server-2012/hh880086(v=msdn.10)). +For more information about how to collect Microsoft.Data.SqlClient traces, see [Enable EventSource tracing in SqlClient](/sql/connect/ado-net/enable-eventsource-tracing). ## Accessing Diagnostic Information in the Extended Events Log -In the .NET Framework Data Provider for SQL Server, data access tracing ([Data Access Tracing](/previous-versions/sql/sql-server-2012/hh880086(v=msdn.10))) has been updated to make it easier to correlate client events with diagnostic information, such as connection failures, from the server's connectivity ring buffer and application performance information in the extended events log. For information about reading the extended events log, see [View Event Session Data](/previous-versions/sql/sql-server-2012/hh710068(v=sql.110)). +Use Microsoft.Data.SqlClient connection IDs to correlate client events with server diagnostic information, such as connection failures, in the connectivity ring buffer and extended events log. For information about how to read the extended events log, see [View Event Session Data](/previous-versions/sql/sql-server-2012/hh710068(v=sql.110)). -For connection operations, ADO.NET will send a client connection ID. If the connection fails, you can access the connectivity ring buffer ([Connectivity troubleshooting in SQL Server 2008 with the Connectivity Ring Buffer](/archive/blogs/sql_protocols/connectivity-troubleshooting-in-sql-server-2008-with-the-connectivity-ring-buffer)) and find the `ClientConnectionID` field and get diagnostic information about the connection failure. Client connection IDs are logged in the ring buffer only if an error occurs. (If a connection fails before sending the prelogin packet, a client connection ID will not be generated.) The client connection ID is a 16-byte GUID. You can also find the client connection ID in the extended events target output, if the `client_connection_id` action is added to events in an extended events session. You can enable data access tracing and rerun the connection command and observe the `ClientConnectionID` field in the data access trace, if you need further client driver diagnostic assistance. +For connection operations, Microsoft.Data.SqlClient sends a client connection ID during the prelogin exchange. If the connection fails, look for the `ClientConnectionID` field in the connectivity ring buffer to obtain diagnostic information about the connection failure. Client connection IDs are logged in the ring buffer only if an error occurs. If a connection fails before the prelogin exchange, the server won't receive the ID. The client connection ID is a 16-byte GUID. You can also find the client connection ID in the extended events target output if you add the `client_connection_id` action to events in an extended events session. -You can get the client connection ID programmatically by using the `SqlConnection.ClientConnectionID` property. +To get the client connection ID programmatically, use . -The `ClientConnectionID` is available for a object that successfully establishes a connection. If a connection attempt fails, `ClientConnectionID` may be available via `SqlException.ToString`. +The connection ID is available for after it successfully establishes a connection. If a connection attempt fails, the ID might be available through . -ADO.NET also sends a thread-specific activity ID. The activity ID is captured in the extended events sessions if the sessions are started with the TRACK_CAUSALITY option enabled. For performance issues with an active connection, you can get the activity ID from the client's data access trace (`ActivityID` field) and then locate the activity ID in the extended events output. The activity ID in extended events is a 16-byte GUID (not the same as the GUID for the client connection ID) appended with a four-byte sequence number. The sequence number represents the order of a request within a thread and indicates the relative ordering of batch and RPC statements for the thread. The `ActivityID` is currently optionally sent for SQL batch statements and RPC requests when data access tracing is enabled on and the 18th bit in the data access tracing configuration word is turned ON. +Microsoft.Data.SqlClient also sends a thread-specific activity ID for batch statements and remote procedure call (RPC) requests when its event source is enabled and the server supports trace headers. To capture the activity ID in an extended events session, enable `TRACK_CAUSALITY`. For performance issues with an active connection, locate the activity ID in the client trace and then in the extended events output. The activity ID contains a 16-byte GUID and a four-byte sequence number. The sequence number indicates the relative order of requests within a thread. The legacy data access tracing configuration word doesn't configure Microsoft.Data.SqlClient's event source. The following is a sample that uses Transact-SQL to start an extended events session that will be stored in a ring buffer and will record the activity ID sent from a client on RPC and batch operations. diff --git a/docs/framework/data/adonet/data-type-mappings-in-ado-net.md b/docs/framework/data/adonet/data-type-mappings-in-ado-net.md index 98be8e45d6b7e..b860d07fb77af 100644 --- a/docs/framework/data/adonet/data-type-mappings-in-ado-net.md +++ b/docs/framework/data/adonet/data-type-mappings-in-ado-net.md @@ -1,7 +1,7 @@ --- description: "Learn more about: Data Type Mappings in ADO.NET" title: "Data Type Mappings" -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: d4afab94-ada6-4c77-a73c-41f17bae6b5a --- # Data Type Mappings in ADO.NET @@ -18,7 +18,7 @@ The .NET Framework is based on the common type system, which defines how types a ## In This Section [SQL Server Data Type Mappings](sql-server-data-type-mappings.md) - Lists inferred data type mappings and data accessor methods for . + Lists inferred data type mappings and data accessor methods for . [OLE DB Data Type Mappings](ole-db-data-type-mappings.md) Lists inferred data type mappings and data accessor methods for . diff --git a/docs/framework/data/adonet/dbproviderfactories.md b/docs/framework/data/adonet/dbproviderfactories.md index cbb3d74251782..2700f2f520826 100644 --- a/docs/framework/data/adonet/dbproviderfactories.md +++ b/docs/framework/data/adonet/dbproviderfactories.md @@ -1,14 +1,17 @@ --- description: "Learn more about: DbProviderFactories" title: "DbProviderFactories" -ms.date: "03/30/2017" +ms.date: "10/19/2026" +ai-usage: ai-assisted ms.assetid: 2a8e2640-3a49-42a1-a3a9-b43026907ae1 --- # DbProviderFactories The namespace provides classes for creating instances to work with specific data sources. When you create a instance and pass it information about the data provider, the `DbProviderFactory` can determine the correct, strongly typed connection object to return based on the information it has been provided. - Beginning in the .NET Framework version 4, data providers such as , , , and are no longer listed in machine.config file, but custom providers will continue to be listed there. + Beginning in the .NET Framework version 4, built-in data providers such as , , , and are no longer listed in machine.config file, but custom providers will continue to be listed there. + +For SQL Server, use the [Microsoft.Data.SqlClient NuGet package](https://www.nuget.org/packages/Microsoft.Data.SqlClient). Register its in your application's configuration file on .NET Framework, or call on modern .NET. For both runtimes, use `Microsoft.Data.SqlClient` as the invariant provider name. For more information, see [Obtaining a DbProviderFactory](obtaining-a-dbproviderfactory.md). ## In This Section diff --git a/docs/framework/data/adonet/distributed-transactions.md b/docs/framework/data/adonet/distributed-transactions.md index 246785490fa05..c9953b7b5de70 100644 --- a/docs/framework/data/adonet/distributed-transactions.md +++ b/docs/framework/data/adonet/distributed-transactions.md @@ -1,7 +1,7 @@ --- description: "Learn more about: Distributed Transactions" title: "Distributed Transactions" -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.custom: sfi-ropc-nochange --- # Distributed transactions @@ -17,14 +17,14 @@ A transaction is a set of related tasks that either succeeds (commit) or fails ( ADO.NET 2.0 introduced support for enlisting in a distributed transaction using the `EnlistTransaction` method, which enlists a connection in a instance. In previous versions of ADO.NET, explicit enlistment in distributed transactions was performed using the `EnlistDistributedTransaction` method of a connection to enlist a connection in a instance, which is supported for backwards compatibility. For more information on Enterprise Services transactions, see [Interoperability with Enterprise Services and COM+ Transactions](../transactions/interoperability-with-enterprise-services-and-com-transactions.md). - When using a transaction with the .NET Framework Provider for SQL Server against a SQL Server database, a lightweight will automatically be used. The transaction can then be promoted to a full distributed transaction on an as-needed basis. For more information, see [System.Transactions Integration with SQL Server](system-transactions-integration-with-sql-server.md). + When using a transaction with Microsoft.Data.SqlClient against a SQL Server database, a lightweight will automatically be used. The transaction can then be promoted to a full distributed transaction on an as-needed basis. For more information, see [System.Transactions Integration with SQL Server](system-transactions-integration-with-sql-server.md). > [!NOTE] > The maximum number of distributed transactions that an Oracle database can participate in at one time is set to 10 by default. After the 10th transaction when connected to an Oracle database, an exception is thrown. Oracle does not support `DDL` inside of a distributed transaction. ## Automatically Enlisting in a Distributed Transaction - Automatic enlistment is the default (and preferred) way of integrating ADO.NET connections with `System.Transactions`. A connection object will automatically enlist in an existing distributed transaction if it determines that a transaction is active, which, in `System.Transaction` terms, means that `Transaction.Current` is not null. Automatic transaction enlistment occurs when the connection is opened. It will not happen after that even if a command is executed inside of a transaction scope. You can disable auto-enlistment in existing transactions by specifying `Enlist=false` as a connection string parameter for a , or `OLE DB Services=-7` as a connection string parameter for an . For more information on Oracle and ODBC connection string parameters, see and . + Automatic enlistment is the default (and preferred) way of integrating ADO.NET connections with `System.Transactions`. A connection object will automatically enlist in an existing distributed transaction if it determines that a transaction is active, which, in `System.Transaction` terms, means that `Transaction.Current` is not null. Automatic transaction enlistment occurs when the connection is opened. It will not happen after that even if a command is executed inside of a transaction scope. You can disable auto-enlistment in existing transactions by specifying `Enlist=false` as a connection string parameter for a , or `OLE DB Services=-7` as a connection string parameter for an . For more information on Oracle and ODBC connection string parameters, see and . ## Manually Enlisting in a Distributed Transaction @@ -38,7 +38,7 @@ A transaction is a set of related tasks that either succeeds (commit) or fails ( > Once a connection is explicitly enlisted on a transaction, it cannot be un-enlisted or enlisted in another transaction until the first transaction finishes. > [!CAUTION] -> `EnlistTransaction` throws an exception if the connection has already begun a transaction using the connection's method. However, if the transaction is a local transaction started at the data source (for example, executing the BEGIN TRANSACTION statement explicitly using a ), `EnlistTransaction` will roll back the local transaction and enlist in the existing distributed transaction as requested. You will not receive notice that the local transaction was rolled back, and must manage any local transactions not started using . If you are using the .NET Framework Data Provider for SQL Server (`SqlClient`) with SQL Server, an attempt to enlist will throw an exception. All other cases will go undetected. +> `EnlistTransaction` throws an exception if the connection has already begun a transaction using the connection's method. However, if the transaction is a local transaction started at the data source (for example, executing the BEGIN TRANSACTION statement explicitly using a ), `EnlistTransaction` will roll back the local transaction and enlist in the existing distributed transaction as requested. You will not receive notice that the local transaction was rolled back, and must manage any local transactions not started using . If you are using Microsoft.Data.SqlClient with SQL Server, an attempt to enlist will throw an exception. All other cases will go undetected. ## Promotable Transactions in SQL Server diff --git a/docs/framework/data/adonet/establishing-the-connection.md b/docs/framework/data/adonet/establishing-the-connection.md index b3d3effdb6816..790c317bd982a 100644 --- a/docs/framework/data/adonet/establishing-the-connection.md +++ b/docs/framework/data/adonet/establishing-the-connection.md @@ -1,7 +1,7 @@ --- -description: "Learn more about establishing a connection to SQL Server using the .NET Framework Data Provider for SQL Server." +description: "Learn more about establishing a connection to SQL Server using Microsoft.Data.SqlClient." title: "Establishing the Connection" -ms.date: "03/30/2017" +ms.date: "10/19/2026" dev_langs: - "csharp" - "vb" @@ -9,7 +9,7 @@ ms.custom: sfi-ropc-nochange --- # Establish a connection -To connect to Microsoft SQL Server, use the object of the .NET Framework Data Provider for SQL Server. To connect to an OLE DB data source, use the object of the .NET Framework Data Provider for OLE DB. To connect to an ODBC data source, use the object of the .NET Framework Data Provider for ODBC. To connect to an Oracle data source, use the object of the .NET Framework Data Provider for Oracle. For securely storing and retrieving connection strings, see [Protecting Connection Information](protecting-connection-information.md). +To connect to Microsoft SQL Server, install the [Microsoft.Data.SqlClient NuGet package](https://www.nuget.org/packages/Microsoft.Data.SqlClient) and use . To connect to an OLE DB data source, use the object of the .NET Framework Data Provider for OLE DB. To connect to an ODBC data source, use the object of the .NET Framework Data Provider for ODBC. To connect to an Oracle data source, use the object of the .NET Framework Data Provider for Oracle. For securely storing and retrieving connection strings, see [Protecting Connection Information](protecting-connection-information.md). ## Closing Connections @@ -25,7 +25,7 @@ To connect to Microsoft SQL Server, use the property of the object. You can also use the class to create syntactically valid connection strings at runtime. For more information, see [Connection String Builders](connection-string-builders.md). + Microsoft.Data.SqlClient supports a connection string format that is similar to the OLE DB (ADO) connection string format. For valid string format names and values, see the property of the object. You can also use the class to create syntactically valid connection strings at runtime. For more information, see [Connection String Builders](connection-string-builders.md). The following code example demonstrates how to create and open a connection to a SQL Server database. diff --git a/docs/framework/data/adonet/executing-a-command.md b/docs/framework/data/adonet/executing-a-command.md index 3ac9137a64902..54ed621f438aa 100644 --- a/docs/framework/data/adonet/executing-a-command.md +++ b/docs/framework/data/adonet/executing-a-command.md @@ -1,7 +1,7 @@ --- description: "Learn more about: Executing a Command" title: "Executing a Command" -ms.date: "03/30/2017" +ms.date: "10/19/2026" dev_langs: - "csharp" - "vb" @@ -9,7 +9,7 @@ ms.assetid: 40494916-c25a-4cb8-8f7c-fcb8d378464e --- # Executing a Command -Each .NET Framework data provider included with the .NET Framework has its own command object that inherits from . The .NET Framework Data Provider for OLE DB includes an object, the .NET Framework Data Provider for SQL Server includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. Each of these objects exposes methods for executing commands based on the type of command and desired return value, as described in the following table. +Each ADO.NET data provider has its own command object that inherits from . The .NET Framework Data Provider for OLE DB includes an object, Microsoft.Data.SqlClient includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. Each of these objects exposes methods for executing commands based on the type of command and desired return value, as described in the following table. |Command|Return Value| |-------------|------------------| @@ -28,14 +28,14 @@ Each .NET Framework data provider included with the .NET Framework has its own c ## Example - The following code example demonstrates how to create a object to execute a stored procedure by setting its properties. A object is used to specify the input parameter to the stored procedure. The command is executed using the method, and the output from the is displayed in the console window. + The following code example demonstrates how to create a object to execute a stored procedure by setting its properties. A object is used to specify the input parameter to the stored procedure. The command is executed using the method, and the output from the is displayed in the console window. [!code-csharp[DataWorks SqlClient.StoredProcedure#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs#1)] [!code-vb[DataWorks SqlClient.StoredProcedure#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/source.vb#1)] ### Troubleshooting Commands - The .NET Framework Data Provider for SQL Server adds performance counters to enable you to detect intermittent problems related to failed command executions. For more information see [Performance Counters](performance-counters.md). + Microsoft.Data.SqlClient exposes Windows performance counters on .NET Framework and EventCounters on modern .NET. For more information, see [Performance Counters](performance-counters.md). ## See also diff --git a/docs/framework/data/adonet/factory-model-overview.md b/docs/framework/data/adonet/factory-model-overview.md index 40fdc44bd20c0..20a8d62c432cf 100644 --- a/docs/framework/data/adonet/factory-model-overview.md +++ b/docs/framework/data/adonet/factory-model-overview.md @@ -1,12 +1,12 @@ --- description: "Learn more about: Factory Model Overview" title: "Factory Model Overview" -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: b5dc81c4-7554-44b9-b513-769bd61e2e7b --- # Factory Model Overview -ADO.NET 2.0 introduced new base classes in the namespace. The base classes are abstract, which means that they can't be directly instantiated. They include , , and and are shared by the .NET Framework data providers, such as and . The addition of base classes simplifies adding functionality to the .NET Framework data providers without having to create new interfaces. +ADO.NET 2.0 introduced new base classes in the namespace. The base classes are abstract, which means that they can't be directly instantiated. They include , , and and are shared by ADO.NET data providers, such as and . The addition of base classes simplifies adding functionality to data providers without having to create new interfaces. ADO.NET 2.0 also introduced abstract base classes, which enable a developer to write generic data access code that does not depend on a specific data provider. diff --git a/docs/framework/data/adonet/floating-point-numbers.md b/docs/framework/data/adonet/floating-point-numbers.md index 7cbdbb942e1d9..69ea64c237060 100644 --- a/docs/framework/data/adonet/floating-point-numbers.md +++ b/docs/framework/data/adonet/floating-point-numbers.md @@ -1,12 +1,12 @@ --- description: "Learn more about: Floating-Point Numbers" title: "Floating-Point Numbers" -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: 73c218c6-1c44-4402-a167-4f6262629a91 --- # Floating-Point Numbers -This topic describes some of the issues that developers frequently encounter when they work with floating-point numbers in ADO.NET. These issues are caused by the way that computers store floating-point numbers, and are not specific to a particular provider such as or . +This topic describes some of the issues that developers frequently encounter when they work with floating-point numbers in ADO.NET. These issues are caused by the way that computers store floating-point numbers, and are not specific to a particular provider such as or . Floating-point numbers generally do not have an exact binary representation. Instead, the computer stores an approximation of the number. At different times, different numbers of binary digits may be used to represent the number. When a floating point number is converted from one representation to another representation, the least significant digits of that number may vary slightly. Conversion typically occurs when the number is cast from one type to another type. The variation occurs whether the conversion occurs within a database, between types that represent database values, or between types. Because of these changes, numbers that would logically be equal may have changes in their least-significant digits that cause them to have different values. The number of digits of precision in the number may be larger or smaller than expected. When formatted as a string, the number may not show the expected value. diff --git a/docs/framework/data/adonet/getschema-and-schema-collections.md b/docs/framework/data/adonet/getschema-and-schema-collections.md index ef339fb458345..2e1d9eec669dc 100644 --- a/docs/framework/data/adonet/getschema-and-schema-collections.md +++ b/docs/framework/data/adonet/getschema-and-schema-collections.md @@ -1,7 +1,7 @@ --- description: "Learn more about: GetSchema and Schema Collections" title: "GetSchema and Schema Collections" -ms.date: "03/30/2017" +ms.date: "10/19/2026" dev_langs: - "csharp" - "vb" @@ -18,10 +18,10 @@ The `Connection` classes in each of the .NET Framework managed providers impleme ### Retrieving Schema Collections Example - The following examples demonstrate how to use the method of the .NET Framework Data Provider for the SQL Server class to retrieve schema information about all of the tables contained in the `AdventureWorks` sample database: + The following examples demonstrate how to use the method of the class to retrieve schema information about all of the tables contained in the `AdventureWorks` sample database: ```vb -Imports System.Data.SqlClient +Imports Microsoft.Data.SqlClient Module Module1 Sub Main() @@ -58,7 +58,7 @@ End Module ```csharp using System; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; class Program { diff --git a/docs/framework/data/adonet/index.md b/docs/framework/data/adonet/index.md index 4716aa639d8e6..6c9ce35b58f40 100644 --- a/docs/framework/data/adonet/index.md +++ b/docs/framework/data/adonet/index.md @@ -2,13 +2,16 @@ title: "ADO.NET" description: Learn about ADO.NET, classes that expose data access services for .NET Framework programmers for creating distributed, data-sharing applications. titleSuffix: "" -ms.date: "03/30/2017" +ms.date: "10/19/2026" +ai-usage: ai-assisted ms.assetid: 5b96ed06-9759-4966-a797-a1d5f6ee50ca --- # ADO.NET ADO.NET is a set of classes that expose data access services for .NET Framework programmers. ADO.NET provides a rich set of components for creating distributed, data-sharing applications. It is an integral part of the .NET Framework, providing access to relational, XML, and application data. ADO.NET supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects used by applications, tools, languages, or Internet browsers. +For new SQL Server applications, use the [Microsoft.Data.SqlClient](https://www.nuget.org/packages/Microsoft.Data.SqlClient) NuGet package. For runnable C# and Visual Basic examples, see [ADO.NET code examples](ado-net-code-examples.md#sqlclient). For an existing application that uses `System.Data.SqlClient`, follow the [migration guide](/sql/connect/ado-net/migrate-system-data-sql-client-to-microsoft-data-sql-client). + ## In This Section [What's New in ADO.NET](whats-new.md)\ diff --git a/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md b/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md index bec24c314e7d9..f9334bd6fe77d 100644 --- a/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md +++ b/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md @@ -1,47 +1,54 @@ --- title: "Obtaining a DbProviderFactory" description: Learn how to obtain a DbProviderFactory from the DbProviderFactories class to work with specific data sources in .NET Framework. -ms.date: "03/30/2017" +ms.date: "10/19/2026" +ai-usage: ai-assisted dev_langs: - "csharp" - "vb" --- # Obtaining a DbProviderFactory -The process of obtaining a involves passing information about a data provider to the class. Based on this information, the method creates a strongly typed provider factory. For example, to create a , you can pass `GetFactory` a string with the provider name specified as "System.Data.SqlClient". The other overload of `GetFactory` takes a . Once you create the provider factory, you can then use its methods to create additional objects. Some of the methods of a `SqlClientFactory` include , , and . +The process of obtaining a involves passing information about a data provider to the class. Based on this information, the method returns a strongly typed provider factory. For example, after you register , pass `GetFactory` the provider name `Microsoft.Data.SqlClient`. Another overload of `GetFactory` takes a . Once you obtain the provider factory, you can then use its methods to create additional objects. Some of the methods of a `SqlClientFactory` include , , and . > [!NOTE] > The , , and classes also provide similar functionality. ## Registering DbProviderFactories - Each .NET Framework data provider that supports a factory-based class registers configuration information in the `DbProviderFactories` section of the **machine.config** file on the local computer. The following configuration file fragment shows the syntax and format for . +Install the [Microsoft.Data.SqlClient NuGet package](https://www.nuget.org/packages/Microsoft.Data.SqlClient) before you register its factory. + +On .NET Framework, add the following `system.data` section inside the `configuration` element of your application's `app.config` or `web.config` file. The `remove` element avoids duplicate registrations inherited from another configuration file. ```xml - + ``` - The `invariant` attribute identifies the underlying data provider. This three-part naming syntax is also used when creating a new factory and for identifying the provider in an application configuration file so that the provider name, along with its associated connection string, can be retrieved at runtime. +On modern .NET, configuration files don't register provider factories. Before you call `GetFactory`, call with `Microsoft.Data.SqlClient` as the provider name and as the factory instance. `RegisterFactory` isn't available on .NET Framework. + +The following examples register the factory in code for modern .NET. For .NET Framework, use the previous configuration entry and omit any `RegisterFactory` call. + +The invariant provider name identifies the underlying data provider. Use the same name for factory lookups and the `providerName` attribute of a connection string. ## Retrieving Provider Information - You can retrieve information about all of the data providers installed on the local computer by using the method. It returns a named `DbProviderFactories` that contains the columns described in the following table. + You can retrieve information about registered data providers by using the method. It returns a named `DbProviderFactories` that contains the columns described in the following table. The example values correspond to the .NET Framework configuration entry shown previously; assembly version details depend on the installed package. | Column ordinal | Column name | Example output | Description | |----------------|-----------------|--------------------------------------------|-------------------------------------------| -| 0 | `Name` | SqlClient Data Provider | Readable name for the data provider | -| 1 | `Description` | .Net Framework Data Provider for SqlServer | Readable description of the data provider | -| 2 | `InvariantName` | System.Data.SqlClient | Name that can be used programmatically to refer to the data provider| -| 3 | `AssemblyQualifiedName` | System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 | Fully qualified name of the factory class, which contains enough information to instantiate the object | +| 0 | `Name` | Microsoft SqlClient Data Provider | Readable name for the data provider | +| 1 | `Description` | Microsoft SqlClient Data Provider for SQL Server | Readable description of the data provider | +| 2 | `InvariantName` | Microsoft.Data.SqlClient | Name that can be used programmatically to refer to the data provider| +| 3 | `AssemblyQualifiedName` | Microsoft.Data.SqlClient.SqlClientFactory, Microsoft.Data.SqlClient | Assembly-qualified name of the factory class | This `DataTable` can be used to enable a user to select a at runtime. The selected `DataRow` can then be passed to the method to create a strongly typed . A selected can be passed to the `GetFactory` method to create the desired `DbProviderFactory` object. @@ -63,9 +70,9 @@ The process of obtaining a involves involves ### Retrieve a Connection String by Provider Name - In order to create a provider factory, you must supply a connection string as well as the provider name. This example demonstrates how to retrieve a connection string from an application configuration file by passing the provider name in the invariant format "*System.Data.ProviderName*". The code iterates through the . It returns the on success; otherwise `null` (`Nothing` in Visual Basic). If there are multiple entries for a provider, the first one found is returned. For more information and examples of retrieving connection strings from configuration files, see [Connection Strings and Configuration Files](connection-strings-and-configuration-files.md). + To create a connection through a provider factory, supply a connection string as well as the provider name. This example demonstrates how to retrieve a connection string from an application configuration file by passing the invariant provider name, such as `Microsoft.Data.SqlClient`. The code iterates through the . It returns the matching connection string on success; otherwise `null` (`Nothing` in Visual Basic). If there are multiple entries for a provider, the first one found is returned. For more information and examples of retrieving connection strings from configuration files, see [Connection Strings and Configuration Files](connection-strings-and-configuration-files.md). > [!NOTE] > A reference to `System.Configuration.dll` is required in order for the code to run. @@ -91,7 +98,7 @@ The process of obtaining a involves ## Creating the DbProviderFactory and DbConnection - This example demonstrates how to create a and object by passing it the provider name in the format "*System.Data.ProviderName*" and a connection string. A `DbConnection` object is returned on success; `null` (`Nothing` in Visual Basic) on any error. + This example demonstrates how to create a and object by passing it the invariant provider name, such as `Microsoft.Data.SqlClient`, and a connection string. A `DbConnection` object is returned on success; `null` (`Nothing` in Visual Basic) on any error. The code obtains the `DbProviderFactory` by calling . Then the method creates the object and the property is set to the connection string. diff --git a/docs/framework/data/adonet/performance-counters.md b/docs/framework/data/adonet/performance-counters.md index 13d6401cf5079..5176cd953be5f 100644 --- a/docs/framework/data/adonet/performance-counters.md +++ b/docs/framework/data/adonet/performance-counters.md @@ -1,18 +1,21 @@ --- title: "Performance Counters" description: Use ADO.NET performance counters to monitor your application status and its connection resources by using Windows Performance Monitor or programmatically. -ms.date: "03/30/2017" +ms.date: "10/19/2026" +ai-usage: ai-assisted dev_langs: - "csharp" - "vb" --- # Performance counters in ADO.NET -ADO.NET 2.0 introduced expanded support for performance counters that includes support for both and . The performance counters available in previous versions of ADO.NET have been deprecated and replaced with the new performance counters discussed in this topic. You can use ADO.NET performance counters to monitor the status of your application and the connection resources that it uses. Performance counters can be monitored by using Windows Performance Monitor or can be accessed programmatically using the class in the namespace. +On .NET Framework, Microsoft.Data.SqlClient exposes Windows performance counters to monitor your application and its connection resources. Install the [Microsoft.Data.SqlClient NuGet package](https://www.nuget.org/packages/Microsoft.Data.SqlClient) and use the `Microsoft.Data.SqlClient` namespace for the SQL examples in this article. Read these counters through Windows Performance Monitor or . + +On modern .NET, Microsoft.Data.SqlClient exposes EventCounters instead of Windows performance counters. For more information, see [Event counters in SqlClient](/sql/connect/ado-net/event-counters). ## Available Performance Counters - Currently there are 14 different performance counters available for and as described in the following table. Note that the names for the individual counters are not localized across regional versions of the Microsoft .NET Framework. + On .NET Framework, the following 14 performance counters are available for and . Note that the names for the individual counters are not localized across regional versions of the Microsoft .NET Framework. | Performance counter | Description | |----------------------------|--------------------------------------------------------------------------------| @@ -63,7 +66,7 @@ When using Windows Authentication (integrated security), you must monitor both t Option Explicit On Option Strict On -Imports System.Data.SqlClient +Imports Microsoft.Data.SqlClient Imports System.Diagnostics Imports System.Runtime.InteropServices @@ -204,7 +207,7 @@ End Class ```csharp using System; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/docs/framework/data/adonet/retrieving-database-schema-information.md b/docs/framework/data/adonet/retrieving-database-schema-information.md index 6d728236b92eb..2fd72b5466c3b 100644 --- a/docs/framework/data/adonet/retrieving-database-schema-information.md +++ b/docs/framework/data/adonet/retrieving-database-schema-information.md @@ -1,7 +1,7 @@ --- description: "Learn more about: Retrieving Database Schema Information" title: "Retrieving Database Schema Information" -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: 79038d52-f122-4fd4-9bfb-aaa22d6a114b --- # Retrieving Database Schema Information @@ -10,7 +10,7 @@ Obtaining schema information from a database is accomplished with the process of Each of the .NET Framework managed providers implement the `GetSchema` method in the `Connection` class, and the schema information that is returned from the `GetSchema` method comes in the form of a . The `GetSchema` method is an overloaded method that provides optional parameters for specifying the schema collection to return, and restricting the amount of information returned. - The .NET Framework Data Providers for OLE DB, ODBC, Oracle, and SqlClient provide a `GetSchemaTable` method that returns a DataTable describing the column metadata of the **DataReader**. + The .NET Framework Data Providers for OLE DB, ODBC, and Oracle, and Microsoft.Data.SqlClient provide a `GetSchemaTable` method that returns a DataTable describing the column metadata of the **DataReader**. The .NET Framework Data Provider for OLE DB also exposes schema information by using the method of the object. As arguments, `GetOleDbSchemaTable` takes an that identifies the schema information to return, and an array of restrictions on those returned columns. `GetOleDbSchemaTable` returns a populated with the requested schema information. @@ -26,7 +26,7 @@ Obtaining schema information from a database is accomplished with the process of Describes all of the common schema collections supported by all of the .NET Framework managed providers. [SQL Server Schema Collections](sql-server-schema-collections.md) - Describes the schema collection supported by the .NET Framework provider for SQL Server. + Describes the schema collections supported by Microsoft.Data.SqlClient. [Oracle Schema Collections](oracle-schema-collections.md) Describes the schema collection supported by the .NET Framework provider for Oracle. @@ -51,8 +51,8 @@ Obtaining schema information from a database is accomplished with the process of Describes the `GetSchema` method of the class. - - Describes the `GetSchema` method of the class. + + Describes the `GetSchema` method of the class. Describes the `GetSchemaTable` method of the class. @@ -66,8 +66,8 @@ Obtaining schema information from a database is accomplished with the process of Describes the `GetSchemaTable` method of the class. - - Describes the `GetSchemaTable` method of the class. + + Describes the `GetSchemaTable` method of the class. ## See also diff --git a/docs/framework/data/adonet/schema-restrictions.md b/docs/framework/data/adonet/schema-restrictions.md index 4b80b6102d9d4..9fcf2d0e966c9 100644 --- a/docs/framework/data/adonet/schema-restrictions.md +++ b/docs/framework/data/adonet/schema-restrictions.md @@ -1,7 +1,7 @@ --- description: "Learn more about schema restrictions, which are used to limit the amount of schema information returned from the GetSchema method." title: "Schema Restrictions" -ms.date: "03/30/2017" +ms.date: "10/20/2026" dev_langs: - "csharp" - "vb" @@ -10,7 +10,7 @@ dev_langs: The second optional parameter of the `GetSchema` method is the restrictions that are used to limit the amount of schema information returned. It's passed to the `GetSchema` method as an array of strings. The position in the array determines the values that you can pass, and this is equivalent to the restriction number. - For example, the following table describes the restrictions supported by the "Tables" schema collection using .NET Framework Data Provider for SQL Server. Additional restrictions for SQL Server schema collections are listed at the end of this article. + For example, the following table describes the restrictions supported by the "Tables" schema collection using Microsoft.Data.SqlClient. Additional restrictions for SQL Server schema collections are listed at the end of this article. | Restriction Name | Parameter Name | Restriction Default | Restriction Number | |------------------|----------------|---------------------|--------------------| @@ -33,14 +33,14 @@ The second optional parameter of the `GetSchema` method is the restrictions that ### Example - The following examples demonstrate how to use the method of the .NET Framework Data Provider for the SQL Server class to retrieve schema information about all of the tables contained in the `AdventureWorks` sample database, and to restrict the information returned to only those tables in the "Sales" schema: + The following examples demonstrate how to use the method of the class to retrieve schema information about all of the tables contained in the `AdventureWorks` sample database, and to restrict the information returned to only those tables in the "Sales" schema: ```vb -Imports System.Data.SqlClient +Imports Microsoft.Data.SqlClient Module Module1 Sub Main() - Dim connectionString As String = "..."; + Dim connectionString As String = "..." Dim restrictions(3) As String Using connection As New SqlConnection(connectionString) @@ -68,7 +68,7 @@ End Module ```csharp using System; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; class Program { diff --git a/docs/framework/data/adonet/secure-data-access.md b/docs/framework/data/adonet/secure-data-access.md index 7952c8696f701..dfca80933ddb4 100644 --- a/docs/framework/data/adonet/secure-data-access.md +++ b/docs/framework/data/adonet/secure-data-access.md @@ -1,7 +1,7 @@ --- description: "Learn more about secure data access and understand the security mechanisms available in the underlying data store or database." title: "Secure Data Access" -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: 473ebd69-21a3-4627-b95e-4e04d035c56f ms.custom: sfi-ropc-nochange --- @@ -11,7 +11,7 @@ To write secure ADO.NET code, you have to understand the security mechanisms ava ## Authentication, Authorization, and Permissions -When connecting to Microsoft SQL Server, you can use Windows Authentication, also known as Integrated Security, which uses the identity of the current active Windows user rather than passing a user ID and password. Using Windows Authentication is recommended for on-premises databases because user credentials aren't exposed in the connection string. If you can't use Windows Authentication to connect to SQL Server, then consider creating connection strings at runtime using the . +When connecting to Microsoft SQL Server, you can use Windows Authentication, also known as Integrated Security, which uses the identity of the current active Windows user rather than passing a user ID and password. Using Windows Authentication is recommended for on-premises databases because user credentials aren't exposed in the connection string. If you can't use Windows Authentication to connect to SQL Server, then consider creating connection strings at runtime using the . [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] diff --git a/docs/framework/data/adonet/snippets/ado-net-code-examples/csharp/Program.cs b/docs/framework/data/adonet/snippets/ado-net-code-examples/csharp/Program.cs new file mode 100644 index 0000000000000..f4fb8890bac2d --- /dev/null +++ b/docs/framework/data/adonet/snippets/ado-net-code-examples/csharp/Program.cs @@ -0,0 +1,33 @@ +// +using System; +using System.Data; +using Microsoft.Data.SqlClient; + +class Program +{ + static void Main() + { + string connectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING") + ?? throw new InvalidOperationException("Set the SQL_CONNECTION_STRING environment variable."); + + const string queryString = + "SELECT ProductID, UnitPrice, ProductName FROM dbo.Products " + + "WHERE UnitPrice > @pricePoint ORDER BY UnitPrice DESC;"; + + using (SqlConnection connection = new SqlConnection(connectionString)) + using (SqlCommand command = new SqlCommand(queryString, connection)) + { + command.Parameters.Add("@pricePoint", SqlDbType.Money).Value = 5m; + connection.Open(); + + using (SqlDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + Console.WriteLine($"{reader.GetInt32(0)}\t{reader.GetDecimal(1)}\t{reader.GetString(2)}"); + } + } + } + } +} +// diff --git a/docs/framework/data/adonet/snippets/ado-net-code-examples/csharp/SqlClientExample.csproj b/docs/framework/data/adonet/snippets/ado-net-code-examples/csharp/SqlClientExample.csproj new file mode 100644 index 0000000000000..fe559ff257401 --- /dev/null +++ b/docs/framework/data/adonet/snippets/ado-net-code-examples/csharp/SqlClientExample.csproj @@ -0,0 +1,15 @@ + + + + Exe + net10.0;net481 + latest + enable + + + + + + + + diff --git a/docs/framework/data/adonet/snippets/ado-net-code-examples/vb/Program.vb b/docs/framework/data/adonet/snippets/ado-net-code-examples/vb/Program.vb new file mode 100644 index 0000000000000..4e200e5906d2e --- /dev/null +++ b/docs/framework/data/adonet/snippets/ado-net-code-examples/vb/Program.vb @@ -0,0 +1,33 @@ +' +Option Explicit On +Option Strict On + +Imports System +Imports System.Data +Imports Microsoft.Data.SqlClient + +Module Program + Sub Main() + Dim connectionString As String = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING") + If String.IsNullOrWhiteSpace(connectionString) Then + Throw New InvalidOperationException("Set the SQL_CONNECTION_STRING environment variable.") + End If + + Const queryString As String = + "SELECT ProductID, UnitPrice, ProductName FROM dbo.Products " & + "WHERE UnitPrice > @pricePoint ORDER BY UnitPrice DESC;" + + Using connection As New SqlConnection(connectionString), + command As New SqlCommand(queryString, connection) + command.Parameters.Add("@pricePoint", SqlDbType.Money).Value = 5D + connection.Open() + + Using reader As SqlDataReader = command.ExecuteReader() + While reader.Read() + Console.WriteLine($"{reader.GetInt32(0)}{vbTab}{reader.GetDecimal(1)}{vbTab}{reader.GetString(2)}") + End While + End Using + End Using + End Sub +End Module +' diff --git a/docs/framework/data/adonet/snippets/ado-net-code-examples/vb/SqlClientExample.vbproj b/docs/framework/data/adonet/snippets/ado-net-code-examples/vb/SqlClientExample.vbproj new file mode 100644 index 0000000000000..b9628df9c7ecb --- /dev/null +++ b/docs/framework/data/adonet/snippets/ado-net-code-examples/vb/SqlClientExample.vbproj @@ -0,0 +1,15 @@ + + + + Exe + SqlClientExample + net10.0;net481 + On + + + + + + + + diff --git a/docs/framework/data/adonet/sql-server-connection-pooling.md b/docs/framework/data/adonet/sql-server-connection-pooling.md index b5eb39e8fb9ca..7fb3c4b8a1edc 100644 --- a/docs/framework/data/adonet/sql-server-connection-pooling.md +++ b/docs/framework/data/adonet/sql-server-connection-pooling.md @@ -1,7 +1,7 @@ --- title: "SQL Server Connection Pooling" description: Learn how ADO.NET minimizes the cost of opening connections by using SQL Server connection pooling, which reduces overhead for new connections. -ms.date: "03/30/2017" +ms.date: "10/19/2026" dev_langs: - "csharp" - "vb" @@ -17,7 +17,7 @@ Connecting to a database server typically consists of several time-consuming ste Connection pooling reduces the number of times that new connections must be opened. The *pooler* maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls `Open` on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls `Close` on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next `Open` call. - Only connections with the same configuration can be pooled. ADO.NET keeps several pools at the same time, one for each configuration. Connections are separated into pools by connection string, and by Windows identity when integrated security is used. Connections are also pooled based on whether they are enlisted in a transaction. When using , the instance affects the connection pool. Different instances of will use different connection pools, even if the user ID and password are the same. + Only connections with the same configuration can be pooled. Microsoft.Data.SqlClient keeps several pools at the same time, one for each configuration. Connections are separated into pools by connection string, and by Windows identity when integrated security is used. Connections are also pooled based on whether they are enlisted in a transaction. When using , the instance affects the connection pool. Different instances of will use different connection pools, even if the user ID and password are the same. Pooling connections can significantly enhance the performance and scalability of your application. By default, connection pooling is enabled in ADO.NET. Unless you explicitly disable it, the pooler optimizes the connections as they are opened and closed in your application. You can also supply several connection string modifiers to control connection pooling behavior. For more information, see "Controlling Connection Pooling with Connection String Keywords" later in this topic. @@ -28,7 +28,7 @@ Connecting to a database server typically consists of several time-consuming ste When a connection is first opened, a connection pool is created based on an exact matching algorithm that associates the pool with the connection string in the connection. Each connection pool is associated with a distinct connection string. When a new connection is opened, if the connection string is not an exact match to an existing pool, a new pool is created. Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity. Connection strings must also be an exact match; keywords supplied in a different order for the same connection will be pooled separately. - In the following C# example, three new objects are created, but only two connection pools are required to manage them. Note that the first and second connection strings differ by the value assigned for `Initial Catalog`. + In the following C# example, three new objects are created, but only two connection pools are required to manage them. Note that the first and second connection strings differ by the value assigned for `Initial Catalog`. ```csharp using (SqlConnection connection = new SqlConnection( @@ -64,7 +64,7 @@ using (SqlConnection connection = new SqlConnection( A connection pool is created for each unique connection string. When a pool is created, multiple connection objects are created and added to the pool so that the minimum pool size requirement is satisfied. Connections are added to the pool as needed, up to the maximum pool size specified (100 is the default). Connections are released back into the pool when they are closed or disposed. - When a object is requested, it is obtained from the pool if a usable connection is available. To be usable, a connection must be unused, have a matching transaction context or be unassociated with any transaction context, and have a valid link to the server. + When a object is requested, it is obtained from the pool if a usable connection is available. To be usable, a connection must be unused, have a matching transaction context or be unassociated with any transaction context, and have a valid link to the server. The connection pooler satisfies requests for connections by reallocating connections as they are released back into the pool. If the maximum pool size has been reached and no usable connection is available, the request is queued. The pooler then tries to reclaim any connections until the time-out is reached (the default is 15 seconds). If the pooler cannot satisfy the request before the connection times out, an exception is thrown. @@ -84,7 +84,7 @@ For more info about the events associated with opening and closing connections, ## Clear the pool - ADO.NET 2.0 introduced two new methods to clear the pool: and . `ClearAllPools` clears the connection pools for a given provider, and `ClearPool` clears the connection pool that is associated with a specific connection. If there are connections being used at the time of the call, they are marked appropriately. When they are closed, they are discarded instead of being returned to the pool. + Microsoft.Data.SqlClient provides two methods to clear the pool: and . `ClearAllPools` clears the connection pools for a given provider, and `ClearPool` clears the connection pool that is associated with a specific connection. If there are connections being used at the time of the call, they are marked appropriately. When they are closed, they are discarded instead of being returned to the pool. ## Transaction support @@ -94,7 +94,7 @@ For more info about the events associated with opening and closing connections, ## Control connection pooling with connection string keywords - The `ConnectionString` property of the object supports connection string key/value pairs that can be used to adjust the behavior of the connection pooling logic. For more information, see . + The `ConnectionString` property of the object supports connection string key/value pairs that can be used to adjust the behavior of the connection pooling logic. For more information, see . ## Pool fragmentation diff --git a/docs/framework/data/adonet/sql-server-data-type-mappings.md b/docs/framework/data/adonet/sql-server-data-type-mappings.md index 1d430688b4dce..0e7f4797786a2 100644 --- a/docs/framework/data/adonet/sql-server-data-type-mappings.md +++ b/docs/framework/data/adonet/sql-server-data-type-mappings.md @@ -1,49 +1,49 @@ --- title: "SQL Server Data Type Mappings" description: Learn about mapping between the different type systems for SQL Server and the .NET Framework. This article summarizes how the systems interact in ADO.NET. -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: fafdc31a-f435-4cd3-883f-1dfadd971277 --- # SQL Server Data Type Mappings -SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. To maintain data integrity when reading and writing data, the exposes SQL Server–specific typed accessor methods that return objects of as well as accessor methods that return .NET Framework types. Both SQL Server types and .NET Framework types are also represented by enumerations in the and classes, which you can use when specifying data types. +SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. To maintain data integrity when reading and writing data, exposes SQL Server-specific typed accessor methods that return objects of as well as accessor methods that return .NET Framework types. Both SQL Server types and .NET Framework types are also represented by enumerations in the and classes, which you can use when specifying data types. - The following table shows the inferred .NET Framework type, the and enumerations, and the accessor methods for the . + The following table shows the inferred .NET Framework type, the and enumerations, and the accessor methods for the . |SQL Server Database Engine type|.NET Framework type|SqlDbType enumeration|SqlDataReader SqlTypes typed accessor|DbType enumeration|SqlDataReader DbType typed accessor| |-------------------------------------|-------------------------|---------------------------|-------------------------------------------|------------------------|-----------------------------------------| -|bigint|Int64||||| -|binary|Byte[]||||| -|bit|Boolean||||| -|char|String

Char[]|||,

|

| -|date 1

(SQL Server 2008 and later)|DateTime| 1|| 1|| -|datetime|DateTime||||| -|datetime2

(SQL Server 2008 and later)|DateTime||None||| -|datetimeoffset

(SQL Server 2008 and later)|DateTimeOffset||none||| -|decimal|Decimal||||| -|FILESTREAM attribute (varbinary(max))|Byte[]||||| -|float|Double||||| -|image|Byte[]||||| -|int|Int32||||| -|money|Decimal||||| -|nchar|String

Char[]||||

| -|ntext|String

Char[]||||

| -|numeric|Decimal||||| -|nvarchar|String

Char[]||||

| -|real|Single||||| -|rowversion|Byte[]||||| -|smalldatetime|DateTime||||| -|smallint|Int16||||| -|smallmoney|Decimal||||| -|sql_variant|Object 2|| 2|| 2| -|text|String

Char[]||||

| -|time

(SQL Server 2008 and later)|TimeSpan||none||| -|timestamp|Byte[]||||| -|tinyint|Byte||||| -|uniqueidentifier|Guid||||| -|varbinary|Byte[]||||| -|varchar|String

Char[]|||, |

| -|xml|Xml||||none| +|bigint|Int64||||| +|binary|Byte[]||||| +|bit|Boolean||||| +|char|String

Char[]|||,

|

| +|date 1

(SQL Server 2008 and later)|DateTime| 1|| 1|| +|datetime|DateTime||||| +|datetime2

(SQL Server 2008 and later)|DateTime||None||| +|datetimeoffset

(SQL Server 2008 and later)|DateTimeOffset||none||| +|decimal|Decimal||||| +|FILESTREAM attribute (varbinary(max))|Byte[]||||| +|float|Double||||| +|image|Byte[]||||| +|int|Int32||||| +|money|Decimal||||| +|nchar|String

Char[]||||

| +|ntext|String

Char[]||||

| +|numeric|Decimal||||| +|nvarchar|String

Char[]||||

| +|real|Single||||| +|rowversion|Byte[]||||| +|smalldatetime|DateTime||||| +|smallint|Int16||||| +|smallmoney|Decimal||||| +|sql_variant|Object 2|| 2|| 2| +|text|String

Char[]||||

| +|time

(SQL Server 2008 and later)|TimeSpan||none||| +|timestamp|Byte[]||||| +|tinyint|Byte||||| +|uniqueidentifier|Guid||||| +|varbinary|Byte[]||||| +|varchar|String

Char[]|||, |

| +|xml|Xml||||none| 1 You cannot set the `DbType` property of a `SqlParameter` to `SqlDbType.Date`. 2 Use a specific typed accessor if you know the underlying type of the `sql_variant`. diff --git a/docs/framework/data/adonet/sql-server-schema-collections.md b/docs/framework/data/adonet/sql-server-schema-collections.md index afe5ad428ab6e..7534441f298a6 100644 --- a/docs/framework/data/adonet/sql-server-schema-collections.md +++ b/docs/framework/data/adonet/sql-server-schema-collections.md @@ -1,12 +1,12 @@ --- description: "Learn more about: SQL Server Schema Collections" title: "SQL Server Schema Collections" -ms.date: "03/30/2017" +ms.date: "10/19/2026" ms.assetid: c6403cc3-d78b-4f85-bab1-ada7a3446ec5 --- # SQL Server Schema Collections -The Microsoft .NET Framework Data Provider for SQL Server supports additional schema collections in addition to the common schema collections. The schema collections vary slightly by the version of SQL Server you are using. To determine the list of supported schema collections, call the `GetSchema` method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. +Microsoft.Data.SqlClient supports additional schema collections in addition to the common schema collections. The schema collections vary slightly by the version of SQL Server you are using. To determine the list of supported schema collections, call the `GetSchema` method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. ## Databases diff --git a/docs/framework/data/adonet/sqlclient-streaming-support.md b/docs/framework/data/adonet/sqlclient-streaming-support.md index 36a318dda694d..78805182e18cf 100644 --- a/docs/framework/data/adonet/sqlclient-streaming-support.md +++ b/docs/framework/data/adonet/sqlclient-streaming-support.md @@ -1,34 +1,34 @@ --- description: "Learn more about streaming support between SQL Server and an application, which supports unstructured data on the server." title: "SqlClient Streaming Support" -ms.date: "03/30/2017" +ms.date: "10/20/2026" --- # SqlClient streaming support -Streaming support between SQL Server and an application (new in .NET Framework 4.5) supports unstructured data on the server (documents, images, and media files). A SQL Server database can store binary large objects (BLOBs), but retrieving BLOBS can use a lot of memory. +Microsoft.Data.SqlClient supports streams between SQL Server and an application for unstructured data on the server (documents, images, and media files). A SQL Server database can store binary large objects (BLOBs), but retrieving BLOBS can use a lot of memory. For the examples in this article, install the [Microsoft.Data.SqlClient NuGet package](https://www.nuget.org/packages/Microsoft.Data.SqlClient). Streaming support to and from SQL Server simplifies writing applications that stream data, without having to fully load the data into memory, resulting in fewer memory overflow exceptions. Streaming support will also enable middle-tier applications to scale better, especially in scenarios where business objects connect to SQL Azure in order to send, retrieve, and manipulate large BLOBs. -> [!WARNING] -> Asynchronous calls are not supported if an application also uses the `Context Connection` connection string keyword. +> [!NOTE] +> Microsoft.Data.SqlClient doesn't support `Context Connection=true`. When you construct or assign its `ConnectionString` property with that setting, the driver throws with the message `Connecting to the context connection using Microsoft.Data.SqlClient is not supported.` The exception occurs before you call `Open` or `OpenAsync`; the setting isn't ignored. > > The members added to support streaming are used to retrieve data from queries and to pass parameters to queries and stored procedures. The streaming feature addresses basic OLTP and data migration scenarios and is applicable to on-premises and off-premises data migrations environments. ## Streaming Support from SQL Server -Streaming support from SQL Server introduces new functionality in the and in the classes in order to get , , and objects and react to them. These classes are used to retrieve data from queries. As a result, Streaming support from SQL Server addresses OLTP scenarios and applies to on-premises and off-premises environments. +Streaming support from SQL Server uses the and classes to get , , and objects and react to them. These classes are used to retrieve data from queries. As a result, Streaming support from SQL Server addresses OLTP scenarios and applies to on-premises and off-premises environments. -The following members were added to to enable streaming support from SQL Server: +The following members of support streams from SQL Server: -- -- -- -- -- -- +- +- +- +- +- +- The following members were added to to enable streaming support from SQL Server: @@ -38,27 +38,27 @@ The following members were added to to en ## Streaming Support to SQL Server -Streaming support to SQL Server introduces new functionality in the class so it can accept and react to , , and objects. is used to pass parameters to queries and stored procedures. +Streaming support to SQL Server uses the class to accept and react to , , and objects. is used to pass parameters to queries and stored procedures. -Disposing a object or calling must cancel any streaming operation. If an application sends , cancellation is not guaranteed. +To request cancellation of a streaming operation, call or pass to the asynchronous execute method. Cancellation isn't guaranteed. Disposing the command doesn't request cancellation. -The following types will accept a of : +The following types will accept a of : - **Binary** - **VarBinary** -The following types will accept a of : +The following types will accept a of : - **Char** - **NChar** - **NVarChar** - **Xml** -The **Xml** type will accept a of . +The **Xml** type will accept a of . - can accept values of type , , and . + can accept values of type , , and . -The , , and object will be transferred up to the value defined by the . +The , , and object will be transferred up to the value defined by the . ## Sample: Streaming from SQL Server @@ -84,15 +84,15 @@ GO The sample shows how to do the following: - Avoid blocking a user-interface thread by providing an asynchronous way to retrieve large files. -- Transfer a large text file from SQL Server in .NET Framework 4.5. -- Transfer a large XML file from SQL Server in .NET Framework 4.5. +- Transfer a large text file from SQL Server with Microsoft.Data.SqlClient. +- Transfer a large XML file from SQL Server with Microsoft.Data.SqlClient. - Retrieve data from SQL Server. - Transfer large files (BLOBs) from one SQL Server database to another without running out of memory. ```csharp using System; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.IO; using System.Threading.Tasks; using System.Xml; @@ -110,7 +110,7 @@ namespace StreamingFromServer { Console.WriteLine("Done"); } - // Retrieve a large BLOB from SQL Server in .NET Framework 4.5 using the asynchronous capability. + // Retrieve a large BLOB from SQL Server asynchronously. private static async Task CopyBinaryValueToFile() { string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "binarydata.bin"); @@ -138,7 +138,7 @@ namespace StreamingFromServer { } } - // Transfer a large Text File from SQL Server in .NET Framework 4.5. + // Transfer a large text file from SQL Server. private static async Task PrintTextValues() { using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); @@ -173,7 +173,7 @@ namespace StreamingFromServer { } } - // Transfer a large Xml Document from SQL Server in .NET Framework 4.5. + // Transfer a large XML document from SQL Server. private static async Task PrintXmlValues() { using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); @@ -216,7 +216,7 @@ namespace StreamingFromServer { } } - // Transfer a large Xml Document from SQL Server in .NET Framework 4.5. + // Transfer a large XML document from SQL Server. // This goes via NVarChar and TextReader to enable asynchronous reading. private static async Task PrintXmlValuesViaNVarChar() { XmlReaderSettings xmlSettings = new XmlReaderSettings() { @@ -302,8 +302,8 @@ GO The sample shows how to do the following: -- Transfer a large BLOB to SQL Server in .NET Framework 4.5. -- Transfer a large text file to SQL Server in .NET Framework 4.5. +- Transfer a large BLOB to SQL Server with Microsoft.Data.SqlClient. +- Transfer a large text file to SQL Server with Microsoft.Data.SqlClient. - Use the new asynchronous feature to transfer a large BLOB. - Use the new asynchronous feature and the await keyword to transfer a large BLOB. - Cancel the transfer of a large BLOB. @@ -312,7 +312,7 @@ The sample shows how to do the following: ```csharp using System; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -367,7 +367,7 @@ namespace StreamingToServer { } } - // Transfer a large BLOB to SQL Server in .NET Framework 4.5. + // Transfer a large BLOB to SQL Server. private static async Task StreamBLOBToServer() { using (SqlConnection conn = new SqlConnection(connectionString)) { await conn.OpenAsync(); @@ -385,7 +385,7 @@ namespace StreamingToServer { } } - // Transfer a large Text File to SQL Server in .NET Framework 4.5. + // Transfer a large text file to SQL Server. private static async Task StreamTextToServer() { using (SqlConnection conn = new SqlConnection(connectionString)) { await conn.OpenAsync(); @@ -435,7 +435,7 @@ This sample demonstrates how to asynchronously stream a large BLOB from one SQL ```csharp using System; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; using System.IO; using System.Threading; using System.Threading.Tasks; diff --git a/docs/framework/data/adonet/system-transactions-integration-with-sql-server.md b/docs/framework/data/adonet/system-transactions-integration-with-sql-server.md index 31500bc8b67fe..b1f7d4c496464 100644 --- a/docs/framework/data/adonet/system-transactions-integration-with-sql-server.md +++ b/docs/framework/data/adonet/system-transactions-integration-with-sql-server.md @@ -1,7 +1,7 @@ --- description: "Learn more about System.Transactions integration with SQL Server, which exposes transactions in a way that is fully integrated in .NET Framework." title: "System.Transactions Integration with SQL Server" -ms.date: "03/30/2017" +ms.date: "10/20/2026" dev_langs: - "csharp" - "vb" @@ -13,28 +13,28 @@ ms.custom: sfi-ropc-nochange In addition to the programmability enhancements, and ADO.NET can work together to coordinate optimizations when you work with transactions. A promotable transaction is a lightweight (local) transaction that can be automatically promoted to a fully distributed transaction on an as-needed basis. - Starting with ADO.NET 2.0, supports promotable transactions when you work with SQL Server. A promotable transaction does not invoke the added overhead of a distributed transaction unless the added overhead is required. Promotable transactions are automatic and require no intervention from the developer. + Microsoft.Data.SqlClient supports promotable transactions when you work with SQL Server. A promotable transaction does not invoke the added overhead of a distributed transaction unless the added overhead is required. Promotable transactions are automatic and require no intervention from the developer. - Promotable transactions are only available when you use the .NET Framework Data Provider for SQL Server (`SqlClient`) with SQL Server. + For the examples in this article, install the [Microsoft.Data.SqlClient NuGet package](https://www.nuget.org/packages/Microsoft.Data.SqlClient) and import the `Microsoft.Data.SqlClient` namespace. ## Creating Promotable Transactions - The .NET Framework Provider for SQL Server provides support for promotable transactions, which are handled through the classes in the .NET Framework namespace. Promotable transactions optimize distributed transactions by deferring creating a distributed transaction until it is needed. If only one resource manager is required, no distributed transaction occurs. + Microsoft.Data.SqlClient provides support for promotable transactions, which are handled through the classes in the namespace. Promotable transactions optimize distributed transactions by deferring creating a distributed transaction until it is needed. If only one resource manager is required, no distributed transaction occurs. > [!NOTE] > In a partially trusted scenario, the is required when a transaction is promoted to a distributed transaction. ## Promotable Transaction Scenarios - Distributed transactions typically consume significant system resources, being managed by Microsoft Distributed Transaction Coordinator (MS DTC), which integrates all the resource managers accessed in the transaction. A promotable transaction is a special form of a transaction that effectively delegates the work to a simple SQL Server transaction. , , and SQL Server coordinate the work involved in handling the transaction, promoting it to a full distributed transaction as needed. + Distributed transactions typically consume significant system resources, being managed by Microsoft Distributed Transaction Coordinator (MS DTC), which integrates all the resource managers accessed in the transaction. A promotable transaction is a special form of a transaction that effectively delegates the work to a simple SQL Server transaction. , , and SQL Server coordinate the work involved in handling the transaction, promoting it to a full distributed transaction as needed. The benefit of using promotable transactions is that when a connection is opened by using an active transaction, and no other connections are opened, the transaction commits as a lightweight transaction, instead of incurring the additional overhead of a full distributed transaction. ### Connection String Keywords - The property supports a keyword, `Enlist`, which indicates whether will detect transactional contexts and automatically enlist the connection in a distributed transaction. If `Enlist=true`, the connection is automatically enlisted in the opening thread's current transaction context. If `Enlist=false`, the `SqlClient` connection does not interact with a distributed transaction. The default value for `Enlist` is true. If `Enlist` is not specified in the connection string, the connection is automatically enlisted in a distributed transaction if one is detected when the connection is opened. + The property supports a keyword, `Enlist`, which indicates whether will detect transactional contexts and automatically enlist the connection in a distributed transaction. If `Enlist=true`, the connection is automatically enlisted in the opening thread's current transaction context. If `Enlist=false`, the `SqlClient` connection does not interact with a distributed transaction. The default value for `Enlist` is true. If `Enlist` is not specified in the connection string, the connection is automatically enlisted in a distributed transaction if one is detected when the connection is opened. - The `Transaction Binding` keywords in a connection string control the connection's association with an enlisted `System.Transactions` transaction. It is also available through the property of a . + The `Transaction Binding` keywords in a connection string control the connection's association with an enlisted `System.Transactions` transaction. It is also available through the property of a . The following table describes the possible values. @@ -49,19 +49,19 @@ ms.custom: sfi-ropc-nochange We recommend that you use a `using` block to make sure that is called on the object when the using block is exited. Failure to commit or roll back pending transactions can significantly damage performance because the default time-out for the is one minute. If you do not use a `using` statement, you must perform all work in a `Try` block and explicitly call the method in the `Finally` block. - If an exception occurs in the , the transaction is marked as inconsistent and is abandoned. It will be rolled back when the is disposed. If no exception occurs, participating transactions commit. + If an exception leaves the before you call , the transaction rolls back when the scope is disposed. If you catch an exception inside the scope, don't call `Complete` after the failed operation. > [!NOTE] > The `TransactionScope` class creates a transaction with a of `Serializable` by default. Depending on your application, you might want to consider lowering the isolation level to avoid high contention in your application. > [!NOTE] -> We recommend that you perform only updates, inserts, and deletes within distributed transactions because they consume significant database resources. Select statements may lock database resources unnecessarily, and in some scenarios, you may have to use transactions for selects. Any non-database work should be done outside the scope of the transaction, unless it involves other transacted resource managers. Although an exception in the scope of the transaction prevents the transaction from committing, the class has no provision for rolling back any changes your code has made outside the scope of the transaction itself. If you have to take some action when the transaction is rolled back, you must write your own implementation of the interface and explicitly enlist in the transaction. +> We recommend that you perform only updates, inserts, and deletes within distributed transactions because they consume significant database resources. Select statements may lock database resources unnecessarily, and in some scenarios, you may have to use transactions for selects. Any non-database work should be done outside the scope of the transaction, unless it involves other transacted resource managers. The class can't roll back changes your code makes outside the transaction. If you have to take some action when the transaction is rolled back, you must write your own implementation of the interface and explicitly enlist in the transaction. ## Example Working with requires that you have a reference to System.Transactions.dll. - The following function demonstrates how to create a promotable transaction against two different SQL Server instances, represented by two different objects, which are wrapped in a block. The code creates the block with a `using` statement and opens the first connection, which automatically enlists it in the . The transaction is initially enlisted as a lightweight transaction, not a full distributed transaction. The second connection is enlisted in the only if the command in the first connection does not throw an exception. When the second connection is opened, the transaction is automatically promoted to a full distributed transaction. The method is invoked, which commits the transaction only if no exceptions have been thrown. If an exception has been thrown at any point in the block, `Complete` will not be called, and the distributed transaction will roll back when the is disposed at the end of its `using` block. + The following function demonstrates how to create a promotable transaction against two different SQL Server instances, represented by two different objects, which are wrapped in a block. The code creates the block with a `using` statement and opens the first connection, which automatically enlists it in the . The transaction is initially enlisted as a lightweight transaction, not a full distributed transaction. The second connection is enlisted in the only if the command in the first connection does not throw an exception. When the second connection is opened, the transaction is automatically promoted to a full distributed transaction. The method is invoked, which commits the transaction only if no exceptions have been thrown. If an exception has been thrown at any point in the block, `Complete` will not be called, and the distributed transaction will roll back when the is disposed at the end of its `using` block. ```csharp // This function takes arguments for the 2 connection strings and commands in order @@ -110,9 +110,13 @@ static public int CreateTransactionScope( SqlCommand command2 = new SqlCommand(commandText2, connection2); returnValue = command2.ExecuteNonQuery(); writer.WriteLine("Rows to be affected by command2: {0}", returnValue); + + // Complete only after both commands succeed. + scope.Complete(); } catch (Exception ex) { + returnValue = 0; // Display information that command2 failed. writer.WriteLine("returnValue for command2: {0}", returnValue); writer.WriteLine("Exception Message2: {0}", ex.Message); @@ -120,15 +124,12 @@ static public int CreateTransactionScope( } catch (Exception ex) { + returnValue = 0; // Display information that command1 failed. writer.WriteLine("returnValue for command1: {0}", returnValue); writer.WriteLine("Exception Message1: {0}", ex.Message); } } - - // If an exception has been thrown, Complete will not - // be called and the transaction is rolled back. - scope.Complete(); } // The returnValue is greater than 0 if the transaction committed. @@ -194,7 +195,11 @@ Public Function CreateTransactionScope( _ returnValue = command2.ExecuteNonQuery() writer.WriteLine("Rows to be affected by command2: {0}", returnValue) + ' Complete only after both commands succeed. + scope.Complete() + Catch ex As Exception + returnValue = 0 ' Display information that command2 failed. writer.WriteLine("returnValue for command2: {0}", returnValue) writer.WriteLine("Exception Message2: {0}", ex.Message) @@ -202,15 +207,12 @@ Public Function CreateTransactionScope( _ End Using Catch ex As Exception + returnValue = 0 ' Display information that command1 failed. writer.WriteLine("returnValue for command1: {0}", returnValue) writer.WriteLine("Exception Message1: {0}", ex.Message) End Try End Using - - ' If an exception has been thrown, Complete will - ' not be called and the transaction is rolled back. - scope.Complete() End Using ' The returnValue is greater than 0 if the transaction committed. diff --git a/docs/standard/threading/mutexes.md b/docs/standard/threading/mutexes.md index eb7e7d2e17a28..17f2af375d64e 100644 --- a/docs/standard/threading/mutexes.md +++ b/docs/standard/threading/mutexes.md @@ -34,7 +34,9 @@ In the case of a system-wide mutex, an abandoned mutex might indicate that an ap ## Local and system mutexes -Mutexes are of two types: local mutexes and named system mutexes. If you create a object using a constructor that accepts a name, it is associated with an operating-system object of that name. Named system mutexes are visible throughout the operating system and can be used to synchronize the activities of processes. You can create multiple objects that represent the same named system mutex, and you can use the method to open an existing named system mutex. +Mutexes are of two types: local mutexes and named system mutexes. If you create a object using a constructor that accepts a name, it is associated with an operating-system object of that name. Named mutex scope depends on the platform: on Windows, named mutexes are visible throughout the operating system; on Unix, they default to the current user. Named mutexes can synchronize processes that share their scope. You can create multiple objects that represent the same named mutex, and you can use the method to open an existing named mutex. + +To learn about the Unix default scope change and how to opt into global scope, see [Named mutexes default to user scope on Unix](../../core/compatibility/core-libraries/11/named-mutexes-unix-default-scope.md). A local mutex exists only within your process. It can be used by any thread in your process that has a reference to the local object. Each object is a separate local mutex. diff --git a/docs/standard/threading/overview-of-synchronization-primitives.md b/docs/standard/threading/overview-of-synchronization-primitives.md index 2637ca1681b88..54fbad3dde41f 100644 --- a/docs/standard/threading/overview-of-synchronization-primitives.md +++ b/docs/standard/threading/overview-of-synchronization-primitives.md @@ -64,7 +64,7 @@ For more information, see the API reference. The class, like , grants exclusive access to a shared resource. Use one of the [Mutex.WaitOne]() method overloads to request the ownership of a mutex. Like , has thread affinity and the thread that acquired a mutex must release it by calling the method. -Unlike , the class can be used for inter-process synchronization. To do that, use a named mutex, which is visible throughout the operating system. To create a named mutex instance, use a [Mutex constructor]() that specifies a name. You can also call the method to open an existing named system mutex. +Unlike , the class can be used for inter-process synchronization. To do that, use a named mutex. On Windows, named mutexes are visible throughout the operating system; on Unix, they default to the current user. To create a named mutex instance, use a [Mutex constructor]() that specifies a name. You can also call the method to open an existing named mutex. For the Unix default scope change, see [Named mutexes default to user scope on Unix](../../core/compatibility/core-libraries/11/named-mutexes-unix-default-scope.md). For more information, see the [Mutexes](mutexes.md) article and the API reference. diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/Project.csproj index dfc9c8c001e84..d6934374ac510 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/Project.csproj index dfc9c8c001e84..d6934374ac510 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/Project.csproj index c6a69b3bbd694..ea9c2e5a92020 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs index 505d08b65bd04..c261bc3e00370 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs @@ -5,7 +5,7 @@ static class Program { static void Main() { - var s = GetConnectionStringByProvider("System.Data.SqlClient"); + var s = GetConnectionStringByProvider("Microsoft.Data.SqlClient"); Console.WriteLine(s); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/Project.csproj index dfc9c8c001e84..d6934374ac510 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/Project.csproj index 7208d89833e41..36cb736aa6bd2 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/Project.csproj @@ -6,7 +6,6 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/Project.csproj index 3785d16ad2f1b..82c72383f0dee 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/Project.csproj @@ -7,6 +7,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/Project.csproj index 6b7c491de35c2..b74f573320fb5 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/Project.csproj @@ -9,6 +9,7 @@ - + + diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs index 892565c804156..5efe0fc996744 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs @@ -1,7 +1,7 @@ using System; using System.Configuration; using System.Data.Common; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; static class Program { @@ -52,7 +52,7 @@ static void ExecuteDbCommand(DbConnection connection) // // Given a provider, create the factory and connect to the data source. - // The provider invariant name is in the format System.Data.ProviderName. + // For SQL Server, use the Microsoft.Data.SqlClient provider invariant name. static DbConnection? CreateFactoryConnection(string providerName) { // Retrieve the connection string from the configuration file @@ -62,6 +62,13 @@ static void ExecuteDbCommand(DbConnection connection) // Create the factory if there's a valid connection string. if (connectionString != null) { +#if !NETFRAMEWORK + if (providerName == "Microsoft.Data.SqlClient") + { + DbProviderFactories.RegisterFactory(providerName, SqlClientFactory.Instance); + } +#endif + DbProviderFactory factory = DbProviderFactories.GetFactory(providerName); diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/Project.csproj index dfc9c8c001e84..d6934374ac510 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj index 41a1f6cd5f86c..f3d4045ee8b5c 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj @@ -6,6 +6,7 @@ - + + diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs index d71a389d6845c..cbf90ba62ff74 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs @@ -1,5 +1,6 @@ using System; using System.Data.Common; +using Microsoft.Data.SqlClient; static class Program { @@ -18,6 +19,13 @@ static DbConnection CreateDbConnection( { try { +#if !NETFRAMEWORK + if (providerName == "Microsoft.Data.SqlClient") + { + DbProviderFactories.RegisterFactory(providerName, SqlClientFactory.Instance); + } +#endif + DbProviderFactory factory = DbProviderFactories.GetFactory(providerName); diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj index 41a1f6cd5f86c..f3d4045ee8b5c 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj @@ -6,6 +6,7 @@ - + + diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs index 539f22de42422..15c3ef1660c0e 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs @@ -1,6 +1,7 @@ using System; using System.Data; using System.Data.Common; +using Microsoft.Data.SqlClient; static class Program { @@ -13,6 +14,10 @@ static void Main() // This example assumes a reference to System.Data.Common. static DataTable GetProviderFactoryClasses() { +#if !NETFRAMEWORK + DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance); +#endif + // Retrieve the installed providers and factories. DataTable table = DbProviderFactories.GetFactoryClasses(); diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/Project.csproj index 6e16082796ba9..571b48a6492c9 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/Project.csproj index 994f42896bf76..afd28c4929e03 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/Project.csproj index 901f8d82d108f..df999438e1faf 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/Project.csproj @@ -8,6 +8,5 @@ - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/Project.csproj deleted file mode 100644 index 3785d16ad2f1b..0000000000000 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/Project.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Library - net8.0 - enable - - - - - - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs deleted file mode 100644 index ace72c4f600a1..0000000000000 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs +++ /dev/null @@ -1,54 +0,0 @@ - -// -using System; -using System.Data.SqlClient; - -static class Program -{ - static void Main() - { - const string connectionString = - "Data Source=(local);Initial Catalog=Northwind;" - + "Integrated Security=true"; - - // Provide the query string with a parameter placeholder. - const string queryString = - "SELECT ProductID, UnitPrice, ProductName from dbo.products " - + "WHERE UnitPrice > @pricePoint " - + "ORDER BY UnitPrice DESC;"; - - // Specify the parameter value. - const int paramValue = 5; - - // Create and open the connection in a using block. This - // ensures that all resources will be closed and disposed - // when the code exits. - using (SqlConnection connection = - new(connectionString)) - { - // Create the Command and Parameter objects. - SqlCommand command = new(queryString, connection); - command.Parameters.AddWithValue("@pricePoint", paramValue); - - // Open the connection in a try/catch block. - // Create and execute the DataReader, writing the result - // set to the console window. - try - { - connection.Open(); - SqlDataReader reader = command.ExecuteReader(); - while (reader.Read()) - { - Console.WriteLine($"\t{reader[0]}\t{reader[1]}\t{reader[2]}"); - } - reader.Close(); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - } - Console.ReadLine(); - } - } - // -} diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/Project.csproj index bd76b7294a72a..564a9fedaba6d 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/Project.csproj @@ -10,7 +10,5 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/Project.csproj index 3785d16ad2f1b..a242a2264855e 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/Project.csproj @@ -7,6 +7,7 @@ - + + diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs index b75598af7a73e..04e57a8cab66b 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs @@ -1,6 +1,6 @@ using System; using System.Data; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; static class Program { diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/VB/Project.vbproj new file mode 100644 index 0000000000000..79ea1abfac102 --- /dev/null +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/VB/Project.vbproj @@ -0,0 +1,12 @@ + + + + Project + net10.0 + + + + + + + diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/VB/source.vb index 3436fe399acba..49da72a2f1879 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/VB/source.vb @@ -1,8 +1,6 @@ Option Explicit On Option Strict On Imports System.Data -Imports System.Data.OleDb -Imports System.Data.SqlClient Imports System.Configuration @@ -34,4 +32,3 @@ Class Program End Function ' End Class - diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/VB/Project.vbproj new file mode 100644 index 0000000000000..79ea1abfac102 --- /dev/null +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/VB/Project.vbproj @@ -0,0 +1,12 @@ + + + + Project + net10.0 + + + + + + + diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/VB/source.vb index 512689de5240c..e136361237e85 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/VB/source.vb @@ -5,7 +5,7 @@ Imports System.Configuration Class Program Shared Sub Main() - Dim s As String = GetConnectionStringByProvider("System.Data.SqlClient") + Dim s As String = GetConnectionStringByProvider("Microsoft.Data.SqlClient") Console.WriteLine(s) Console.ReadLine() End Sub diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/VB/Project.vbproj new file mode 100644 index 0000000000000..1379b6c6b4b36 --- /dev/null +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/VB/Project.vbproj @@ -0,0 +1,14 @@ + + + + Project + net10.0 + + + + + + + + + diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/VB/source.vb index 9db3b2213d7db..9642ffaa25769 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/VB/source.vb @@ -1,6 +1,5 @@ Imports System.Data -Imports System.Data.SqlClient -Imports System.Data.OleDb +Imports Microsoft.Data.SqlClient Imports System.Configuration Imports System.Data.Common @@ -49,7 +48,7 @@ Class Program ' ' Given a provider, create the factory and connect to the data source. - ' The provider invariant name is in the format System.Data.ProviderName. + ' Use Microsoft.Data.SqlClient as the SQL Server provider invariant name. Private Shared Function CreateDbConnection( _ ByVal providerName As String) As DbConnection @@ -60,6 +59,9 @@ Class Program ' Create the factory if there's a valid connection string. If Not connectionString Is Nothing Then +#If Not NETFRAMEWORK Then + DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance) +#End If Dim factory As DbProviderFactory = _ DbProviderFactories.GetFactory(providerName) diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/VB/Project.vbproj new file mode 100644 index 0000000000000..1379b6c6b4b36 --- /dev/null +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/VB/Project.vbproj @@ -0,0 +1,14 @@ + + + + Project + net10.0 + + + + + + + + + diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/VB/source.vb index 87b25e82b61d3..cd94a7b297f30 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/VB/source.vb @@ -1,14 +1,12 @@ Imports System.Data -Imports System.Data.SqlClient -Imports System.Data.OleDb +Imports Microsoft.Data.SqlClient Imports System.Configuration Imports System.Data.Common Class Program Shared Sub Main() - Dim c As DbConnection = CreateDbConnection("System.Data.OleDb") - 'Dim c As DbConnection = CreateDbConnection("System.Data.SqlClient") + Dim c As DbConnection = CreateDbConnection("Microsoft.Data.SqlClient") DbCommandSelect(c) Console.ReadLine() End Sub @@ -50,7 +48,7 @@ Class Program ' ' Given a provider, create the factory and connect to the data source. - ' The provider invariant name is in the format System.Data.ProviderName. + ' Use Microsoft.Data.SqlClient as the SQL Server provider invariant name. Private Shared Function CreateDbConnection( _ ByVal providerName As String) As DbConnection @@ -61,6 +59,9 @@ Class Program ' Create the factory if there's a valid connection string. If Not connectionString Is Nothing Then +#If Not NETFRAMEWORK Then + DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance) +#End If Dim factory As DbProviderFactory = _ DbProviderFactories.GetFactory(providerName) diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/VB/Project.vbproj new file mode 100644 index 0000000000000..ff2b41bc06b3e --- /dev/null +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/VB/Project.vbproj @@ -0,0 +1,13 @@ + + + + Project + net10.0 + + + + + + + + diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/VB/source.vb index 5b4a25c37a215..ce7ac9637bafb 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/VB/source.vb @@ -1,5 +1,5 @@ Imports System.Data -Imports System.Data.SqlClient +Imports Microsoft.Data.SqlClient Imports System.Configuration Imports System.Data.Common @@ -22,6 +22,9 @@ Class Program ' Create the DbProviderFactory and DbConnection. If Not connectionString Is Nothing Then Try +#If Not NETFRAMEWORK Then + DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance) +#End If Dim factory As DbProviderFactory = _ DbProviderFactories.GetFactory(providerName) @@ -42,4 +45,3 @@ Class Program End Function ' End Class - diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/VB/Project.vbproj new file mode 100644 index 0000000000000..ff2b41bc06b3e --- /dev/null +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/VB/Project.vbproj @@ -0,0 +1,13 @@ + + + + Project + net10.0 + + + + + + + + diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/VB/source.vb index 673da4bd42382..25471a1a9f072 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/VB/source.vb @@ -1,6 +1,5 @@ Imports System.Data -Imports System.Data.SqlClient -Imports System.Data.OleDb +Imports Microsoft.Data.SqlClient Imports System.Configuration Imports System.Data.Common @@ -14,6 +13,10 @@ Class Program ' This example assumes a reference to System.Data.Common. Private Shared Function GetProviderFactoryClasses() As DataTable +#If Not NETFRAMEWORK Then + DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", SqlClientFactory.Instance) +#End If + ' Retrieve the installed providers and factories. Dim table As DataTable = DbProviderFactories.GetFactoryClasses() @@ -30,4 +33,3 @@ Class Program End Function ' End Class - diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/VB/Project.vbproj index 9d03f1658176a..e049c8367694d 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/VB/Project.vbproj +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/VB/Project.vbproj @@ -7,7 +7,6 @@ - diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/VB/Project.vbproj index f23c85b603fd8..6af396cbc37d8 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/VB/Project.vbproj +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/VB/Project.vbproj @@ -7,7 +7,6 @@ - diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/VB/Project.vbproj index 893209cfd31a9..fde40dca64952 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/VB/Project.vbproj +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/VB/Project.vbproj @@ -7,7 +7,6 @@ - diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/VB/Project.vbproj deleted file mode 100644 index 6d21e5fcc8317..0000000000000 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/VB/Project.vbproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Library - net8.0 - - - - - - - diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/VB/source.vb deleted file mode 100644 index f38a80191aa25..0000000000000 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/VB/source.vb +++ /dev/null @@ -1,53 +0,0 @@ -' -Option Explicit On -Option Strict On - -Imports System.Data -Imports System.Data.SqlClient - -Public Class Program - Public Shared Sub Main() - - Dim connectionString As String = _ - "..." - - ' Provide the query string with a parameter placeholder. - Dim queryString As String = _ - "SELECT ProductID, UnitPrice, ProductName from dbo.Products " _ - & "WHERE UnitPrice > @pricePoint " _ - & "ORDER BY UnitPrice DESC;" - - ' Specify the parameter value. - Dim paramValue As Integer = 5 - - ' Create and open the connection in a using block. This - ' ensures that all resources will be closed and disposed - ' when the code exits. - Using connection As New SqlConnection(connectionString) - - ' Create the Command and Parameter objects. - Dim command As New SqlCommand(queryString, connection) - command.Parameters.AddWithValue("@pricePoint", paramValue) - - ' Open the connection in a try/catch block. - ' Create and execute the DataReader, writing the result - ' set to the console window. - Try - connection.Open() - Dim dataReader As SqlDataReader = _ - command.ExecuteReader() - Do While dataReader.Read() - Console.WriteLine( _ - vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}", _ - dataReader(0), dataReader(1), dataReader(2)) - Loop - dataReader.Close() - - Catch ex As Exception - Console.WriteLine(ex.Message) - End Try - Console.ReadLine() - End Using - End Sub -End Class -' diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/Project.vbproj b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/Project.vbproj index 6d21e5fcc8317..b0f5cc2b2bc5a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/Project.vbproj +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/Project.vbproj @@ -6,7 +6,8 @@ - + + diff --git a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/source.vb b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/source.vb index e4165e3d7dab5..624a6052b350a 100644 --- a/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/source.vb +++ b/samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/VB/source.vb @@ -1,5 +1,5 @@ Imports System.Data -Imports System.Data.SqlClient +Imports Microsoft.Data.SqlClient Class Program