Is there a way to force methods to be accessible only during certain events during the page life cycle. For example, I have a extension to System.Web.UI.Page that adds a PrependTitle method.
I also have a masterpage that embeds another masterpage. The first masterpage sets the base title (Google), the next masterpage prepends the title (Calendar), and a page also prepends the title (21 May 2011).
The result should be:
21 May 2011 :: Calendar :: Google
And this is the case when the PrependTitle is run during the Page_Init event. However, when the method is run during Page_Load the following the results:
Google
So, that brings me to the question: How can it be enforced that a method only be accessible during specified life cycle events?
// The Method Mentioned
public static class PageExtensions
{
public static void PrependTitle(this Page page, string newTitle)
{
page.Title = newTitle + " " + Global.TITLE_DELIMITER + " " + page.Title;
}
}
If you want to brute force ensure that the method is being called from Init, you can inspect the call stack. Something like this:
Then you would use it like:
However, I’d caution that the stack trace isn’t the most reliable thing. In release, code could get optimized such that the Control.OnInit method is inlined so your code wouldn’t be able to see it in the call stack. You could wrap this check in an
#if DEBUGblock so it only executes during development. Depending on your use case, it might be good enough to catch this problem while in DEBUG and not bother doing the check in RELEASE. But that’s up to you.Another option…building on Tommy Hinrichs answer, if all your pages inherit from a base class, you’ll be able to do it a bit more reliably. I’d suggest something like this:
That way, PrependTitle will throw an exception unless it’s called between PreInit and InitComplete (which sounds like exactly what you want).
As one last option, you could be sneaky and use reflection to access the
Control.ControlStateproperty (which is a confusing name because it’s not related to Control State – the thing similar to View State). That property tracks the Control as it goes throw its lifecycle – and it has the following values:You’ll notice that Enum is internal. So is the Control.ControlState property. But with Reflection, you could use that – and you could even use it from an extension method that is external to the Page.
Hope one of those ways will work for you!