Skip to content

Instantly share code, notes, and snippets.

Created March 10, 2014 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/9460950 to your computer and use it in GitHub Desktop.
Save anonymous/9460950 to your computer and use it in GitHub Desktop.
DB Custom Profiler class
public class CustomDBProfiler : IDbProfiler
{
private readonly static CustomDBProfiler instance = new CustomDBProfiler();
[ThreadStatic]
private static Stopwatch sw = new Stopwatch();
public delegate void ExecuteFinishDelegate(IDbCommand profiledDbCommand, ExecuteType executeType, DbDataReader reader, string parameterString, string result, TimeSpan elapsedTime);
public delegate void ExecuteStartDelegate(IDbCommand profiledDbCommand, ExecuteType executeType);
public delegate void ErrorDelegate(IDbCommand profiledDbCommand, ExecuteType executeType, Exception exception, string parameterString, TimeSpan elapsedTime);
public delegate void ReaderFinishDelegate(IDataReader reader);
public static ExecuteFinishDelegate OnExecuteFinish;
public static ExecuteStartDelegate OnExecuteStart;
public static ErrorDelegate OnExecuteError;
public static ReaderFinishDelegate OnReaderFinish;
private CustomDBProfiler()
{
}
public static CustomDBProfiler Instance
{
get
{
return instance;
}
}
public void ExecuteFinish(IDbCommand profiledDbCommand, ExecuteType executeType, DbDataReader reader)
{
if (sw == null)
{
return;
}
var result = "";
if (reader != null)
result = reader.RecordsAffected.ToString();
else
result = "";
var ptxt = new StringBuilder();
foreach (DbParameter param in profiledDbCommand.Parameters)
{
ptxt.Append(String.Format("{2} {0} = {1} ", param.ParameterName, param.Value, ptxt.Length > 0 ? "," : ""));
}
if (OnExecuteFinish != null)
OnExecuteFinish(profiledDbCommand, executeType, reader, ptxt.ToString(), result, sw.Elapsed);
}
public void ExecuteStart(IDbCommand profiledDbCommand, ExecuteType executeType)
{
if (sw == null)
{
sw = new Stopwatch();
}
else
{
sw.Restart();
}
if (OnExecuteStart != null)
OnExecuteStart(profiledDbCommand, executeType);
}
public bool IsActive
{
get { return true; }
}
public void OnError(IDbCommand profiledDbCommand, ExecuteType executeType, Exception exception)
{
if (sw == null)
{
return;
}
sw.Stop();
var ptxt = new StringBuilder();
foreach (DbParameter param in profiledDbCommand.Parameters)
{
ptxt.Append(String.Format("{2} {0} = {1} ", param.ParameterName, param.Value, ptxt.Length > 0 ? "," : ""));
}
if (OnExecuteError != null)
OnExecuteError(profiledDbCommand, executeType, exception, ptxt.ToString(), sw.Elapsed);
}
public void ReaderFinish(IDataReader reader)
{
if (sw == null)
{
return;
}
if (OnReaderFinish != null)
OnReaderFinish(reader);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment