Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
74 changes: 74 additions & 0 deletions src/EFCore.SqlServer/Storage/Internal/SqlServerConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Concurrent;
using System.Runtime.InteropServices;
Comment thread
roji marked this conversation as resolved.
Resolved
Comment thread
roji marked this conversation as resolved.
Resolved
using Microsoft.Data.SqlClient;

namespace Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal;
Expand All @@ -19,6 +20,15 @@ public class SqlServerConnection : RelationalConnection, ISqlServerConnection

private static readonly ConcurrentDictionary<string, bool> MultipleActiveResultSetsEnabledMap = new();

/// <summary>
/// Maps a user-provided connection string to a possibly transformed connection string that will actually be used
/// to connect. By default, if the user-provided connection string doesn't set Application Name, we set it to contain
/// information about EF Core and the version being used.
/// </summary>
private static readonly ConcurrentDictionary<string, string> ConnectionStringMap = new();

private static string? _defaultApplicationName;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand All @@ -28,6 +38,29 @@ public class SqlServerConnection : RelationalConnection, ISqlServerConnection
public SqlServerConnection(RelationalConnectionDependencies dependencies)
: base(dependencies)
{
// If EF was configured with a connection string that doesn't contain Application Name, rewrite it to inject
// Application Name with EF and versioning info.
// Note that we don't do anything if EF was configured with a SqlConnection, as that could reset the
// password because of Persist Security Info=true
var relationalOptions = RelationalOptionsExtension.Extract(dependencies.ContextOptions);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I don't love that we need to extract the options here again (or the smelly assignment from ConnectionString to ConnectionString), but RelationalConnection works hard to prevent implementations from ever knowing if it was configured with a connection string or connection and generally to implement this kind of feature.

I'd propose some refactorings here, but this is temporary throwaway code, since SqlClient will be including a first-class user-agent-like feature anyway - so as a stop-gap this seems ok...


if (!string.IsNullOrWhiteSpace(relationalOptions.ConnectionString))
{
Check.DebugAssert(relationalOptions.Connection is null);

// In the base constructor, the connection string is set by assigning directly to _connectionString
// (possibly first going through ConnectionStringResolver).
// Here we re-assign the same via the ConnectionString property, which does the rewriting.
var userProvidedConnectionString = ConnectionString;
ConnectionString = userProvidedConnectionString;
}
}

/// <inheritdoc />
public override string? ConnectionString
{
get => base.ConnectionString;
set => base.ConnectionString = value is null ? null : ConnectionStringMap.GetOrAdd(value, ModifyConnectionString);
}

/// <summary>
Expand Down Expand Up @@ -120,4 +153,45 @@ public virtual bool IsMultipleActiveResultSetsEnabled
/// </summary>
protected override bool SupportsAmbientTransactions
=> true;

