ASP.NET base page that controls page executiong – level 300

Have you ever wanted to make an ASP.NET base page that controls execution of any aspx that inherits from it?  Like controlling exactly WHEN the Page_Load logic occurs?  Maybe logging the beginning and ending of the Load method.  I’ve come up with a way to do exactly that.  I’m not claiming that this is a unique idea, but it’s a very slick way to track and control the execution of all derived pages.

1:     protected new event EventHandler Load;

2: private void RaiseLoad(EventArgs e)

3: {

4: if(Load != null)

5: Load(this, e);

6: }

7: private void Page_Load(object sender, System.EventArgs e)

8: {

9: Trace.Warn(“Begin Load”);

10: RaiseLoad(e);

11: Trace.Warn(“End Load”);

12: }

13: Page()

14: {

15: base.Load+=new EventHandler(Page_Load);

16: }

Notice that I’m using the “new” keywork on my event.  This hides the real event and creates another of my own.  This method will trap the Load event from System.Web.UI.Page and then raise a new Load event that it completely controls.  It can do some work before and after this happens.  Now any aspx that derives from this will be executing within this framework.  When it subscribes to the Load event, it will be subscribing this this class’s load event.  You can also do this with the other events of the Control class.

2 comments

  1. Michael Palermo

    Another way to accomplish this is to override the various "On" methods of the base class. For example, override the protected OnLoad method. The body of the method would look like this…

    {
    Trace.Warn("Begin Load");
    // next line triggers the event
    base.OnLoad(e);
    Trace.Warn("End Load");
    }

    This accomplishes the same purpose. What are your thoughts?

  2. Jeffrey Palermo

    I thought about that, but if I override that method, the aspx can still override it and execute code before calling base.OnInit. I’ve changed RaiseInit to new virtual OnInit(), and now I trap events from the base class and then reraise them with the same name.

    Check out my next post for my refined code.

Comments are closed.