using System.Data; using System.Diagnostics; using System.Text; using Chloe.Infrastructure.Interception; namespace DB; public class DbCommandInterceptor : IDbCommandInterceptor { public void ReaderExecuting(IDbCommand command, DbCommandInterceptionContext interceptionContext) { ToDb(command, interceptionContext.Exception); } public void ReaderExecuted(IDbCommand command, DbCommandInterceptionContext interceptionContext) { ToDb(command, interceptionContext.Exception); } public void NonQueryExecuting(IDbCommand command, DbCommandInterceptionContext interceptionContext) { ToDb(command, interceptionContext.Exception); } public void NonQueryExecuted(IDbCommand command, DbCommandInterceptionContext interceptionContext) { ToDb(command, interceptionContext.Exception); } public void ScalarExecuting(IDbCommand command, DbCommandInterceptionContext interceptionContext) { ToDb(command, interceptionContext.Exception); } public void ScalarExecuted(IDbCommand command, DbCommandInterceptionContext interceptionContext) { ToDb(command, interceptionContext.Exception); } private void ToDb(IDbCommand command, Exception? exception) { #if DEBUG Trace.WriteLine(command.CommandText); Trace.WriteLine(AppendDbCommandInfo(command)); #endif } private string AppendDbCommandInfo(IDbCommand command) { var sb = new StringBuilder(); foreach (IDbDataParameter param in command.Parameters) { if (param == null) continue; object value; if (param.Value == null || param.Value == DBNull.Value) { value = "NULL"; } else { value = param.Value; if (param.DbType == DbType.String || param.DbType == DbType.AnsiString || param.DbType == DbType.DateTime) value = "'" + value + "'"; } sb.AppendFormat("{3} {0} {1} = {2};", Enum.GetName(typeof(DbType), param.DbType), param.ParameterName, value, Enum.GetName(typeof(ParameterDirection), param.Direction)); sb.AppendLine(); } return sb.ToString(); } }