/// <summary>
/// Modifies the user-provided connection string. By default, adds an Application Name to the connection
/// string containing EF Core and versioning information.
/// </summary>
/// <remarks>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </remarks>
[EntityFrameworkInternal]
protected virtual string ModifyConnectionString(string userProvidedConnectionString)
{
try
{
var connectionStringBuilder = new SqlConnectionStringBuilder(userProvidedConnectionString);

// SqlClient sends "Core Microsoft SqlClient Data Provider" as the default Application Name when unset;
// detect that and overwrite.
if (connectionStringBuilder.ApplicationName is "Core Microsoft SqlClient Data Provider" or "" or null)
{
var efVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
Comment thread
AndriySvyryd marked this conversation as resolved.
Resolved

Comment thread
roji marked this conversation as resolved.
Resolved
_defaultApplicationName ??=
$"EFCore/{efVersion} ({RuntimeInformation.OSDescription} {RuntimeInformation.OSArchitecture})";

connectionStringBuilder.ApplicationName = _defaultApplicationName;

return connectionStringBuilder.ToString();
}
}
catch
{
// If anything goes wrong, simply don't modify the connection string.
// There are some scenarios where an invalid string is provided and an exception isn't expected at this phase
// (see e.g. test GetContextInfo_does_not_throw_if_DbConnection_cannot_be_created)
}

return userProvidedConnectionString;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ public class TwoDatabasesSqlServerTest(SqlServerFixture fixture) : TwoDatabasesT
protected new SqlServerFixture Fixture
=> (SqlServerFixture)base.Fixture;

[ConditionalTheory(Skip = "In SQL Server specifically, injection of Application Name into the connection string causes this test to fail (#36548)")]
public override void Can_set_connection_string_in_interceptor(bool withConnectionString, bool withNullConnectionString)
=> base.Can_set_connection_string_in_interceptor(withConnectionString, withNullConnectionString);

protected override DbContextOptionsBuilder CreateTestOptions(
DbContextOptionsBuilder optionsBuilder,
bool withConnectionString = false,
Expand All @@ -24,5 +28,5 @@ protected override TwoDatabasesWithDataContext CreateBackingContext(string datab
=> new(Fixture.CreateOptions(SqlServerTestStore.Create(databaseName)));

protected override string DummyConnectionString
=> "Database=DoesNotExist";
=> "Database=DoesNotExist;Application Name=foo";
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@ public void Creates_SQL_Server_connection_string()
Assert.IsType<SqlConnection>(connection.DbConnection);
}

#region Master connection

[ConditionalFact]
public void Can_create_master_connection()
{
using var connection = new SqlServerConnection(CreateDependencies());
using var master = connection.CreateMasterConnection();
Assert.Equal(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master", master.ConnectionString);
Assert.Equal(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master", StripApplicationName(master.ConnectionString));
Assert.Equal(60, master.CommandTimeout);
}

Expand All @@ -39,7 +41,7 @@ public void Master_connection_string_contains_filename()

using var connection = new SqlServerConnection(CreateDependencies(options));
using var master = connection.CreateMasterConnection();
Assert.Equal(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master", master.ConnectionString);
Assert.Equal(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master", StripApplicationName(master.ConnectionString));
}

[ConditionalFact]
Expand All @@ -56,6 +58,61 @@ public void Master_connection_string_none_default_command_timeout()
Assert.Equal(55, master.CommandTimeout);
}

#endregion Master connection

#region Application Name

[ConditionalFact]
public void ApplicationName_is_injected_when_not_defined_with_connection_string()
{
var options = new DbContextOptionsBuilder()
.UseSqlServer("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlServerConnectionTest""")
.Options;

using var connection = new SqlServerConnection(CreateDependencies(options));
Assert.StartsWith("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlServerConnectionTest;Application Name="EFCore/""", connection.ConnectionString);

connection.ConnectionString = """Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SomeOtherDatabase""";
Assert.StartsWith("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SomeOtherDatabase;Application Name="EFCore/""", connection.ConnectionString);
}

[ConditionalFact]
public void ApplicationName_is_not_injected_when_user_defined_with_connection_string()
{
var options = new DbContextOptionsBuilder()
.UseSqlServer("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlServerConnectionTest;Application Name=foo""")
.Options;

using var connection = new SqlServerConnection(CreateDependencies(options));
Assert.Equal("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlServerConnectionTest;Application Name=foo""", connection.ConnectionString);

connection.ConnectionString = """Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SomeOtherDatabase;Application Name=foo""";
Assert.Equal("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SomeOtherDatabase;Application Name=foo""", connection.ConnectionString);
}

[ConditionalFact]
public void ApplicationName_is_not_injected_with_connection()
{
var dbConnection1 = new SqlConnection("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlServerConnectionTest""");
var options = new DbContextOptionsBuilder().UseSqlServer(dbConnection1).Options;

using var connection = new SqlServerConnection(CreateDependencies(options));
Assert.Equal("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SqlServerConnectionTest""", connection.ConnectionString);

var dbConnection2 = new SqlConnection("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SomeOtherDatabase""");
connection.DbConnection = dbConnection2;
Assert.Equal("""Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SomeOtherDatabase""", connection.ConnectionString);
}

#endregion Application Name

private static string StripApplicationName(string connectionString)
{
var builder = new SqlConnectionStringBuilder(connectionString);
builder.Remove("Application Name");
return builder.ToString();
}

public static RelationalConnectionDependencies CreateDependencies(DbContextOptions options = null)
{
options ??= new DbContextOptionsBuilder()
Expand Down