Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions doc/samples/SqlConnection_RegisterSqlClientAgent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Data.SqlClient;

internal static class MiddlewareRegistration
{
// Register once during application startup, before opening any connections.
internal static void Register()
{
SqlConnection.RegisterSqlClientAgent(SqlClientAgent.EntityFramework);
}
}
41 changes: 41 additions & 0 deletions doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2294,6 +2294,47 @@ The following sample tries to open a connection to an invalid database to simula
</para>
</remarks>
</System.ICloneable.Clone>
<RegisterSqlClientAgent>
<summary>
Globally registers the middleware agent for physical connections opened by Microsoft.Data.SqlClient.
</summary>
<param name="id">The positive numeric identifier assigned to the middleware agent.</param>
<exception cref="T:System.ArgumentOutOfRangeException">

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This property won't throw out-of-range.

The numeric value of <paramref name="id" /> is zero.
</exception>
<exception cref="T:System.InvalidOperationException">
An agent was already registered programmatically or through application configuration.
</exception>
Comment thread
cheenamalhotra marked this conversation as resolved.
<example>
[!code-csharp[Register an agent](~/../sqlclient/doc/samples/SqlConnection_RegisterSqlClientAgent.cs)]
</example>
<remarks>
<para>
This API is intended only for approved middleware partners. Applications should not call it directly.
</para>
<para>
Register the agent once during application startup, before opening any connections. The first registration
applies process-wide and cannot be replaced. Existing physical connections are not updated after registration.
</para>
<para>
An agent can instead be registered from an application configuration file. Configuration is loaded before
programmatic registration and therefore takes precedence:
</para>
<code language="xml">
&lt;configuration&gt;
&lt;configSections&gt;
&lt;section name="SqlClientAgent"
type="Microsoft.Data.SqlClient.SqlClientAgentConfigurationSection,Microsoft.Data.SqlClient" /&gt;
&lt;/configSections&gt;
&lt;SqlClientAgent id="EntityFramework" /&gt;
&lt;/configuration&gt;
</code>
<para>
The <c>id</c> value can be an enum member name or a positive numeric value. Numeric values not declared by
<see cref="T:Microsoft.Data.SqlClient.SqlClientAgent" /> are accepted for forward compatibility.
</para>
</remarks>
</RegisterSqlClientAgent>
<WorkstationId>
<summary>
Gets a string that identifies the database client.
Expand Down
33 changes: 33 additions & 0 deletions src/Microsoft.Data.SqlClient/ref/Microsoft.Data.SqlClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,36 @@ public void LogError(string type, string method, string message) { }
public void LogInfo(string type, string method, string message) { }
}

/// <summary>
/// Identifies known middleware agents that use Microsoft.Data.SqlClient.
/// </summary>
[System.CLSCompliantAttribute(false)]
public enum SqlClientAgent : ushort
{
/// <summary>The Microsoft Entity Framework Core SQL Server provider.</summary>
EntityFramework = 1,
/// <summary>Microsoft Semantic Kernel.</summary>
SemanticKernel = 2,
/// <summary>Microsoft SQL Server Management Studio.</summary>
ManagementStudio = 3,
/// <summary>Microsoft SQL Server Management Objects.</summary>
SqlManagementObjects = 4,
/// <summary>Microsoft SQL Server Data-Tier Application Framework.</summary>
DataTierApplicationFramework = 5,
/// <summary>Microsoft SQL Tools Service.</summary>
SqlToolsService = 6,
/// <summary>Microsoft ASP.NET Core distributed SQL Server cache.</summary>
AspNetCoreDistributedSqlServerCache = 7,
/// <summary>Microsoft Entity Framework 6 SQL Server provider.</summary>
EntityFramework6 = 8,
/// <summary>Microsoft Azure Functions SQL extension.</summary>
AzureFunctionsSqlExtension = 9,
/// <summary>Microsoft Orleans ADO.NET providers.</summary>
OrleansAdoNet = 10,
/// <summary>Microsoft Durable Task SQL Server provider.</summary>
DurableTaskSqlServer = 11
}

