Modules

Modules, which are self-contained components that receive and handle life-cycle requests and which can monitor or modify a request and its response. It can be packaged up and used in multiple applications. 

 

1. ASP.NET Modules

Modules are classes that implement the System.Web.IHttpModule interface. The interface defines the two methods :

Init(app)                                           This method is called when the module class is passed an HttpApplication object, which is used to register methods for the request life-cycle events and to initialize any resources that are required.
Dispose() This method is called when the request processing has finished. Use this method to release any resources that require explicit management

 

1.1 Setting up the event handlers

Modules are instantiated when the ASP.NET framework creates an instance of the global application class. The module init method is invokded so that the module can prepare itself to handle requests. 

        public void Init(HttpApplication context)
        {
            context.BeginRequest += HandleEvent;
            context.EndRequest += HandleEvent;
        }

The init method is called only when a module object is instantiated, and you must use the init method only to perform one-off configuration tasks. 

 

1.2 Handling the BeginRequest Event

The handleEvent life-cycle event is the place to start the timer. 

       private void HandleEvent(object src, EventArgs args)
        {
            HttpContext ctx = HttpContext.Current;
            if (ctx.CurrentNotification == RequestNotification.BeginRequest)
            {
                timer = Stopwatch.StartNew();
            }
            else
            {
                ctx.Response.Write(string.Format("<div class='alert alert-success'>Elapsed: {0:F5} seconds</div>", ((float)timer.ElapsedTicks) / Stopwatch.Frequency));
            }
        }

 

1.3 Registering a Module

Modules are registered in the web.config file. 

  <system.webServer>
    <modules>
      <add name="Timer" type="UrlRoutes.Infrastructure.TimerModule"/>
    </modules>
  </system.webServer>

Each module is defined using the add element. 

 

2. Creating sef-registering modules

One of the benefits modules conver is that they can be reused across multiple projects. A common approach to module development is to define them in a separate project from the rest of the web application so that the output from the project can be used multiple times. 

PreApplicationStartMethod attribute allows an assemby to define a method that is excuted before Application_Start method in global class.  It is a good place to perform one-off configuration tasks in class library so that additions to the web.config file are not required. 

[assembly: PreApplicationStartMethod(typeof(CommonModules.ModuleRegisteration), "RegisterModule")]

namespace CommonModules
{
    public class ModuleRegisteration
    {
        public static void RegisterModule()
        {
            HttpApplication.RegisterModule(typeof(InfoModule));            
        }
    }
}

 

The arguments for the PreApplicationStartMethod are the type of the class that contains the method that will be executed when the application starts and the name of that method, expressed as string. And the method must be public and static, can not contain any arguments.

 

3. Using Module Events

Module events allow modules to coordinate their activities and share data. Using module events allows you to create more complex functionality without needing to duplicate functionality in multiple modules. 

 

   public class TimerModule : IHttpModule
    {
        public event EventHandler<RequestTimerEventArgs> RequestTimed; 
        private Stopwatch timer;

        public void Dispose()
        {
            //do nothing
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += HandleEvent;
            context.EndRequest += HandleEvent;            
        }

        private void HandleEvent(object src, EventArgs args)
        {
            HttpContext ctx = HttpContext.Current;
            if (ctx.CurrentNotification == RequestNotification.BeginRequest)
            {
                timer = Stopwatch.StartNew();
            }
            else
            {
                float duration = (float) timer.ElapsedTicks/Stopwatch.Frequency;
                ctx.Response.Write(string.Format("<div class='alert alert-success'>Elapsed: {0:F5} seconds</div>", duration));
                if (RequestTimed != null)
                {
                    RequestTimed(this, new RequestTimerEventArgs{Duration = duration});
                }
            }
        }
    }

 

Next step is to create a module that will handle the event from TimerModule and gather details of the overall amount of time spent handling requests. 

        private static float totalTime = 0;
        private static int requestCount = 0;
      
        public void Init(HttpApplication app)
        {
            IHttpModule module = app.Modules["Timer"];
            if (module != null && module is TimerModule)
            {
                var timerModule = (TimerModule) module;
                timerModule.RequestTimed += (src, args) =>
                {
                    totalTime += args.Duration;
                    requestCount++;
                };
            }

            app.EndRequest += (src, args) => app.Context.Response.Write(string.Format("Total time is {0}, request number is {1}", totalTime, requestCount));

 

4. Generating HTML


using HtmlTextWriter defined in System.Web.UI namespace. 

AddAttribute(attr, value) Sets an attribute that will be applied to the next element that is rendered. 
RenderBeginTag(tag) Write the opending tag of an HTML element specified as a value from the HtmlTextWriterTag enumeration
RenderEndTag() Writes the ending tag to match the most recently written openning tag
Write(content) Write the content to the response. 

 

 

 

posted @ 2015-06-28 11:35  tim_bo  阅读(303)  评论(0编辑  收藏  举报