Files
Umbraco-CMS/src/Umbraco.Core/Configuration/Models/ConnectionStrings.cs

94 lines
3.2 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2020-03-23 14:31:21 +01:00
using System.Data.Common;
namespace Umbraco.Core.Configuration.Models
{
public class ConnectionStrings
{
// Backing field for UmbracoConnectionString to load from configuration value with key umbracoDbDSN.
// Attributes cannot be applied to map from keys that don't match, and have chosen to retain the key name
// used in configuration for older Umbraco versions.
// See: https://stackoverflow.com/a/54607296/489433
private string umbracoDbDSN
{
get => string.Empty;
set
{
UmbracoConnectionString = value;
ConnectionStringDictionary[Constants.System.UmbracoConnectionName] = value;
}
}
public string UmbracoConnectionString
{
get
{
ConnectionStringDictionary.TryGetValue(Constants.System.UmbracoConnectionName, out var value);
return value;
}
set => ConnectionStringDictionary[Constants.System.UmbracoConnectionName] = value;
}
private Dictionary<string, string> ConnectionStringDictionary { get; } = new Dictionary<string, string>();
public ConfigConnectionString this[string key]
{
2020-03-23 14:31:21 +01:00
get
{
if (!ConnectionStringDictionary.TryGetValue(key, out var connectionString))
{
return null;
}
2020-03-23 14:31:21 +01:00
var provider = ParseProvider(connectionString);
return new ConfigConnectionString(connectionString, provider, key);
}
set => throw new NotImplementedException();
}
2020-03-23 14:31:21 +01:00
private string ParseProvider(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
{
return null;
}
var builder = new DbConnectionStringBuilder();
builder.ConnectionString = connectionString;
if (builder.TryGetValue("Data Source", out var ds) && ds is string dataSource)
{
if (dataSource.EndsWith(".sdf"))
{
return Constants.DbProviderNames.SqlCe;
}
}
if (builder.TryGetValue("Server", out var s) && s is string server && !string.IsNullOrEmpty(server))
2020-03-23 14:31:21 +01:00
{
if (builder.TryGetValue("Database", out var db) && db is string database && !string.IsNullOrEmpty(database))
{
return Constants.DbProviderNames.SqlServer;
}
if (builder.TryGetValue("AttachDbFileName", out var a) && a is string attachDbFileName && !string.IsNullOrEmpty(attachDbFileName))
2020-03-23 14:31:21 +01:00
{
return Constants.DbProviderNames.SqlServer;
}
if (builder.TryGetValue("Initial Catalog", out var i) && i is string initialCatalog && !string.IsNullOrEmpty(initialCatalog))
{
return Constants.DbProviderNames.SqlServer;
}
2020-03-23 14:31:21 +01:00
}
throw new ArgumentException("Cannot determine provider name from connection string", nameof(connectionString));
}
}
}