baseline: 小军 WMS 二开代码原始快照(含 SynOABusiness.cs Debugger.Break)
This commit is contained in:
commit
c2b0e7be0d
6522 files changed
+3530643
No files matched your search
Executable
+268
@@ -0,0 +1,268 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
|
||||
internal class BlockingDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
|
||||
{
|
||||
private readonly IDictionary<TKey, TValue> _dic;
|
||||
|
||||
private readonly ReaderWriterLockSlim _locker;
|
||||
|
||||
public ICollection<TKey> Keys
|
||||
{
|
||||
get
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
List<TKey> result = _dic.Keys.ToList();
|
||||
_locker.ExitReadLock();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public ICollection<TValue> Values
|
||||
{
|
||||
get
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
List<TValue> result = _dic.Values.ToList();
|
||||
_locker.ExitReadLock();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public TValue this[TKey key]
|
||||
{
|
||||
get
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
try
|
||||
{
|
||||
return _dic[key];
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitReadLock();
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_dic[key] = value;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
int count = _dic.Count;
|
||||
_locker.ExitReadLock();
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
|
||||
|
||||
public void Add(TKey key, TValue value)
|
||||
{
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_dic.Add(key, value);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
public bool ContainsKey(TKey key)
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
try
|
||||
{
|
||||
return _dic.ContainsKey(key);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
public bool Remove(TKey key)
|
||||
{
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
return _dic.Remove(key);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryGetValue(TKey key, out TValue value)
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
try
|
||||
{
|
||||
return _dic.TryGetValue(key, out value);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
public TValue GetOrAdd(TKey key, TValue value)
|
||||
{
|
||||
if (TryGetValue(key, out var value2))
|
||||
{
|
||||
return value2;
|
||||
}
|
||||
return GetOrAddInternal(key, (TKey _) => value);
|
||||
}
|
||||
|
||||
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
|
||||
{
|
||||
if (TryGetValue(key, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
return GetOrAddInternal(key, valueFactory);
|
||||
}
|
||||
|
||||
public TValue GetOrAddInternal(TKey key, Func<TKey, TValue> valueFactory)
|
||||
{
|
||||
_locker.EnterUpgradeableReadLock();
|
||||
try
|
||||
{
|
||||
if (_dic.TryGetValue(key, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
TValue val = valueFactory(key);
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_dic.Add(key, val);
|
||||
return val;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitUpgradeableReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
foreach (KeyValuePair<TKey, TValue> item in _dic)
|
||||
{
|
||||
yield return item;
|
||||
}
|
||||
_locker.ExitReadLock();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_dic.Clear();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
|
||||
{
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_dic.Add(item);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
|
||||
{
|
||||
_locker.EnterReadLock();
|
||||
try
|
||||
{
|
||||
return _dic.Contains(item);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
|
||||
{
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_dic.CopyTo(array, arrayIndex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return GetEnumerator();
|
||||
}
|
||||
|
||||
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
|
||||
{
|
||||
_locker.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
return _dic.Remove(item);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_locker.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
public BlockingDictionary()
|
||||
{
|
||||
_dic = new Dictionary<TKey, TValue>();
|
||||
_locker = new ReaderWriterLockSlim();
|
||||
}
|
||||
|
||||
public BlockingDictionary(int capacity)
|
||||
{
|
||||
_dic = new Dictionary<TKey, TValue>(capacity);
|
||||
_locker = new ReaderWriterLockSlim();
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+112
@@ -0,0 +1,112 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public static class ConfigConvert
|
||||
{
|
||||
public static DataAccessOptions XmlToConfig(string xml, DataAccessOptions oldDataAccessConfig)
|
||||
{
|
||||
DataAccessOptions dataAccessOptions = new DataAccessOptions();
|
||||
XElement xElement = XDocument.Parse(xml).Element("opbase.dataAccess");
|
||||
if (xElement == null)
|
||||
{
|
||||
return dataAccessOptions;
|
||||
}
|
||||
dataAccessOptions.AppUK = (string)xElement.Attribute("name");
|
||||
foreach (XElement item in xElement.Elements("database"))
|
||||
{
|
||||
DatabaseOptions databaseOptions = new DatabaseOptions();
|
||||
databaseOptions.Name = (string)item.Attribute("name");
|
||||
if (string.IsNullOrWhiteSpace(databaseOptions.Name))
|
||||
{
|
||||
string message = "OPBase.Data配置项中,database节点name属性未设置,请联系DBA";
|
||||
//Log.Error(message);
|
||||
throw new ArgumentNullException("database.name", message);
|
||||
}
|
||||
databaseOptions.IsDefault = string.Equals(bool.TrueString, (string)item.Attribute("default"), StringComparison.OrdinalIgnoreCase);
|
||||
XElement xElement2 = item.Element("read");
|
||||
if (xElement2 != null)
|
||||
{
|
||||
IList<ConnectionOptions> connections = GetConnections(xElement2);
|
||||
if (!ValidateConnectionString(databaseOptions.Name, connections))
|
||||
{
|
||||
if (oldDataAccessConfig.Databases.TryGetValue(databaseOptions.Name, out var value))
|
||||
{
|
||||
dataAccessOptions.Databases.Add(databaseOptions.Name, value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
databaseOptions.ReadConnections.AddRange(connections);
|
||||
}
|
||||
XElement xElement3 = item.Element("write");
|
||||
if (xElement3 != null)
|
||||
{
|
||||
IList<ConnectionOptions> connections2 = GetConnections(xElement3);
|
||||
if (!ValidateConnectionString(databaseOptions.Name, connections2))
|
||||
{
|
||||
if (oldDataAccessConfig.Databases.TryGetValue(databaseOptions.Name, out var value2))
|
||||
{
|
||||
dataAccessOptions.Databases.Add(databaseOptions.Name, value2);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
databaseOptions.WriteConnections.AddRange(connections2);
|
||||
}
|
||||
if (databaseOptions.ReadConnections.Count + databaseOptions.WriteConnections.Count > 0)
|
||||
{
|
||||
dataAccessOptions.Databases.Add(databaseOptions.Name, databaseOptions);
|
||||
}
|
||||
}
|
||||
return dataAccessOptions;
|
||||
}
|
||||
|
||||
private static bool ValidateConnectionString(string dbName, IList<ConnectionOptions> connectionConfigs)
|
||||
{
|
||||
return connectionConfigs.Count(delegate (ConnectionOptions config)
|
||||
{
|
||||
IConnectionFactory byProvider;
|
||||
try
|
||||
{
|
||||
byProvider = ConnectionFactory.Instance.GetByProvider(config.Provider);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Log.Warn(ex, ex.Message);
|
||||
Console.WriteLine(ex.Message);
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
byProvider.CreateConnectionStringBuilder(config.ConnectionString);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
Console.WriteLine(ex2.Message);
|
||||
//Log.Warn(ex2, ex2.Message);
|
||||
return true;
|
||||
}
|
||||
}) == 0;
|
||||
}
|
||||
|
||||
private static IList<ConnectionOptions> GetConnections(XElement serversElement)
|
||||
{
|
||||
List<ConnectionOptions> list = new List<ConnectionOptions>();
|
||||
foreach (XElement item in serversElement.Elements("server"))
|
||||
{
|
||||
ConnectionOptions connectionOptions = new ConnectionOptions();
|
||||
connectionOptions.Enabled = string.Equals(bool.TrueString, (string)item.Attribute("enabled"), StringComparison.OrdinalIgnoreCase);
|
||||
connectionOptions.PasswordEncrypted = string.Equals(bool.TrueString, (string)item.Attribute("encrypt"), StringComparison.OrdinalIgnoreCase);
|
||||
connectionOptions.LoadWeight = (int.TryParse((string)item.Attribute("weight"), out var result) ? result : 0);
|
||||
connectionOptions.ConnectionString = (string)item.Attribute("connectionString");
|
||||
connectionOptions.CommandTimeOut = (int.TryParse((string)item.Attribute("commandTimeOut"), out var result2) ? result2 : 0);
|
||||
connectionOptions.Provider = (string)item.Attribute("provider");
|
||||
list.Add(connectionOptions);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class ConfigurationEndpointProvider : DictionaryEndpointProvider
|
||||
{
|
||||
private static string dataString;
|
||||
|
||||
private static DataAccessOptions oldAccessOptions;
|
||||
|
||||
private static IDictionary<string, DbEndpoint> _endpoints = new Dictionary<string, DbEndpoint>();
|
||||
|
||||
private static IDictionary<string, DbEndpoint> _endpointsSet = new Dictionary<string, DbEndpoint>();
|
||||
|
||||
private static IDictionary<string, DbEndpoint> _endpointsUnSet = new Dictionary<string, DbEndpoint>();
|
||||
|
||||
public ConfigurationEndpointProvider(IConfiguration configuration)
|
||||
: base(Convert(configuration))
|
||||
{
|
||||
ConfigurationEndpointProvider configurationEndpointProvider = this;
|
||||
ChangeToken.OnChange(() => configuration.GetReloadToken(), delegate
|
||||
{
|
||||
configurationEndpointProvider.ReloadOptions(configuration);
|
||||
configurationEndpointProvider.TriggerEvent(new EndpointChangedEventArgs
|
||||
{
|
||||
ChangedEndpoints = _endpointsSet,
|
||||
DeleteEndpoints = _endpointsUnSet
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private bool ReloadOptions(IConfiguration configuration)
|
||||
{
|
||||
string text = configuration["OPBase.Data"];
|
||||
if (string.Equals(text, dataString))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
//Log.Info("重新加载当前项目" + configuration["APP_UK"] + "OPBase.Cache项:" + text);
|
||||
dataString = text;
|
||||
try
|
||||
{
|
||||
_endpointsSet.Clear();
|
||||
_endpointsUnSet.Clear();
|
||||
DataAccessOptions oldDataAccessConfig = new DataAccessOptions();
|
||||
DataAccessOptions dataAccessOptions = ConfigConvert.XmlToConfig(text, oldDataAccessConfig);
|
||||
if (string.IsNullOrWhiteSpace(text) || dataAccessOptions == null || !dataAccessOptions.Databases.Any())
|
||||
{
|
||||
_endpointsUnSet = _endpoints;
|
||||
_endpoints.Clear();
|
||||
return true;
|
||||
}
|
||||
Dictionary<string, DbEndpoint> dictionary = new Dictionary<string, DbEndpoint>();
|
||||
foreach (KeyValuePair<string, DatabaseOptions> database in dataAccessOptions.Databases)
|
||||
{
|
||||
DbEndpoint dbEndpoint = new DbEndpoint();
|
||||
dbEndpoint.DatabaseOptions = database.Value;
|
||||
dictionary.Add(database.Key, dbEndpoint);
|
||||
}
|
||||
_endpointsSet = dictionary;
|
||||
_endpoints = dictionary;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Log.Error(ex, "OPBase.Data配置项解析失败,请联系DBA");
|
||||
throw new InvalidOperationException("OPBase.Data配置项解析失败,请联系DBA", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static IDictionary<string, DbEndpoint> Convert(IConfiguration configuration)
|
||||
{
|
||||
string text = (dataString = configuration["OPBase.Data"]);
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
//Log.Error("当前项目" + configuration["APP_UK"] + "OPBase.Data项,请联系DBA配置数据库连接");
|
||||
throw new InvalidOperationException("当前项目" + configuration["APP_UK"] + "OPBase.Data项,请联系DBA配置数据库连接");
|
||||
}
|
||||
//Log.Info("获取到当前项目" + configuration["APP_UK"] + "统一配置OPBase.Data项配置:" + text);
|
||||
try
|
||||
{
|
||||
DataAccessOptions oldDataAccessConfig = oldAccessOptions ?? new DataAccessOptions();
|
||||
foreach (KeyValuePair<string, DatabaseOptions> database in (oldAccessOptions = ConfigConvert.XmlToConfig(text, oldDataAccessConfig)).Databases)
|
||||
{
|
||||
DbEndpoint dbEndpoint = new DbEndpoint();
|
||||
dbEndpoint.DatabaseOptions = database.Value;
|
||||
_endpoints.Add(database.Key, dbEndpoint);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Log.Error(ex, "OPBase.Data配置项解析失败,请联系DBA");
|
||||
throw new InvalidOperationException("OPBase.Data配置项解析失败,请联系DBA", ex);
|
||||
}
|
||||
return _endpoints;
|
||||
}
|
||||
|
||||
private static ConnectionOptions GetReadConnectionConfig(DatabaseOptions databaseConfig)
|
||||
{
|
||||
if (databaseConfig.ReadConnections.Count < 2)
|
||||
{
|
||||
return databaseConfig.ReadConnections.FirstOrDefault();
|
||||
}
|
||||
int num = Interlocked.Increment(ref databaseConfig.ReadSeed);
|
||||
int num2 = RoundRobin(databaseConfig.ReadConnections, num);
|
||||
if (num2 < num)
|
||||
{
|
||||
Interlocked.CompareExchange(ref databaseConfig.ReadSeed, num2, num);
|
||||
}
|
||||
return databaseConfig.ReadConnections[num2];
|
||||
}
|
||||
|
||||
private static ConnectionOptions GetWriteConnectionConfig(DatabaseOptions databaseConfig)
|
||||
{
|
||||
if (databaseConfig.WriteConnections.Count < 2)
|
||||
{
|
||||
return databaseConfig.WriteConnections.FirstOrDefault();
|
||||
}
|
||||
int num = Interlocked.Increment(ref databaseConfig.WriteSeed);
|
||||
int num2 = RoundRobin(databaseConfig.WriteConnections, num);
|
||||
if (num2 < num)
|
||||
{
|
||||
Interlocked.CompareExchange(ref databaseConfig.WriteSeed, num2, num);
|
||||
}
|
||||
return databaseConfig.WriteConnections[num2];
|
||||
}
|
||||
|
||||
private static int RoundRobin(List<ConnectionOptions> connectionConfigs, int seed)
|
||||
{
|
||||
return seed % connectionConfigs.Count;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class ConnectionFactory
|
||||
{
|
||||
private static ConnectionFactory _instance;
|
||||
|
||||
private static object _syncRoot = new object();
|
||||
|
||||
private IDictionary<string, string> _assmblyName;
|
||||
|
||||
public static ConnectionFactory Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
ConnectionFactory instance = _instance;
|
||||
if (instance == null)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
instance = Volatile.Read(ref _instance);
|
||||
if (instance == null)
|
||||
{
|
||||
instance = new ConnectionFactory();
|
||||
}
|
||||
Volatile.Write(ref _instance, instance);
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
private ConnectionFactory()
|
||||
{
|
||||
_assmblyName = new Dictionary<string, string>
|
||||
{
|
||||
{ "System.Data.SqlClient", "Opsoft.Data.SqlServer" },
|
||||
{ "MySql.Data.MySqlClient", "Opsoft.Data.MySql" },
|
||||
{ "Npgsql", "Opsoft.Data.PostgreSql" }
|
||||
};
|
||||
}
|
||||
|
||||
public IConnectionFactory GetByProvider(string providerName)
|
||||
{
|
||||
if (!_assmblyName.TryGetValue(providerName, out var value))
|
||||
{
|
||||
//Log.Error("数据库驱动名称" + providerName + "尚未被支持");
|
||||
throw new ArgumentException("数据库驱动名称" + providerName + "尚未被支持", nameof(providerName));
|
||||
}
|
||||
return ExtensionLoader.Instance.GetService<IConnectionFactory>(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class ConnectionOptions
|
||||
{
|
||||
public string ConnectionString { get; set; }
|
||||
|
||||
public string Provider { get; set; }
|
||||
|
||||
internal bool Enabled { get; set; }
|
||||
|
||||
public bool PasswordEncrypted { get; set; }
|
||||
|
||||
internal int LoadWeight { get; set; }
|
||||
|
||||
internal int CommandTimeOut { get; set; }
|
||||
}
|
||||
}
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class DataAccessOptions
|
||||
{
|
||||
public string AppUK { get; set; }
|
||||
|
||||
public IDictionary<string, DatabaseOptions> Databases { get; set; }
|
||||
|
||||
public DataAccessOptions()
|
||||
{
|
||||
Databases = new Dictionary<string, DatabaseOptions>();
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class DataSource
|
||||
{
|
||||
public const string SQLServerProviderName = "System.Data.SqlClient";
|
||||
|
||||
public const string MySQLProviderName = "MySql.Data.MySqlClient";
|
||||
|
||||
public const string PostgreSQLProviderName = "Npgsql";
|
||||
|
||||
public static IDictionary<string, DbEndpoint> Endpoints;
|
||||
}
|
||||
}
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class DataSourceBuilder
|
||||
{
|
||||
public IServiceCollection Services { get; }
|
||||
|
||||
public DataSourceBuilder(IServiceCollection services)
|
||||
{
|
||||
Services = services;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public static class DataSourceBuilderExtensions
|
||||
{
|
||||
public static DataSourceBuilder UseConfiguration(this DataSourceBuilder builder, IConfiguration configuration)
|
||||
{
|
||||
builder.Services.AddSingleton((IDbEndpointProvider)new ConfigurationEndpointProvider(configuration));
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class DatabaseOptions
|
||||
{
|
||||
public int ReadSeed;
|
||||
|
||||
public int WriteSeed;
|
||||
|
||||
internal string Name { get; set; }
|
||||
|
||||
internal bool IsDefault { get; set; }
|
||||
|
||||
public List<ConnectionOptions> ReadConnections { get; private set; }
|
||||
|
||||
public List<ConnectionOptions> WriteConnections { get; private set; }
|
||||
|
||||
public DatabaseOptions()
|
||||
{
|
||||
ReadConnections = new List<ConnectionOptions>();
|
||||
WriteConnections = new List<ConnectionOptions>();
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
using System.Data;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared
|
||||
{
|
||||
public class DbConnectionExtensions
|
||||
{
|
||||
public static string GetDatabaseType(IDbConnection connection)
|
||||
{
|
||||
return (connection as Data.OPDbConnection)?.GetDatabaseType();
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+264
@@ -0,0 +1,264 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class DbConnectionFactory : IDbConnectionFactory
|
||||
{
|
||||
private ConcurrentDictionary<string, DbEndpoint> _endpoints;
|
||||
|
||||
private IConfiguration _configuration;
|
||||
|
||||
private DiagnosticListener _listener = new DiagnosticListener("Opsoft.Data");
|
||||
|
||||
public DbConnectionFactory(IEnumerable<IDbEndpointProvider> providers, IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_endpoints = new ConcurrentDictionary<string, DbEndpoint>();
|
||||
foreach (IDbEndpointProvider provider in providers)
|
||||
{
|
||||
foreach (KeyValuePair<string, DbEndpoint> endpoint in provider.GetEndpoints())
|
||||
{
|
||||
if (_endpoints.ContainsKey(endpoint.Key))
|
||||
{
|
||||
//sky.Error("数据库" + endpoint.Key + "配置重复设置,请检查相关配置!");
|
||||
throw new InvalidOperationException("数据库" + endpoint.Key + "配置重复设置,请检查相关配置!");
|
||||
}
|
||||
_endpoints.TryAdd(endpoint.Key, endpoint.Value);
|
||||
}
|
||||
provider.EndpointChanged += Provider_EndpointChanged;
|
||||
}
|
||||
DataSource.Endpoints = _endpoints;
|
||||
}
|
||||
|
||||
private void Provider_EndpointChanged(object sender, EndpointChangedEventArgs e)
|
||||
{
|
||||
if (e == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
IDictionary<string, DbEndpoint> changedEndpoints = e.ChangedEndpoints;
|
||||
IDictionary<string, DbEndpoint> deleteEndpoints = e.DeleteEndpoints;
|
||||
if (deleteEndpoints != null && deleteEndpoints.Any())
|
||||
{
|
||||
foreach (KeyValuePair<string, DbEndpoint> item in deleteEndpoints)
|
||||
{
|
||||
_endpoints.TryRemove(item.Key, out var _);
|
||||
}
|
||||
}
|
||||
if (changedEndpoints == null || !changedEndpoints.Any())
|
||||
{
|
||||
return;
|
||||
}
|
||||
foreach (KeyValuePair<string, DbEndpoint> optionSet in changedEndpoints)
|
||||
{
|
||||
_endpoints.AddOrUpdate(optionSet.Key, optionSet.Value, (string dbName, DbEndpoint dbEndpoint) => optionSet.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public DbConnection GetConnection(string dbName, bool readOnly = true, bool checkWhere = false)
|
||||
{
|
||||
if (!_endpoints.TryGetValue(dbName, out var value))
|
||||
{
|
||||
//Log.Error("无法找到数据库名为" + dbName + "的对应的ConnectionFactory,请检查配置是否正确");
|
||||
throw new InvalidOperationException("无法找到数据库名为" + dbName + "的对应的ConnectionFactory,请检查配置是否正确");
|
||||
}
|
||||
if (value.DatabaseOptions != null)
|
||||
{
|
||||
ConnectionOptions readConnectionConfig = GetReadConnectionConfig(value.DatabaseOptions);
|
||||
ConnectionOptions writeConnectionConfig = GetWriteConnectionConfig(value.DatabaseOptions);
|
||||
IConnectionFactory connectionFactory = null;
|
||||
string text = null;
|
||||
bool passwordEncrypted = false;
|
||||
string text2 = null;
|
||||
if (readOnly)
|
||||
{
|
||||
if (readConnectionConfig != null)
|
||||
{
|
||||
IConnectionFactory byProvider = ConnectionFactory.Instance.GetByProvider(readConnectionConfig.Provider);
|
||||
passwordEncrypted = readConnectionConfig.PasswordEncrypted;
|
||||
text = readConnectionConfig.ConnectionString;
|
||||
text2 = readConnectionConfig.Provider;
|
||||
connectionFactory = byProvider;
|
||||
}
|
||||
}
|
||||
else if (writeConnectionConfig != null)
|
||||
{
|
||||
IConnectionFactory byProvider2 = ConnectionFactory.Instance.GetByProvider(writeConnectionConfig.Provider);
|
||||
passwordEncrypted = writeConnectionConfig.PasswordEncrypted;
|
||||
text = writeConnectionConfig.ConnectionString;
|
||||
text2 = writeConnectionConfig.Provider;
|
||||
connectionFactory = byProvider2;
|
||||
}
|
||||
if (connectionFactory == null || string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(text2))
|
||||
{
|
||||
//Log.Error("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库"));
|
||||
throw new InvalidOperationException("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库"));
|
||||
}
|
||||
string appUK = _configuration["APP_UK"];
|
||||
return CreateConenction(connectionFactory, text, passwordEncrypted, appUK, text2, checkWhere, _listener);
|
||||
}
|
||||
IConnectionFactory connectionFactory2;
|
||||
string text3;
|
||||
bool passwordEncrypted2;
|
||||
string text4;
|
||||
if (readOnly)
|
||||
{
|
||||
connectionFactory2 = value.ReadConnectionFactory;
|
||||
text3 = value.ReadConnectionString;
|
||||
passwordEncrypted2 = value.ReadPasswordEncrypted;
|
||||
text4 = value.ReadProvider;
|
||||
}
|
||||
else
|
||||
{
|
||||
connectionFactory2 = value.WriteConnectionFactory;
|
||||
text3 = value.WriteConnectionString;
|
||||
passwordEncrypted2 = value.WritePasswordEncrypted;
|
||||
text4 = value.WriteProvider;
|
||||
}
|
||||
if (connectionFactory2 == null || string.IsNullOrWhiteSpace(text3) || string.IsNullOrWhiteSpace(text4))
|
||||
{
|
||||
//Log.Error("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库"));
|
||||
throw new InvalidOperationException("无法找到匹配的数据库连接,请求的数据库是" + dbName + ",请求的数据库类型为" + (readOnly ? "读库" : "写库"));
|
||||
}
|
||||
return CreateConenction(connectionFactory2, text3, passwordEncrypted2, value.AppUK, text4, checkWhere, _listener);
|
||||
}
|
||||
|
||||
private DbConnection CreateConenction(IConnectionFactory connectionFactory, string connectionString, bool passwordEncrypted, string appUK, string provider, bool checkWhere, DiagnosticSource listener)
|
||||
{
|
||||
DbConnectionStringBuilder dbConnectionStringBuilder = connectionFactory.CreateConnectionStringBuilder(connectionString);
|
||||
if (passwordEncrypted)
|
||||
{
|
||||
string toDecrypt = (string)dbConnectionStringBuilder["Password"];
|
||||
//try
|
||||
//{
|
||||
// toDecrypt = Security.Decrypt(toDecrypt, GetSecurity(appUK));
|
||||
//}
|
||||
//catch (Exception ex)
|
||||
//{
|
||||
// Log.Error(ex, "Decrypt password error");
|
||||
// throw new ArgumentException("Decrypt password error", ex);
|
||||
//}
|
||||
dbConnectionStringBuilder["Password"] = toDecrypt;
|
||||
}
|
||||
dbConnectionStringBuilder["PersistSecurityInfo"] = bool.FalseString;
|
||||
OPDbConnection tCDbConnection = new OPDbConnection(connectionFactory.CreateConnection(dbConnectionStringBuilder), checkWhere, provider, listener);
|
||||
dbConnectionStringBuilder["Password"] = "WARNING:You shouldn't use ConnectionString directly!";
|
||||
dbConnectionStringBuilder["PersistSecurityInfo"] = bool.TrueString;
|
||||
tCDbConnection.ConnectionString = dbConnectionStringBuilder.ConnectionString;
|
||||
return tCDbConnection;
|
||||
}
|
||||
|
||||
private string GetSecurity(string appUK)
|
||||
{
|
||||
if (appUK.Length < 16)
|
||||
{
|
||||
return appUK.PadRight(16, '0');
|
||||
}
|
||||
if (appUK.Length > 16)
|
||||
{
|
||||
return appUK.Substring(0, 16);
|
||||
}
|
||||
return appUK;
|
||||
}
|
||||
|
||||
public void Set(string dbName, string connectionString, DbProvider dbProvider)
|
||||
{
|
||||
string provider = GetProvider(dbProvider);
|
||||
IConnectionFactory byProvider = ConnectionFactory.Instance.GetByProvider(provider);
|
||||
IConnectionFactory byProvider2 = ConnectionFactory.Instance.GetByProvider(provider);
|
||||
DbEndpoint dbEndpoint = new DbEndpoint
|
||||
{
|
||||
ReadConnectionFactory = byProvider,
|
||||
ReadConnectionString = connectionString,
|
||||
ReadProvider = provider,
|
||||
WriteConnectionFactory = byProvider2,
|
||||
WriteConnectionString = connectionString,
|
||||
WriteProvider = provider
|
||||
};
|
||||
_endpoints.AddOrUpdate(dbName, dbEndpoint, (string databaseName, DbEndpoint databaseEndpoint) => dbEndpoint);
|
||||
}
|
||||
|
||||
public void Set(string dbName, string readConnectionString, DbProvider readDbProvider, string writeConnectionString, DbProvider writeDbProvider)
|
||||
{
|
||||
string provider = GetProvider(readDbProvider);
|
||||
string provider2 = GetProvider(writeDbProvider);
|
||||
IConnectionFactory byProvider = ConnectionFactory.Instance.GetByProvider(provider);
|
||||
IConnectionFactory byProvider2 = ConnectionFactory.Instance.GetByProvider(provider2);
|
||||
DbEndpoint dbEndpoint = new DbEndpoint
|
||||
{
|
||||
ReadConnectionFactory = byProvider,
|
||||
ReadConnectionString = readConnectionString,
|
||||
ReadProvider = provider,
|
||||
WriteConnectionFactory = byProvider2,
|
||||
WriteConnectionString = writeConnectionString,
|
||||
WriteProvider = provider2
|
||||
};
|
||||
_endpoints.AddOrUpdate(dbName, dbEndpoint, (string databaseName, DbEndpoint databaseEndpoint) => dbEndpoint);
|
||||
}
|
||||
|
||||
public void UnSet(string dbName)
|
||||
{
|
||||
_endpoints.TryRemove(dbName, out var _);
|
||||
}
|
||||
|
||||
private string GetProvider(DbProvider dbProvider)
|
||||
{
|
||||
string empty = string.Empty;
|
||||
switch (dbProvider)
|
||||
{
|
||||
case DbProvider.SQLServerProviderName:
|
||||
return "System.Data.SqlClient";
|
||||
case DbProvider.MySQLProviderName:
|
||||
return "MySql.Data.MySqlClient";
|
||||
case DbProvider.PostgreSQLProviderName:
|
||||
return "Npgsql";
|
||||
default:
|
||||
//Log.Error("provider不在服务提供范围内");
|
||||
throw new ArgumentException("provider不在服务提供范围内");
|
||||
}
|
||||
}
|
||||
|
||||
private static ConnectionOptions GetReadConnectionConfig(DatabaseOptions databaseConfig)
|
||||
{
|
||||
if (databaseConfig.ReadConnections.Count < 2)
|
||||
{
|
||||
return databaseConfig.ReadConnections.FirstOrDefault();
|
||||
}
|
||||
int num = Interlocked.Increment(ref databaseConfig.ReadSeed);
|
||||
int num2 = RoundRobin(databaseConfig.ReadConnections, num);
|
||||
if (num2 < num)
|
||||
{
|
||||
Interlocked.CompareExchange(ref databaseConfig.ReadSeed, num2, num);
|
||||
}
|
||||
return databaseConfig.ReadConnections[num2];
|
||||
}
|
||||
|
||||
private static ConnectionOptions GetWriteConnectionConfig(DatabaseOptions databaseConfig)
|
||||
{
|
||||
if (databaseConfig.WriteConnections.Count < 2)
|
||||
{
|
||||
return databaseConfig.WriteConnections.FirstOrDefault();
|
||||
}
|
||||
int num = Interlocked.Increment(ref databaseConfig.WriteSeed);
|
||||
int num2 = RoundRobin(databaseConfig.WriteConnections, num);
|
||||
if (num2 < num)
|
||||
{
|
||||
Interlocked.CompareExchange(ref databaseConfig.WriteSeed, num2, num);
|
||||
}
|
||||
return databaseConfig.WriteConnections[num2];
|
||||
}
|
||||
|
||||
private static int RoundRobin(List<ConnectionOptions> connectionConfigs, int seed)
|
||||
{
|
||||
return seed % connectionConfigs.Count;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class DbEndpoint
|
||||
{
|
||||
public string AppUK { get; set; }
|
||||
|
||||
public bool ReadPasswordEncrypted { get; set; }
|
||||
|
||||
public bool WritePasswordEncrypted { get; set; }
|
||||
|
||||
public string ReadConnectionString { get; set; }
|
||||
|
||||
public string WriteConnectionString { get; set; }
|
||||
|
||||
public string ReadProvider { get; set; }
|
||||
|
||||
public string WriteProvider { get; set; }
|
||||
|
||||
public IConnectionFactory ReadConnectionFactory { get; set; }
|
||||
|
||||
public IConnectionFactory WriteConnectionFactory { get; set; }
|
||||
|
||||
public DatabaseOptions DatabaseOptions { get; set; }
|
||||
}
|
||||
}
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public enum DbProvider
|
||||
{
|
||||
SQLServerProviderName,
|
||||
MySQLProviderName,
|
||||
PostgreSQLProviderName
|
||||
}
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
internal static class DiagnosticListenerExtensions
|
||||
{
|
||||
public static Guid BeforeOpenConnection(this DiagnosticSource listener, string dbProvider, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "BeforeOpenConnection";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
Guid guid = Guid.NewGuid();
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = guid,
|
||||
Operation = operation,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
return guid;
|
||||
}
|
||||
return Guid.Empty;
|
||||
}
|
||||
|
||||
public static void AfterOpenConnection(this DiagnosticSource listener, string dbProvider, Guid operationId, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "AfterOpenConnection";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static void OpenConnectionError(this DiagnosticSource listener, string dbProvider, Guid operationId, DbConnection tCDbConnection, Exception ex, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "OpenConnectionError";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
Connection = tCDbConnection,
|
||||
Exception = ex,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static Guid BeforeCloseConnection(this DiagnosticSource listener, string dbProvider, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "BeforeCloseConnection";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
Guid guid = Guid.NewGuid();
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = guid,
|
||||
Operation = operation,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
return guid;
|
||||
}
|
||||
return Guid.Empty;
|
||||
}
|
||||
|
||||
public static void AfterCloseConnection(this DiagnosticSource listener, string dbProvider, Guid operationId, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "AfterCloseConnection";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static void CloseConnectionError(this DiagnosticSource listener, string dbProvider, Guid operationId, DbConnection tCDbConnection, Exception ex, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "CloseConnectionError";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
Connection = tCDbConnection,
|
||||
Exception = ex,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static Guid BeforeExecuteDbCommand(this DiagnosticSource listener, string dbProvider, DbCommand tCDbCommand, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "BeforeExecuteDbCommand";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
Guid guid = Guid.NewGuid();
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = guid,
|
||||
Operation = operation,
|
||||
Provider = dbProvider,
|
||||
Command = tCDbCommand
|
||||
});
|
||||
return guid;
|
||||
}
|
||||
return Guid.Empty;
|
||||
}
|
||||
|
||||
public static void AfterExecuteDbCommand(this DiagnosticSource listener, string dbProvider, Guid operationId, DbCommand tCDbCommand, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "AfterExecuteDbCommand";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
Command = tCDbCommand,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static void ExecuteDbCommandError(this DiagnosticSource listener, string dbProvider, Guid operationId, DbCommand tCDbCommand, Exception ex, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "ExecuteDbCommandError";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
Command = tCDbCommand,
|
||||
Exception = ex,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static Guid BeforeCommitTransaction(this DiagnosticSource listener, string dbProvider, IsolationLevel isolationLevel, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "BeforeCommitTransaction";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
Guid guid = Guid.NewGuid();
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = guid,
|
||||
Operation = operation,
|
||||
IsolationLevel = isolationLevel,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
return guid;
|
||||
}
|
||||
return Guid.Empty;
|
||||
}
|
||||
|
||||
public static void AfterCommitTransaction(this DiagnosticSource listener, string dbProvider, Guid operationId, IsolationLevel isolationLevel, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "AfterCommitTransaction";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
IsolationLevel = isolationLevel,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static void CommitTransactionError(this DiagnosticSource listener, string dbProvider, Guid operationId, IsolationLevel isolationLevel, DbConnection tCDbConnection, Exception ex, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "CommitTransactionError";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
IsolationLevel = isolationLevel,
|
||||
Connection = tCDbConnection,
|
||||
Exception = ex,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static Guid BeforeRollbackTransaction(this DiagnosticSource listener, string dbProvider, IsolationLevel isolationLevel, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "BeforeRollbackTransaction";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
Guid guid = Guid.NewGuid();
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = guid,
|
||||
Operation = operation,
|
||||
IsolationLevel = isolationLevel,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
return guid;
|
||||
}
|
||||
return Guid.Empty;
|
||||
}
|
||||
|
||||
public static void AfterRollbackTransaction(this DiagnosticSource listener, string dbProvider, Guid operationId, IsolationLevel isolationLevel, DbConnection tCDbConnection, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "AfterRollbackTransaction";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
IsolationLevel = isolationLevel,
|
||||
Connection = tCDbConnection,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static void RollbackTransactionError(this DiagnosticSource listener, string dbProvider, Guid operationId, IsolationLevel isolationLevel, DbConnection tCDbConnection, Exception ex, [CallerMemberName] string operation = "")
|
||||
{
|
||||
string name = CreateSqlClientPrefix(dbProvider) + "RollbackTransactionError";
|
||||
if (listener.IsEnabled(name))
|
||||
{
|
||||
listener.Write(name, new
|
||||
{
|
||||
OperationId = operationId,
|
||||
Operation = operation,
|
||||
IsolationLevel = isolationLevel,
|
||||
Connection = tCDbConnection,
|
||||
Exception = ex,
|
||||
Provider = dbProvider,
|
||||
Timestamp = Stopwatch.GetTimestamp()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static string CreateSqlClientPrefix(string provider)
|
||||
{
|
||||
string result = string.Empty;
|
||||
switch (provider)
|
||||
{
|
||||
case "System.Data.SqlClient":
|
||||
result = "System.Data.SqlClient.";
|
||||
break;
|
||||
case "MySql.Data.MySqlClient":
|
||||
result = "MySql.Data.MySqlClient.";
|
||||
break;
|
||||
case "Npgsql":
|
||||
result = "Npgsql.";
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class DictionaryEndpointProvider : IDbEndpointProvider
|
||||
{
|
||||
private IDictionary<string, DbEndpoint> _endpoints;
|
||||
|
||||
public event EventHandler<EndpointChangedEventArgs> EndpointChanged;
|
||||
|
||||
public DictionaryEndpointProvider(IDictionary<string, DbEndpoint> endpoints)
|
||||
{
|
||||
_endpoints = endpoints;
|
||||
}
|
||||
|
||||
public IDictionary<string, DbEndpoint> GetEndpoints()
|
||||
{
|
||||
return _endpoints;
|
||||
}
|
||||
|
||||
public void TriggerEvent(EndpointChangedEventArgs args)
|
||||
{
|
||||
this.EndpointChanged?.Invoke(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public class EndpointChangedEventArgs : EventArgs
|
||||
{
|
||||
public IDictionary<string, DbEndpoint> ChangedEndpoints { get; set; }
|
||||
|
||||
public IDictionary<string, DbEndpoint> DeleteEndpoints { get; set; }
|
||||
}
|
||||
}
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
internal class ExtensionLoader
|
||||
{
|
||||
private static ExtensionLoader _instance;
|
||||
|
||||
private static object _syncRoot = new object();
|
||||
|
||||
private BlockingDictionary<string, Assembly> _assemblyCache;
|
||||
|
||||
private BlockingDictionary<Assembly, BlockingDictionary<Type, object>> _extensionCache;
|
||||
|
||||
public static ExtensionLoader Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
ExtensionLoader instance = _instance;
|
||||
if (instance == null)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
instance = Volatile.Read(ref _instance);
|
||||
if (instance == null)
|
||||
{
|
||||
instance = new ExtensionLoader();
|
||||
}
|
||||
Volatile.Write(ref _instance, instance);
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
||||
private ExtensionLoader()
|
||||
{
|
||||
_assemblyCache = new BlockingDictionary<string, Assembly>();
|
||||
_extensionCache = new BlockingDictionary<Assembly, BlockingDictionary<Type, object>>();
|
||||
}
|
||||
|
||||
internal T GetService<T>(string assemblyName)
|
||||
{
|
||||
Assembly extensionAssembly = _assemblyCache.GetOrAdd(assemblyName, delegate
|
||||
{
|
||||
AssemblyName assemblyRef = new AssemblyName(assemblyName);
|
||||
Assembly assembly = null;
|
||||
try
|
||||
{
|
||||
assembly = Assembly.Load(assemblyRef);
|
||||
}
|
||||
catch
|
||||
{
|
||||
//Log.Warn(ex, ex.Message);
|
||||
}
|
||||
if (assembly == null)
|
||||
{
|
||||
string message2 = assemblyName + ".dll未找到,请安装" + assemblyName + "组件NuGet包";
|
||||
//Log.Error(message2);
|
||||
throw new TypeLoadException(message2);
|
||||
}
|
||||
return assembly;
|
||||
});
|
||||
BlockingDictionary<Type, object> orAdd = _extensionCache.GetOrAdd(extensionAssembly, (Assembly _) => new BlockingDictionary<Type, object>());
|
||||
Type baseType = typeof(T);
|
||||
return (T)orAdd.GetOrAdd(baseType, delegate
|
||||
{
|
||||
foreach (Type exportedType in extensionAssembly.ExportedTypes)
|
||||
{
|
||||
if (baseType.IsAssignableFrom(exportedType))
|
||||
{
|
||||
return Expression.Lambda<Func<T>>(Expression.Property(null, exportedType, "Instance"), Array.Empty<ParameterExpression>()).Compile()();
|
||||
}
|
||||
}
|
||||
string message = "在" + assemblyName + "中未找到" + baseType.FullName + "的实现类";
|
||||
//Log.Error(message);
|
||||
throw new TypeLoadException(message);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
using System.Data.Common;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public interface IConnectionFactory
|
||||
{
|
||||
DbConnectionStringBuilder CreateConnectionStringBuilder(string connectionString);
|
||||
|
||||
DbConnection CreateConnection(DbConnectionStringBuilder connectionStringBuilder);
|
||||
}
|
||||
}
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public interface IDbCommandInterceptor
|
||||
{
|
||||
void Executing(string dbName, string sql);
|
||||
|
||||
void Executed(string dbName, string sql);
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
using System.Data.Common;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public interface IDbConnectionFactory
|
||||
{
|
||||
DbConnection GetConnection(string dbName, bool readOnly = true, bool checkWhere = false);
|
||||
|
||||
void Set(string dbName, string connectionString, DbProvider dbProvider);
|
||||
|
||||
void Set(string dbName, string readConnectionString, DbProvider readDbProvider, string writeConnectionString, DbProvider writeDbProvider);
|
||||
|
||||
void UnSet(string dbName);
|
||||
}
|
||||
}
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
public interface IDbEndpointProvider
|
||||
{
|
||||
event EventHandler<EndpointChangedEventArgs> EndpointChanged;
|
||||
|
||||
IDictionary<string, DbEndpoint> GetEndpoints();
|
||||
}
|
||||
}
|
||||
Executable
+313
@@ -0,0 +1,313 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
[ComVisible(false)]
|
||||
internal class OPDbCommand : DbCommand
|
||||
{
|
||||
public delegate void ExecutingEvent(string dbName, string sql);
|
||||
|
||||
public delegate void ExecutedEvent(string dbName, string sql);
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
|
||||
private OPDbConnection innerConnection;
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
|
||||
private OPDbTransaction innerTransaction;
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
|
||||
private readonly DbCommand innerDbCommand;
|
||||
|
||||
private List<ExecutingEvent> ExecutingEventList;
|
||||
|
||||
private List<ExecutedEvent> ExecutedEventList;
|
||||
|
||||
public override string CommandText
|
||||
{
|
||||
get
|
||||
{
|
||||
return innerDbCommand.CommandText;
|
||||
}
|
||||
set
|
||||
{
|
||||
innerDbCommand.CommandText = value;
|
||||
}
|
||||
}
|
||||
|
||||
public override int CommandTimeout
|
||||
{
|
||||
get
|
||||
{
|
||||
return innerDbCommand.CommandTimeout;
|
||||
}
|
||||
set
|
||||
{
|
||||
innerDbCommand.CommandTimeout = value;
|
||||
}
|
||||
}
|
||||
|
||||
public override CommandType CommandType
|
||||
{
|
||||
get
|
||||
{
|
||||
return innerDbCommand.CommandType;
|
||||
}
|
||||
set
|
||||
{
|
||||
innerDbCommand.CommandType = value;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool DesignTimeVisible
|
||||
{
|
||||
get
|
||||
{
|
||||
return innerDbCommand.DesignTimeVisible;
|
||||
}
|
||||
set
|
||||
{
|
||||
innerDbCommand.DesignTimeVisible = value;
|
||||
}
|
||||
}
|
||||
|
||||
public override UpdateRowSource UpdatedRowSource
|
||||
{
|
||||
get
|
||||
{
|
||||
return innerDbCommand.UpdatedRowSource;
|
||||
}
|
||||
set
|
||||
{
|
||||
innerDbCommand.UpdatedRowSource = value;
|
||||
}
|
||||
}
|
||||
|
||||
protected override DbParameterCollection DbParameterCollection => innerDbCommand.Parameters;
|
||||
|
||||
protected override DbConnection DbConnection
|
||||
{
|
||||
get
|
||||
{
|
||||
return innerConnection;
|
||||
}
|
||||
set
|
||||
{
|
||||
innerConnection = value as OPDbConnection;
|
||||
if (innerConnection == null)
|
||||
{
|
||||
innerDbCommand.Connection = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
innerDbCommand.Connection = innerConnection.GetConnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override DbTransaction DbTransaction
|
||||
{
|
||||
get
|
||||
{
|
||||
return innerTransaction;
|
||||
}
|
||||
set
|
||||
{
|
||||
innerTransaction = value as OPDbTransaction;
|
||||
if (innerTransaction == null)
|
||||
{
|
||||
innerDbCommand.Transaction = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
innerDbCommand.Transaction = innerTransaction.GetTransaction();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event ExecutingEvent Executing;
|
||||
|
||||
public event ExecutedEvent Executed;
|
||||
|
||||
public OPDbCommand(DbCommand command, OPDbConnection connection)
|
||||
: this(command, connection, checkWhere: false)
|
||||
{
|
||||
}
|
||||
|
||||
public OPDbCommand(DbCommand command, OPDbConnection connection, bool checkWhere = false)
|
||||
{
|
||||
innerDbCommand = command;
|
||||
innerConnection = connection;
|
||||
ExecutingEventList = new List<ExecutingEvent>();
|
||||
ExecutedEventList = new List<ExecutedEvent>();
|
||||
if (checkWhere)
|
||||
{
|
||||
ExecutingEventList.Add(ExtensionLoader.Instance.GetService<IDbCommandInterceptor>("Opsoft.Data.Audit").Executing);
|
||||
}
|
||||
foreach (ExecutingEvent executingEvent in ExecutingEventList)
|
||||
{
|
||||
Executing += executingEvent;
|
||||
}
|
||||
foreach (ExecutedEvent executedEvent in ExecutedEventList)
|
||||
{
|
||||
Executed += executedEvent;
|
||||
}
|
||||
}
|
||||
|
||||
public override void Cancel()
|
||||
{
|
||||
innerDbCommand.Cancel();
|
||||
}
|
||||
|
||||
public override void Prepare()
|
||||
{
|
||||
innerDbCommand.Prepare();
|
||||
}
|
||||
|
||||
protected override DbParameter CreateDbParameter()
|
||||
{
|
||||
return innerDbCommand.CreateParameter();
|
||||
}
|
||||
|
||||
public override int ExecuteNonQuery()
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeExecuteDbCommand(innerConnection.Provider, this, "ExecuteNonQuery");
|
||||
try
|
||||
{
|
||||
this.Executing?.Invoke(innerConnection.Database, innerDbCommand.CommandText);
|
||||
return innerDbCommand.ExecuteNonQuery();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.ExecuteDbCommandError(innerConnection.Provider, operationId, this, ex, "ExecuteNonQuery");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterExecuteDbCommand(innerConnection.Provider, operationId, this, "ExecuteNonQuery");
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeExecuteDbCommand(innerConnection.Provider, this, "ExecuteNonQueryAsync");
|
||||
try
|
||||
{
|
||||
this.Executing?.Invoke(innerConnection.Database, innerDbCommand.CommandText);
|
||||
return await innerDbCommand.ExecuteNonQueryAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.ExecuteDbCommandError(innerConnection.Provider, operationId, this, ex, "ExecuteNonQueryAsync");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterExecuteDbCommand(innerConnection.Provider, operationId, this, "ExecuteNonQueryAsync");
|
||||
}
|
||||
}
|
||||
|
||||
public override object ExecuteScalar()
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeExecuteDbCommand(innerConnection.Provider, this, "ExecuteScalar");
|
||||
try
|
||||
{
|
||||
this.Executing?.Invoke(innerConnection.Database, innerDbCommand.CommandText);
|
||||
return innerDbCommand.ExecuteScalar();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.ExecuteDbCommandError(innerConnection.Provider, operationId, this, ex, "ExecuteScalar");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterExecuteDbCommand(innerConnection.Provider, operationId, this, "ExecuteScalar");
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeExecuteDbCommand(innerConnection.Provider, this, "ExecuteScalarAsync");
|
||||
try
|
||||
{
|
||||
this.Executing?.Invoke(innerConnection.Database, innerDbCommand.CommandText);
|
||||
return await innerDbCommand.ExecuteScalarAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.ExecuteDbCommandError(innerConnection.Provider, operationId, this, ex, "ExecuteScalarAsync");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterExecuteDbCommand(innerConnection.Provider, operationId, this, "ExecuteScalarAsync");
|
||||
}
|
||||
}
|
||||
|
||||
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeExecuteDbCommand(innerConnection.Provider, this, "ExecuteDbDataReader");
|
||||
try
|
||||
{
|
||||
this.Executing?.Invoke(innerConnection.Database, innerDbCommand.CommandText);
|
||||
return innerDbCommand.ExecuteReader(behavior);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.ExecuteDbCommandError(innerConnection.Provider, operationId, this, ex, "ExecuteDbDataReader");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterExecuteDbCommand(innerConnection.Provider, operationId, this, "ExecuteDbDataReader");
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeExecuteDbCommand(innerConnection.Provider, this, "ExecuteDbDataReaderAsync");
|
||||
try
|
||||
{
|
||||
this.Executing?.Invoke(innerConnection.Database, innerDbCommand.CommandText);
|
||||
return await innerDbCommand.ExecuteReaderAsync(behavior, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.ExecuteDbCommandError(innerConnection.Provider, operationId, this, ex, "ExecuteDbDataReaderAsync");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterExecuteDbCommand(innerConnection.Provider, operationId, this, "ExecuteDbDataReaderAsync");
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
foreach (ExecutingEvent executingEvent in ExecutingEventList)
|
||||
{
|
||||
Executing -= executingEvent;
|
||||
}
|
||||
foreach (ExecutedEvent executedEvent in ExecutedEventList)
|
||||
{
|
||||
Executed -= executedEvent;
|
||||
}
|
||||
innerDbCommand.Dispose();
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+167
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
[ComVisible(false)]
|
||||
internal class OPDbConnection : DbConnection, IDisposable
|
||||
{
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
|
||||
private readonly DbConnection innerConnection;
|
||||
|
||||
private readonly bool checkWhere;
|
||||
|
||||
private bool disposedValue;
|
||||
|
||||
public override string ConnectionString { get; set; }
|
||||
|
||||
public override string Database => innerConnection.Database;
|
||||
|
||||
public override string DataSource => innerConnection.DataSource;
|
||||
|
||||
public override string ServerVersion => innerConnection.ServerVersion;
|
||||
|
||||
public override ConnectionState State => innerConnection.State;
|
||||
|
||||
public override int ConnectionTimeout => innerConnection.ConnectionTimeout;
|
||||
|
||||
public string Provider { get; private set; }
|
||||
|
||||
public DiagnosticSource Listener { get; private set; }
|
||||
|
||||
internal OPDbConnection(DbConnection connection, bool checkWhere, string provider, DiagnosticSource diagnosticListener)
|
||||
{
|
||||
this.checkWhere = checkWhere;
|
||||
innerConnection = connection;
|
||||
innerConnection.StateChange += OnStateChange;
|
||||
Provider = provider;
|
||||
Listener = diagnosticListener;
|
||||
}
|
||||
|
||||
private void OnStateChange(object sender, StateChangeEventArgs e)
|
||||
{
|
||||
base.OnStateChange(e);
|
||||
}
|
||||
|
||||
internal DbConnection GetConnection()
|
||||
{
|
||||
return innerConnection;
|
||||
}
|
||||
|
||||
internal string GetDatabaseType()
|
||||
{
|
||||
return innerConnection.GetType().Name.ToLower();
|
||||
}
|
||||
|
||||
public override void ChangeDatabase(string databaseName)
|
||||
{
|
||||
innerConnection.ChangeDatabase(databaseName);
|
||||
}
|
||||
|
||||
public override void Close()
|
||||
{
|
||||
Guid operationId = Listener.BeforeCloseConnection(Provider, this, "Close");
|
||||
try
|
||||
{
|
||||
innerConnection.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Listener.CloseConnectionError(Provider, operationId, this, ex, "Close");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Listener.AfterCloseConnection(Provider, operationId, this, "Close");
|
||||
}
|
||||
}
|
||||
|
||||
public override void Open()
|
||||
{
|
||||
Guid operationId = Listener.BeforeOpenConnection(Provider, this, "Open");
|
||||
try
|
||||
{
|
||||
innerConnection.Open();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Listener.OpenConnectionError(Provider, operationId, this, ex, "Open");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Listener.AfterOpenConnection(Provider, operationId, this, "Open");
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task OpenAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Guid operationId = Listener.BeforeOpenConnection(Provider, this, "OpenAsync");
|
||||
try
|
||||
{
|
||||
await innerConnection.OpenAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Listener.OpenConnectionError(Provider, operationId, this, ex, "OpenAsync");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Listener.AfterOpenConnection(Provider, operationId, this, "OpenAsync");
|
||||
}
|
||||
}
|
||||
|
||||
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
|
||||
{
|
||||
return new OPDbTransaction(innerConnection.BeginTransaction(isolationLevel), this);
|
||||
}
|
||||
|
||||
protected override DbCommand CreateDbCommand()
|
||||
{
|
||||
return new OPDbCommand(innerConnection.CreateCommand(), this, checkWhere);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposedValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (disposing)
|
||||
{
|
||||
Guid operationId = Listener.BeforeCloseConnection(Provider, this, "Dispose");
|
||||
try
|
||||
{
|
||||
innerConnection.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Listener.CloseConnectionError(Provider, operationId, this, ex, "Dispose");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Listener.AfterCloseConnection(Provider, operationId, this, "Dispose");
|
||||
}
|
||||
}
|
||||
else if (innerConnection.State == ConnectionState.Open)
|
||||
{
|
||||
//Log.Error("垃圾回收时检测到数据库连接有泄漏,请及时关闭数据库连接或使用using语法" + Environment.NewLine + ConnectionString);
|
||||
throw new OverflowException("垃圾回收时检测到数据库连接有泄漏,请及时关闭数据库连接或使用using语法" + Environment.NewLine + ConnectionString);
|
||||
}
|
||||
innerConnection.StateChange -= OnStateChange;
|
||||
base.Dispose(disposing);
|
||||
disposedValue = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Opsoft.NetCore.O3App.Shared.Data
|
||||
{
|
||||
internal class OPDbTransaction : DbTransaction
|
||||
{
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
|
||||
private readonly OPDbConnection innerConnection;
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
|
||||
private readonly DbTransaction innerTransaction;
|
||||
|
||||
public override IsolationLevel IsolationLevel => innerTransaction.IsolationLevel;
|
||||
|
||||
protected override DbConnection DbConnection => innerConnection;
|
||||
|
||||
internal OPDbTransaction(DbTransaction transaction, OPDbConnection connection)
|
||||
{
|
||||
innerTransaction = transaction;
|
||||
innerConnection = connection;
|
||||
}
|
||||
|
||||
internal DbTransaction GetTransaction()
|
||||
{
|
||||
return innerTransaction;
|
||||
}
|
||||
|
||||
public override void Commit()
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeCommitTransaction(innerConnection.Provider, IsolationLevel, innerConnection, "Commit");
|
||||
try
|
||||
{
|
||||
innerTransaction.Commit();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.CommitTransactionError(innerConnection.Provider, operationId, IsolationLevel, innerConnection, ex, "Commit");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterCommitTransaction(innerConnection.Provider, operationId, IsolationLevel, innerConnection, "Commit");
|
||||
}
|
||||
}
|
||||
|
||||
public override void Rollback()
|
||||
{
|
||||
Guid operationId = innerConnection.Listener.BeforeRollbackTransaction(innerConnection.Provider, IsolationLevel, innerConnection, "Rollback");
|
||||
try
|
||||
{
|
||||
innerTransaction.Rollback();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
innerConnection.Listener.RollbackTransactionError(innerConnection.Provider, operationId, IsolationLevel, innerConnection, ex, "Rollback");
|
||||
//Log.Error(ex, ex.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
innerConnection.Listener.AfterRollbackTransaction(innerConnection.Provider, operationId, IsolationLevel, innerConnection, "Rollback");
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
innerTransaction.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user