Jeffrey Palermo (.com)

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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.


Posted 10-20-2004 4:41 AM by Jeffrey Palermo

[Advertisement]

Comments

Michael Palermo wrote re: ASP.NET base page that controls page executiong - level 300
on 10-20-2004 2:13 AM
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?
Jeffrey Palermo wrote re: ASP.NET base page that controls page executiong - level 300
on 10-21-2004 12:11 AM
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.