Asp.net: Measure the request time with a IHttpModule and some javascript

by brunofig 15. February 2007 22:41

Many times we need to show how long a page took to process. One way is to hook up a IHttpModule to the asp.net application, and measuse the time between the Begin and the End request.

 In the BeginRequest we will set a local variable -spanIni - with the DateTime.Now value.
When the page finish all its process, it fires the EndRequest, and we then create a time span with the diference between the spanIni and the DateTime.Now value. This is the time it took to process the page.

	using System;using System.Globalization;using System.Web;namespace CreativeMinds.Web{    public class RequestTime : IHttpModule    {        #region IHttpModule Members        private DateTime spanIni;        private TimeSpan span;        ///<summary>        ///Initializes a module and prepares it to handle requests.        ///</summary>        ///        ///<param name="context">An <see cref="T:System.Web.HttpApplication"></see> 
	        ///that provides access to the methods, properties, and events common to all application 
	        ///objects within an ASP.NET application </param>        public void Init(HttpApplication context)        {            context.BeginRequest += new EventHandler(context_BeginRequest);            context.EndRequest += new EventHandler(context_EndRequest);        }        /// <summary>        /// Handles the EndRequest event of the context control.        /// </summary>        /// <param name="sender">The source of the event.</param>        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>        void context_EndRequest(object sender, EventArgs e)        {            HttpContext context = HttpContext.Current;            if (!context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))                return;            span = DateTime.Now.Subtract(spanIni);            int aux = int.Parse(((Int32)span.TotalMilliseconds).ToString(), NumberStyles.Integer);            context.Response.Write(string.Format("<script>var __set= new Date({0});</script>", aux));        }        /// <summary>        /// Handles the BeginRequest event of the context control.        /// </summary>        /// <param name="sender">The source of the event.</param>        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>        void context_BeginRequest(object sender, EventArgs e)        {            HttpContext context = HttpContext.Current;            if (!context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))                return;            spanIni = DateTime.Now;        }        ///<summary>        ///Disposes of the resources (other than memory) used by the module that implements 
	///<see cref="T:System.Web.IHttpModule"></see>.        ///</summary>        ///        public void Dispose()        {        }        #endregion    }}
	

The above code renders to the page a Javascript variable called "__set" that as the time span for the page proccess.

With this you now just need to show it:

	<%@ Page Language="C#" AutoEventWireup="true" CodeFile="requestTime.aspx.cs" Inherits="requestTime" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>Request Time</title></head><body>    <form id="form1" runat="server">    <div>    <div id="lblReqTime"></div>    </div>    </form>    <script type="text/javascript">    window.onload = function(){        if (__set)        {            var el = document.getElementById("lblReqTime");            el.innerText = "Server time: " + __set.getSeconds() + "." 
	+ __set.getMilliseconds() + " milliseconds.";        }    }    </script></body></html>
	

For test purpose, lets add a Thread.sleep:

using System;using System.Threading;using System.Web.UI;public partial class requestTime : Page{    protected void Page_Load(object sender, EventArgs e)    {        Thread.Sleep(1530);    }}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.7
Theme by Mads Kristensen

About the author

Hi!

My name is Bruno and I'am a senior consultant. When I'm not working, you can catch me playing with my daugther, taking photos and hanging out with my wife and friends. :)

You can also check my dark side or have fun with my vision of the world.

View Bruno Figueiredo's profile on LinkedIn

TwitterCounter for @brunoshine
 
Creative Commons License

 
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
 

Ads

    Page List

      Most comments

      Busby SEO Test Busby SEO Test
      2 comments
      kh Cambodia
      laptop cases laptop cases
      2 comments
      Busby SEO Test Busby SEO Test
      1 comments

      RecentComments

      Comment RSS

      Popuri.us

      My Popularity (by popuri.us)