In the herding code podcast 14 someone mentions that stackoverflow displayed the queries that were executed during a request at the bottom of the page.
It sounds like an excellent idea to me. Every time a page loads I want to know what sql statements are executed and also a count of the total number of DB round trips. Does anyone have a neat solution to this problem?
What do you think is an acceptable number of queries? I was thinking that during development I might have my application throw an exception if more than 30 queries are required to render a page.
EDIT: I think I must not have explained my question clearly. During a HTTP request a web application might execute a dozen or more sql statements. I want to have those statements appended to the bottom of the page, along with a count of the number of statements.
HERE IS MY SOLUTION:
I created a TextWriter class that the DataContext can write to:
public class Logger : StreamWriter { public string Buffer { get; private set; } public int QueryCounter { get; private set; }
public Logger() : base(new MemoryStream())
{}
public override void Write(string value)
{
Buffer += value + "<br/><br/>";
if (!value.StartsWith("--")) QueryCounter++;
}
public override void WriteLine(string value)
{
Buffer += value + "<br/><br/>";
if (!value.StartsWith("--")) QueryCounter++;
}
}
In the DataContext's constructor I setup the logger:
public HeraldDBDataContext()
: base(ConfigurationManager.ConnectionStrings["Herald"].ConnectionString, mappingSource)
{
Log = new Logger();
}
Finally, I use the Application_OnEndRequest event to add the results to the bottom of the page:
protected void Application_OnEndRequest(Object sender, EventArgs e)
{
Logger logger = DataContextFactory.Context.Log as Logger;
Response.Write("Query count : " + logger.QueryCounter);
Response.Write("<br/><br/>");
Response.Write(logger.Buffer);
}