Skip to content

Debugging and Profiling

Sean Lynch edited this page Jul 11, 2013 · 6 revisions

There are a few ways to debug/profile NPoco. They are listed below, and are commonly done by inheriting from Database and overriding a specific method. Note: Make sure you instantiate your new class (MyDb as below) when creating a Database from then on.

Manual

public class MyDb : Database 
{
    public MyDb(string connectionStringName) : base(connectionStringName) { }
    public override void OnExecutingCommand(IDbCommand cmd)
    {
        File.WriteAllText("log.txt", FormatCommand(cmd));
    }
}

MiniProfiler

http://miniprofiler.com/

public class MyDb : Database 
{
    public MyDb(string connectionStringName) : base(connectionStringName) { }
    public override IDbConnection OnConnectionOpened(IDbConnection conn)
    {
        return new ProfiledDbConnection((DbConnection)conn, MiniProfiler.Current);
    }
}

Glimpse

http://getglimpse.com/

Glimpse will usually hook itself up by installing the following packages.

Install-Package Glimpse.ADO
Install-Package Glimpse.Mvc4 (or your mvc version)

Glimpse Screenshot

Show last SQL executed on the ASP.NET error page

Credit: Sam Saffron

public class MyDb : Database 
{
    public MyDb(string connectionStringName) : base(connectionStringName) { }

    public override void OnException(Exception e)
    {
        base.OnException(e);
        e.Data["LastSQL"] = this.LastSQL;
    }
}
void Application_Error(object sender, EventArgs e)
{
    var lastError = Server.GetLastError();

    string sql = null;
    try
    {
        sql = lastError.Data["LastSQL"] as string;
    }
    catch
    { 
        // skip it
    }
    if (sql == null) return;

    var ex = new HttpUnhandledException("An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.", lastError);

    Server.ClearError();

    var html = ex.GetHtmlErrorMessage();
    html = html.Insert(html.IndexOf("<b>Stack Trace:</b>"), @"
    <b>Last Sql:</b><br><br>
    <table width='100%' bgcolor='#ffffccc'>
        <tbody>
            <tr>
                <td><code><pre>" + sql + @"</pre></code></td>
            </tr>
        </tbody>
    </table><br>");

    Response.Write(html);
    Response.StatusCode = 500;
    Response.End();
}

sql on error page