Monitor how much time the server is taking to process a request and to give a response.
Sometimes we need to monitor the performance of our web application, like how much time the server is taking to process a page.
To find out the time a particular request is taking to get processed we can take the help of HttpModule.In the code below, I have used an HttpModule and in that module I have used two events, those are:
HttpApplication.BeginRequest Event
The BeginRequest event signals the creation of any given new request. This event is always raised and is always the first event to occur during the processing of a request.
In this event, I am initializing time value (i.e, setting a start time).
HttpApplication.EndRequest Event
Occurs as the last event in the HTTP pipeline chain of execution when ASP.NET responds to a request.
In this event, I am finding the time difference between the start and end of the request.
publicclassTimeCalculation:IHttpModule { DateTime dtStartTime; publicvoid Init(HttpApplication context) { context.BeginRequest += newEventHandler(context_BeginRequest); context.EndRequest += newEventHandler(context_EndRequest); } void context_BeginRequest(object sender, EventArgs e) { dtStartTime = DateTime.Now; // Give a start time. } void context_EndRequest(object sender, EventArgs e) { // For success response only show the execution time. if (HttpContext.Current.Response.StatusCode == 200) { TimeSpan tsDifference = DateTime.Now - dtStartTime; // Find out the time difference. // Show how much time is taken to execute the page. HttpContext.Current.Response.Write("Took " + tsDifference.Milliseconds + " milli second(s) to execute the page."); } } publicvoid Dispose() { } } Then we have to register the HttpModule in web.config file. The follow line will do that. <httpModules> <addname="TimeCalculation"type="TimeCalculation"/> </httpModules>
Now comes the time to test it : )
Actually we do not have to do anything else for examining it, the only thing we have to do is to open any page in the Web Browser and thats it. We will see a message at the bottom part of the page saying “Took xxx milli second(s) to execute the page.”
This code takes into account the time taken by the server to process the request, It is not taking into account the time that the Browser is taking to process the page for rendering or the time it is taking the response to reach from server to client.
Here in this code I am showing the message at the bottom part of the page. Neither it is a good idea to show this message to the end user nor it is useful for monitoring purpose.
So, Instead of showing this message we can store it in DB for future reference and it will help us in analyzing the performance of the site.
Hope this will help you : )
Thanks