/// <include file='../../../doc/snippets/Microsoft.Data.SqlClient/SqlClientMetaDataCollectionNames.xml' path='docs/members[@name="SqlClientMetaDataCollectionNames"]/SqlClientMetaDataCollectionNames/*'/>
public static class SqlClientMetaDataCollectionNames
{
Expand Down Expand Up @@ -1010,6 +1040,9 @@ public SqlConnection() { }
public SqlConnection(string connectionString) { }
/// <include file='../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ctorConnectionStringCredential/*'/>
public SqlConnection(string connectionString, Microsoft.Data.SqlClient.SqlCredential credential) { }
/// <include file='../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/RegisterSqlClientAgent/*' />
[System.CLSCompliantAttribute(false)]
public static void RegisterSqlClientAgent(Microsoft.Data.SqlClient.SqlClientAgent id) { }

/// <include file='../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/AccessToken/*'/>
[System.ComponentModel.BrowsableAttribute(false)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Configuration;
using System.Threading;
using Microsoft.Data.Common;
using Microsoft.Data.SqlClient.Internal;

#nullable enable

namespace Microsoft.Data.SqlClient;

/// <summary>
/// Identifies known middleware agents that use Microsoft.Data.SqlClient.
/// </summary>
[CLSCompliant(false)]
public enum SqlClientAgent : ushort
{
/// <summary>The Microsoft Entity Framework Core SQL Server provider.</summary>
EntityFramework = 1,

/// <summary>Microsoft Semantic Kernel.</summary>
SemanticKernel = 2,

/// <summary>Microsoft SQL Server Management Studio.</summary>
ManagementStudio = 3,

/// <summary>Microsoft SQL Server Management Objects.</summary>
SqlManagementObjects = 4,

/// <summary>Microsoft SQL Server Data-Tier Application Framework.</summary>
Comment thread
cheenamalhotra marked this conversation as resolved.
Outdated
DataTierApplicationFramework = 5,

/// <summary>Microsoft SQL Tools Service.</summary>
SqlToolsService = 6,

/// <summary>Microsoft ASP.NET Core distributed SQL Server cache.</summary>
AspNetCoreDistributedSqlServerCache = 7,

/// <summary>Microsoft Entity Framework 6 SQL Server provider.</summary>
EntityFramework6 = 8,

/// <summary>Microsoft Azure Functions SQL extension.</summary>
AzureFunctionsSqlExtension = 9,

/// <summary>Microsoft Orleans ADO.NET providers.</summary>
Comment thread
cheenamalhotra marked this conversation as resolved.
Outdated
OrleansAdoNet = 10,

/// <summary>Microsoft Durable Task SQL Server provider.</summary>
DurableTaskSqlServer = 11
Comment thread
cheenamalhotra marked this conversation as resolved.
Outdated
}

/// <summary>
/// <para>
/// Holds the process-wide agent registration reported in the USERAGENT
/// login feature extension.
/// </para>
/// <para>
/// An agent may be registered at most once per process, either from the
/// application configuration file or programmatically via
/// <see cref="SqlConnection.RegisterSqlClientAgent"/>. The configuration
/// file wins, because it is read during static construction, before any
/// application code can call
/// <see cref="SqlConnection.RegisterSqlClientAgent"/>.
/// </para>
/// </summary>
internal static class SqlClientAgentRegistration
{
// The registered agent identifier, or 0 when no agent is registered.
//
// Written at most once, either by static construction from the application
// configuration file, or by the first Register() call.
private static int s_agentId = LoadFromAppConfig();

/// <summary>
/// The registered agent, or null when no agent has been registered.
/// </summary>
internal static SqlClientAgent? Agent
{
get
{
int id = Volatile.Read(ref s_agentId);
return id == 0 ? null : (SqlClientAgent)id;
}
}

/// <summary>
/// Register the given agent for the lifetime of the process.
/// </summary>
/// <param name="id">The agent to register.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="id"/> is not a valid agent identifier.
/// </exception>
/// <exception cref="InvalidOperationException">
/// An agent has already been registered.
/// </exception>
internal static void Register(SqlClientAgent id)
{
Validate(id);
if (Interlocked.CompareExchange(ref s_agentId, (ushort)id, 0) != 0)
{
throw SQL.SqlClientAgentAlreadyRegistered();
Comment thread
mdaigle marked this conversation as resolved.
Outdated
}
}

/// <summary>
/// <para>
/// Convert a configured agent identifier to a
/// <see cref="SqlClientAgent"/>.
/// </para>
/// <para>
/// Both the name of a known agent (case-insensitive) and its numeric
/// identifier are accepted. A numeric identifier that is not yet
/// defined in <see cref="SqlClientAgent"/> is accepted, so an agent
/// assigned an identifier after this driver shipped can still be
/// configured.
/// </para>
/// </summary>
/// <param name="value">The agent identifier to convert.</param>
/// <returns>The agent the identifier names.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is not a valid agent identifier.
/// </exception>
internal static SqlClientAgent Parse(string value)
{
// Enum.TryParse accepts comma-separated lists and combines them, so
// "EntityFramework,SemanticKernel" would silently yield an unrelated
// agent. Only a single name or number is valid here.
if (value is null
|| value.IndexOf(',') >= 0
|| !Enum.TryParse(value, ignoreCase: true, out SqlClientAgent id)
|| (ushort)id == 0)
{
throw SQL.InvalidSqlClientAgent(value ?? string.Empty, nameof(value));
}

return id;
}

/// <summary>
/// Throw if the given agent is not a valid agent identifier.
/// </summary>
/// <param name="id">The agent to validate.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="id"/> is not a valid agent identifier.
/// </exception>
private static void Validate(SqlClientAgent id)
{
if ((ushort)id == 0)
{
throw SQL.InvalidSqlClientAgent(id.ToString(), nameof(id));
}
Comment thread
cheenamalhotra marked this conversation as resolved.
Outdated
}

/// <summary>
/// <para>
/// Read the agent registered in the application configuration file.
/// </para>
/// <para>All known exceptions are consumed.</para>
/// </summary>
/// <returns>
/// The configured agent identifier, or 0 when no valid agent is
/// configured.
/// </returns>
private static int LoadFromAppConfig()
{
// This runs during static initialization on the login path, so any
// escaping exception would surface as a TypeInitializationException on
// every connection attempt. Telemetry must never break connections.
try
{
object section = ConfigurationManager.GetSection(SqlClientAgentConfigurationSection.Name);
if (section is null)
{
return 0;
}

if (section is SqlClientAgentConfigurationSection configurationSection)
{
return (ushort)Parse(configurationSection.Id);
}

SqlClientEventSource.Log.TryTraceEvent(
"SqlClientAgentRegistration: The SqlClientAgent configuration section has an unexpected type; the agent was not registered.");
}
catch (Exception e) when (ADP.IsCatchableExceptionType(e))
{
SqlClientEventSource.Log.TryTraceEvent(
"SqlClientAgentRegistration: Unable to load the SqlClientAgent configuration; the agent was not registered: {0}",
e);
}

return 0;
}
}

/// <summary>
/// <para>
/// The <c>SqlClientAgent</c> application configuration file section, used
/// to register an agent without changing application code.
/// </para>
/// <para>
/// <code>
/// &lt;configSections&gt;
/// &lt;section name="SqlClientAgent"
/// type="Microsoft.Data.SqlClient.SqlClientAgentConfigurationSection, Microsoft.Data.SqlClient" /&gt;
/// &lt;/configSections&gt;
/// &lt;SqlClientAgent id="EntityFramework" /&gt;
/// </code>
/// </para>
/// </summary>
internal sealed class SqlClientAgentConfigurationSection : ConfigurationSection
{
/// <summary>
/// The name of this configuration section.
/// </summary>
internal const string Name = "SqlClientAgent";

/// <summary>
/// The name or numeric identifier of the agent to register.
/// </summary>
[ConfigurationProperty("id", IsRequired = true)]
public string Id
{
get => this["id"] as string ?? string.Empty;
set => this["id"] = value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,11 @@ public static void RegisterColumnEncryptionKeyStoreProviders(IDictionary<string,
}
}

/// <include file='../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/RegisterSqlClientAgent/*' />
[CLSCompliant(false)]
public static void RegisterSqlClientAgent(SqlClientAgent id)
=> SqlClientAgentRegistration.Register(id);

/// <include file='../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/RegisterColumnEncryptionKeyStoreProvidersOnConnection/*' />
public void RegisterColumnEncryptionKeyStoreProvidersOnConnection(IDictionary<string, SqlColumnEncryptionKeyStoreProvider> customProviders)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1856,6 +1856,16 @@ internal static Exception EmptyProviderName()

#endregion Always Encrypted Errors

internal static Exception SqlClientAgentAlreadyRegistered()
{
return ADP.InvalidOperation(StringsHelper.GetString(Strings.SQL_SqlClientAgentAlreadyRegistered));
}

internal static Exception InvalidSqlClientAgent(string value, string parameterName)
{
return ADP.ArgumentOutOfRange(StringsHelper.GetString(Strings.SQL_InvalidSqlClientAgent, value), parameterName);
}

//
// Merged Provider
//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1361,7 +1361,7 @@ internal void TdsLogin(
requestedFeatures,
recoverySessionData,
fedAuthFeatureExtensionData,
UserAgent.Ucs2Bytes,
UserAgent.GetUcs2Bytes(SqlClientAgentRegistration.Agent),
Comment thread
cheenamalhotra marked this conversation as resolved.
Outdated
useFeatureExt,
length
);
Expand Down Expand Up @@ -9521,7 +9521,7 @@ private void WriteLoginData(SqlLogin rec,
requestedFeatures,
recoverySessionData,
fedAuthFeatureExtensionData,
UserAgent.Ucs2Bytes,
UserAgent.GetUcs2Bytes(SqlClientAgentRegistration.Agent),
useFeatureExt,
length,
true
Expand Down
Loading
Loading