This is a journey on how to build a better Base page. The result of this will be a reusable framework that you can use to create as many Base pages as you like (on many different sites) and still have something that will keep the designers on your team happy. There is a lot to explain so I am breaking this up into several parts starting with the pros and cons of all the approaches I have seen in the past.
Whenever I start a new ASP.NET project I am asked how to make a look and feel that can be reused on all pages of the site. The following are the several approaches I have seen to date:
Comments: This is the approach I have seen done by folks breaking into ASP.NET development. Maintaining sites like this can be a nightmare to say the least. Just pray your client does not ask to change the main look and feel or you will be staying late to get it done…
Comments: This is a little better as it makes use of User Controls to centralize the look and feel into separate components but can still be problematic and time consuming when the main look and feel templates need to be added/removed.
OnInit()
because it does not guarantee that your controls will be in place at all phases of execution within your ASP.NET pipeline, the code for generating the base page should be in the CreateChildControls()
call. You can force CreateChildControls()
to be called by calling EnsureChildControls()
. Comments: We used this approach at two different client sites and it worked well. However when I presented this approach to the client I was at when I wrote this, they balked and wanted to know how to use the visual designer and also how to make changes without compiling and redeploying the site DLL. The next approach is the answer to that question.
Comments: Although this approach served us well at a client site, we also did not have to worry about them changing the main layout (yet). If that happens I am going to recommend migrating to the next approach which is the approach we are going to be implementing in this series of posts related to this topic.
I mention ASP.NET 2.0 here because the fact that it’s coming soon will make most of the ASP.NET 1.1 techniques in this article obsolete.
Comments – We have used this approach at several clients in the past, it has worked well in the past. One of the things I did not like about it was the lack of centralized configuration and no way to solidify the state objects in our site. It would be nice to have a framework that did all this, that is what we are going to do in this article.
So why write this article? Simple, even though I have seen a lot of companies upgrade their systems to Windows 2003 Server, Windows XP and have embraced using the .NET framework, I do know of a few places that are still stuck using NT 4 Server (even though the client machines are on Windows 2000 Professional which for them are doing well). So yes, using this approach will be invalid when VS.NET 2005 is released to the world. But for the rest of us that get stuck working with old technology, this will be a huge timesaver.
To close this section, I will describe the steps to get started on your own BasePage Framework implementation.
System.Web
reference. SuperBasePage
class and inherit from System.Web.UI.Page
. BasePageConfigurationHandler
. Implement the System.Configuration.ICustomConfigurationHandler
interface. Add an XML file so we have a place to put our configuration stuff (this does not need to be part of the project, it’s just a nice place to keep our configuration schema for the Base pages).
Add the following XML to the schema…
/
I am going to continue this where we left off in part one, so I am skipping the steps for setting up our Base Page Framework project. Refer to part one to see these steps…
Now I like to centralize everything that is consistent about the pages in my site (i.e. script links, CSS files, body attributes, default name etc...) in one place. I have seen other base pages hard code this stuff which always makes me shudder. (As it should everyone because hard coding things like this should be avoided.)
IMHO it makes sense to place these stuff in a location that can be changed without having to recompile our project. My favorite place for this is the Web.Config file. But since this is a separate framework assembly, it might be a good idea to not use the default
settings available in the
section because I personally think this is less intuitive as to what the settings are for. Plus it would be nice to not clutter our appsettings
for this application with the configuration information that is going to be used across one to many sites. To solve this problem, we create a custom configuration section for our Base Page Framework. That is the subject of this section.
The first thing we need to do for our base page framework is to create a custom configuration handler to parse the custom configuration settings in our web.config. (See part one for the schema). We do this by implementing the IConfigurationSectionHandler
interface which is part of the System.Configuration
namespace. This is really easy to do and if you know how to parse XML, you are 4/5th of the way there.
The IConfigurationSectionHandler
interface has one method called Create()
. Here is the prototype for Create
and what each argument is intended to provide:
public object Create(object parent, object configContext, XmlNode section);
object
: this object can be anything you want. I like to create a separate configuration class that holds all my settings and return it so I can cache it for later use. This example will be doing the very same thing. object parent
The parent config section.
object configContext
An HttpConfigurationContext
object. This is only passed to us when we call it from ASP.NET. As you probably guessed, if you do this out of a Windows app via an app.config file, this parameter will be null
.
XmlNode section
This is our custom configuration section. We will be parsing this to get our configuration settings out of the config file.
Let’s get started…
I like to keep my items in any project logically separated, so create a folder for our configuration stuff. Call it “configuration”. Add a class to this folder and call it BasePageConfigurationSectionHandler
. This class will be our configuration handler so implement the IConfigurationSectionHandler
interface. Here is the code:
public class BasePageSectionHandler : System.Configuration.IConfigurationSectionHandler { #region IConfigurationSectionHandler Members public object Create(object parent, object configContext, XmlNode section) { System.Xml.XmlNodeList pages = section.SelectNodes("page"); return new BasePagesConfiguration(pages); } #endregion }
In this implementation, we are going to return the next class we are going to create which is the BasePagesConfiguration
class. If you look at the schema for our configuration you will see that there can be 1:n page elements. This is because you can have more than one base page in your site. So if you guessed that BasePagesConfiguration
is a collectionbase
object, then you guessed right. We are going to need to implement this object next. Here is the code:
public class BasePagesConfiguration : System.Collections.ReadOnlyCollectionBase { public BasePagesConfiguration(System.Xml.XmlNodeList pages) { foreach(System.Xml.XmlNode page in pages) this.InnerList.Add(new BasePageConfiguration(page)); } public BasePageConfiguration this[string pageName] { get { foreach(BasePageConfiguration pge in this.InnerList) { if(pge.Name == pageName) return pge; } throw new System.InvalidOperationException("The base page ID " + pageName + " could not be found in" + " the current configuration"); } } }
The indexer of this object returns a single BasePageConfiguration
object via a key value. I am not too concerned with how quickly the collection returns individual configuration objects so I am using a simple loop. The reason we don’t really care about performance here is because our base page will internally cache its configuration object so it does not have to keep going out to the config file every time it gets requested.
Finally we get to the configuration object. We are going to aptly call this BasePageConfiguration
. Create the BasePageConfiguration
class in your project. Here is the code. I am going to assume that you know how to parse XML documents so I am not going to go into detail on how that works. I will just explain what each field of this object is for.
public class BasePageConfiguration { private string _pageName = string.Empty; private NameValueCollection _bodyAttributes = new NameValueCollection(); private string _defaultTitle = string.Empty; private NameValueCollection _scriptFiles = new NameValueCollection(); private NameValueCollection _cssFiles = new NameValueCollection(); private NameValueCollection _metaTags = new NameValueCollection(); public BasePageConfiguration(XmlNode xml) { //parse the xml passed to us and set the configuration state //first get the name of this page System.Xml.XmlAttribute pageName = (XmlAttribute)xml.Attributes.GetNamedItem("name"); System.Xml.XmlAttribute defaultTitle = (XmlAttribute)xml.Attributes.GetNamedItem("defaultTitle"); if(defaultTitle != null) _defaultTitle = defaultTitle.Value; else _defaultTitle = string.Empty; if(pageName != null) _pageName = pageName.Value; else throw new System.Configuration.ConfigurationException("The name" + " attribute is required on all basepage configuration entries."); //get the body tag attributes System.Xml.XmlNodeList bodyAttrib = xml.SelectNodes("body/attribute"); foreach(XmlNode attr in bodyAttrib) { XmlAttribute name = (XmlAttribute)attr.Attributes.GetNamedItem("name"); XmlAttribute val = (XmlAttribute)attr.Attributes.GetNamedItem("value"); if(name != null && val != null) { _bodyAttributes.Add(name.Value,val.Value); } } //get the site settings System.Xml.XmlNode title = xml.SelectSingleNode("site/title"); if(title != null) { XmlAttribute val = (XmlAttribute)title.Attributes.GetNamedItem("value"); if(val != null) _defaultTitle = val.Value; } //get the main page links System.Xml.XmlNodeList cssFiles = xml.SelectNodes("links/css"); foreach(XmlNode css in cssFiles) { XmlAttribute file = (XmlAttribute)css.Attributes.GetNamedItem("file"); XmlAttribute path = (XmlAttribute)css.Attributes.GetNamedItem("path"); if(file != null && path != null) _cssFiles.Add(file.Value,path.Value); } System.Xml.XmlNodeList scriptFiles = xml.SelectNodes("links/script"); foreach(XmlNode script in scriptFiles) { XmlAttribute file = (XmlAttribute)script.Attributes.GetNamedItem("file"); XmlAttribute path = (XmlAttribute)script.Attributes.GetNamedItem("path"); if(file != null && path != null) _scriptFiles.Add(file.Value,path.Value); } // get the place holder settings so we can see what user // controls to load into our base page placeholders System.Xml.XmlNodeList metaTags = xml.SelectNodes("metatags/meta"); foreach(XmlNode tag in metaTags) { XmlAttribute name = (XmlAttribute)tag.Attributes.GetNamedItem("name"); XmlAttribute content = (XmlAttribute)tag.Attributes.GetNamedItem("Content"); this._metaTags.Add(name.Value,content.Value); } } //do not allow outside access to the individual //values of the configuration public NameValueCollection BodyAttributes{get{return _bodyAttributes;}} public HorizontalAlign SiteAlignment{get{return _alignment;}} public string DefaultTitle{get{return _defaultTitle;}} public NameValueCollection Scripts{get{return _scriptFiles;}} public NameValueCollection StyleSheets{get{return _cssFiles;}} public string Name{get{return _pageName;}} public NameValueCollection MetaTags{get{return _metaTags;}} }
_pageName
This is the ID of our base page. Each base page in the system must have a unique name so its configuration can be located in the config file (more on this later when we get into implementing the actual base page Base).
private NameValueCollection _bodyAttributes
These are the individual body attribute tags that will go into each and every one of our pages. They are injected into the HTML in the base page Base OnAddParsedSubObject()
call (many thanks to Michael Earls for showing me the light on this one).
private string _defaultTitle
This is the default title that will be used on all pages of our site. Should the HTML designer not put anything into the
tag we will replace that blank value with this one.
private NameValueCollection _scriptFiles
This is a list of script links that will be placed inside the tags.
private NameValueCollection _cssFiles
This is a list of stylesheet links that will be placed inside the tags.
private NameValueCollection _metaTags
This is a list of default metatags that will appear in all pages of our site.
Finally as you can see, the configuration is a read only object. This is logical because it will only get its values from the configuration file when the object is created by the configuration handler.
Using this handler is easy. To create an instance of the configuration handler, you need to call GetConfig()
in your ConfigurationSettings
object.
Configuration.BasePagesConfiguration baseConfiguration =
(Configuration.BasePagesConfiguration)
System.Configuration.ConfigurationSettings.GetConfig(
"base.configuration");
Returns: the appropriate configuration object based on your section in the configSections
tag. See the following snippet taken from the schema we created in part one.
The object that gets returned here is whatever you decided to return from your IConfigurationSectionHandler.Create
implementation. In this case, it is our ReadOnlyCollectionBase
"BasePagesConfiguration
" object that contains the individual BasePageConfiguration
objects for our site.
The name attribute of this configuration section is the configuration section in your .config file. The type is the fully qualified object name that implements the IConfiguraitonSectionHandler
interface, along with the name of the assembly this object resides in, separated by a comma. If you are referencing a strong named assembly then you need to put all four parts of the assembly name into the type attribute like this (taken from System.dll):
As you can see, you put the remaining four parts of the strong name into the type tag after your DLL name (separated by commas).
In part 3, we are going to get started on the implementation of the SuperBasePage
itself. To close in part 4, I am going to show you how to throw in some extra features that wrap standard site state management. The objects are classes that implement the ISmartQueryString
, ISmartSession
, and ISmartApplication
interfaces.
I am going to continue this at the point where we left off creating the BasePageConfiguration
class. In this part, we are going to implement the SuperBasePage
that will be used in all the derived Base pages of your site. It is useful to have multiple Base pages in your site because you might want to have a layout for printer friendly pages, popup windows, dialogs, etc…
This part is a bit on the long side, I will try to keep it as short as possible given the amount of stuff that’s happening here. I will also post some UML class and sequence diagrams in the next part so there will be some decent docs to go with it.
The SuperBasePage
is actually two separate classes and a user control that implements a custom interface all working together to form a template. They are declared as follows:
public interface IBaseTemplate { PlaceHolder ContentArea {get;} } public class SuperBasePage : WebUI.Page { private BaseServerForm _baseForm = null; //new SuperBasePage("BASE_FORM"); //the form tag where we place all our webserver controls private Configuration.BasePageConfiguration _config = null; …
These three items when properly used will not only allow us to quickly create Base pages that can be configured from the web.config, but also allows us to leave the HTML in our individual pages on our site. I have seen other frameworks / Base page concepts where you need to remove the HTML
, HEAD
, TITLE
, BODY
, and FORM
tags in order to be useable. We will not be doing that here. It is important that we keep that part intact for two reasons:
To start with, we need to look at the existing objects at our disposal in the System.Web
namespace. The ones we are interested in right now are System.Web.UI.Page
and System.Web.UI.HtmlControls.HtmlForm
. The latter of the two is what we will be worrying about first.
The HtmlForm
when set with a server tag becomes the heart of the ubiquitous ASP.NET webform. You cannot instantiate server controls on your page without it. Herein lies our problem, how can we get our form which we have to define on each page to behave the same by displaying the same outlying content with unique content for each page, and more importantly, how do we get the content from our page to actually nest itself within this form’s content area? What I have seen done in past Base pages I have developed is to “move” the content from each of their pages to a specified “content area” in their Base page class. We are still doing that here but in a more discreet way. And, as I have already mentioned, most of the examples force you to delete the HTML header and footer along with the Form
tag from your page before using it (try explaining that to a web-designer and see what they do).
There must be a better way, so instead of moving the content from our derived page to the Base page’s content area, we will do a little switcharoo with the HtmlForm
and change it into a form that has the following functionality…
So in essence instead of our Base page high-jacking the content of each page, our Base page receives an HtmlForm
and makes it work in such a way that allows us to set content wherever we want from a given template that the form will initialize when it gets created. You will notice that our BaseServerForm
is nothing more than a plain old HtmlForm
with a template reference. The following is the code for our Base server form…
public class BaseServerForm : HtmlUI.HtmlForm { private WebCtlUI.PlaceHolder _uiTemplatePlcHldr = new WebCtlUI.PlaceHolder(); internal BaseServerForm(HtmlUI.HtmlForm oldFrm,IBaseTemplate uiTemplate) { foreach(string key in oldFrm.Attributes.Keys) this.Attributes.Add(key,oldFrm.Attributes[key]); System.Type frmTp = oldFrm.GetType(); // move the controls first - so they are located // in the main form before we // rip apart the htmlform via reflection while(oldFrm.Controls.Count > 0) uiTemplate.ContentArea.Controls.Add( (System.Web.UI.Control)oldFrm.Controls[0]); //copy the old form's values into our new form... foreach(FieldInfo fields in frmTp.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) this.GetType().GetField(fields.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, fields.GetValue(oldFrm)); this._uiTemplatePlcHldr.Controls.Add( (System.Web.UI.Control)uiTemplate); this.Controls.Add((System.Web.UI.Control) this._uiTemplatePlcHldr); } public IBaseTemplate BaseTemplate { get{return (IBaseTemplate)_uiTemplatePlcHldr.Controls[0];} } }
The constructor of this class takes two things, an HtmlForm
object and a reference to something called an IBaseTemplate
. This is how you will implement the IBaseTemplate
in your code…
public class AcmeBaseTemplate : System.Web.UI.UserControl, BasePageFramework.IBaseTemplate { protected System.Web.UI.WebControls.PlaceHolder _content; protected System.Web.UI.WebControls.PlaceHolder _leftNav; public PlaceHolder LeftNavigation {get{return _leftNav;}} #region IBaseTemplate Members public PlaceHolder ContentArea { get { return _content; } } #endregion
This template interface is how I get around a limitation in another framework that does almost the same thing this one does. Why define an interface to be used for our complete Base layout if we may want to change that layout in the future? What I think makes sense is to define a class that exposes our Base page’s content areas so we can change what they contain at will. Plus, it would also be nice to create different layouts with access to all areas in our page. This will also allow us to dynamically change our layouts at runtime under certain conditions. Finally, it would also be really nice if our designers could change the look of the Base page without going into the code but instead by using the designer. That is where using a UserControl (that implements our IBaseTemplate
interface) comes in handy.
There is one gotcha however, we can’t be sure of what the template developer is going to call the area to place our content. We really need to know this so we can relocate the pages controls to this area in a nice seamless and discreet manner. This is where the IBaseTemplate
interface comes in to play. As you can see in the above example, we define a placeholder where our derived pages' content will go in the Base page and return it through this interface's only property “ContentArea
” (which coincidentally returns a placeholder for our content). Now our Base page will have a contract with the UserControl that says “I will assume responsibility of locating the controls where they belong so you don’t have too”.
You will see later on in the Base page definition why we need to expose the other placeholders in our user control to the outside world via properties as I have done in the above example.
The BaseServerForm
class doesn’t do much other than encapsulate the movement of our page's content to the template’s content area (and perform the role of server form) so besides loading a UI template, it is basically just a server form with a layout defined. I should also note that we do not want anything but the Base page creating a BaseServerForm
, so we hide the constructor from the outside world by declaring it internal
. This is because the Base page is the only object that should ever need to crate a BaseServerForm
. However, we do want developers to be able to reference the form in case they decide to change something programmatically before the request is handled. I had to resort to using reflection to rip apart the old HtmlForm
’s private values and copy them to our BaseServerForm
. We could have used a “has-a” relationship with the HtmlForm
but that seemed a bit on the clunky side, therefore I made it an "is-a" relationship to make its relationship with our pages seamless. Also note that it is critical that we move the control tree and attributes of the old HtmlForm
to our new BaseServerForm
before we use reflection to get any internal
values. We can get to the control tree just fine, we don’t need to use reflection to get to it. I normally do not like using reflection unless absolutely required. I like to think of reflection like I think of Duct Tape, it’s a tool that has a noble purpose… But when used “creatively” you can end up really shooting yourself in the foot (if you will forgive the old C cliché).
Now that we have our BaseServerForm
class defined, we need to define the super base page from which we will derive all our sites' base pages. Here is the code…
public class SuperBasePage : WebUI.Page { #region Constants //large string builder initial buffer siz private const int LG_STR_BUFFER_SZ = 512; //medium string builder inital buffer size private const int MD_STR_BUFFER_SZ = 256; //small (default) string builder buffer size private const int SM_STR_BUFFER_SZ = 128; private const string OPEN_TITLE_TAG = ""; private const string OPEN_HEAD_TAG = ""; private const string CLOSE_HEAD_TAG = ""; private const string OPEN_HTML_TAG = ""; private const int DEFAULT_LINK_WIDTH = 20; //this is used to estimage the number of characters //to reserve space for in our string builders //in an attempt to maximize efficency #endregion #region SuperBasePage Members //our form sits in this placeholder private WebCtl.PlaceHolder _serverFormPlcHldr = new WebCtl.PlaceHolder(); //the title of the page (displayed in the caption bar) private string _title = string.Empty; private BaseServerForm _baseForm = null; //new SuperBasePage("BASE_FORM"); //the form tag where we place all our webserver controls private Configuration.BasePageConfiguration _config = null; private string _basePageName = string.Empty; private ISmartQueryString _smartQueryString = null; private ISmartSession _smartSession = null; private ISmartApplication _smartApp = null; #endregion #region Properties public string Title { get{return this._title;} set{this._title = value;} } public BaseServerForm BaseForm {get{return this._baseForm;}} public IBaseTemplate MainUITemplate {get{return this._baseForm.BaseTemplate;}} public ISmartSession SmartSession { get{ if(this._smartSession == null) throw new InvalidOperationException("You must" + " initialize the smart session state" + " before you can reference it"); else return this._smartSession; } } public ISmartApplication SmartApplication { get{ if(this._smartApp == null) throw new InvalidOperationException("You must" + " initialize the smart application state" + " before you can reference it"); else return this._smartApp; } } public ISmartQueryString SmartQueryString { get { if(this._smartQueryString == null) throw new InvalidOperationException("You must" + " initialize the smart query string" + " before you can reference it"); else return this._smartQueryString; } } #endregion protected override void CreateChildControls() { InitSmartQueryString(ref this._smartQueryString); if(this._smartQueryString != null) this._smartQueryString.SetQueryStringInfo(this.Page); InitSmartSession(ref this._smartSession); if(this._smartSession != null) this._smartSession.SetSessionState(this.Page.Session); //allows us to set the base page state from //the child page before any rendering of the base page occurs BasePreRender(this._baseForm); //call the virutal method to allow the base page //to set the appropriate usercontrols into the base template LoadTemplatePanels(); } protected override void OnInit(EventArgs e) { this.EnsureChildControls(); base.OnInit (e); } protected override void AddParsedSubObject(Object obj) { //put all the configuration extras into our html header here //make sure you modify the body tag as well since it is also //editable from our custom configuration section if(obj is HtmlCtl.HtmlForm) { BasePageFramework.IBaseTemplate tmplt = null; this.LoadBaseUITemplate(ref tmplt); if(tmplt == null) throw new InvalidOperationException("Unable to" + " load the base UI Template"); this._baseForm = new BaseServerForm((HtmlCtl.HtmlForm)obj, tmplt); //replace the object reference with //our own "base server form" obj = this._baseForm; } if(obj is Web.UI.LiteralControl) { Web.UI.LiteralControl htmlHeader = (Web.UI.LiteralControl)obj; //we only need to do this processing when we are in the header if(htmlHeader.Text.IndexOf(OPEN_HTML_TAG)>=0) { //we are going to need the stuff from //the configuration now so load it up... ConfigLoadingArgs cfgParam = new ConfigLoadingArgs(); InitializeConfiguration(ref cfgParam); this._config = (Configuration.BasePageConfiguration) Cache["BASE_CONFIGURATION_" + cfgParam.BasePageID]; if(this._config == null) InitFromConfiguration(cfgParam.BasePageID); if(this._config != null) { System.Text.StringBuilder htmlBuilder = new System.Text.StringBuilder(htmlHeader.Text.Length*2); htmlBuilder.Append(htmlHeader.Text); //check to see if the current literal control //being passed to us is actually //the HTML header - if it is then we need //to add any values from the custom web.config settings //if the current page has any of the same //values in the body tag or any inline scripts - //then we need to allow the page to override //the web.config settings - //this is in following with the //same pattern for everything in ASP.NET //(machine.config-web.config-page...) //see if the title is filled in if not //insert the default title //if the title tag is missing then add one now int openingTitleTagOffset = htmlHeader.Text.ToUpper().IndexOf( OPEN_TITLE_TAG,0,htmlHeader.Text.Length); int endTitleTagOffset = htmlHeader.Text.ToUpper().IndexOf( CLOSE_TITLE_TAG,0,htmlHeader.Text.Length); endTitleTagOffset -= CLOSE_TITLE_TAG.Length-1; int titleLen = htmlHeader.Text.Substring(openingTitleTagOffset, endTitleTagOffset -openingTitleTagOffset).Length; //get the length of our title if(openingTitleTagOffset >= 0) { //check the length of our title //if the title is missing then add the default one if(titleLen == 0) htmlBuilder.Insert(openingTitleTagOffset+ OPEN_TITLE_TAG.Length, this._config.DefaultTitle); } else { int openHeadTagOffset = htmlHeader.Text.ToUpper().IndexOf(OPEN_HEAD_TAG, 0,htmlHeader.Text.Length); //if the head tag is missing then add it //otherwise just insert the default title if needed //create another string Builder to handle //our missing header/title tag System.Text.StringBuilder subHtml = new System.Text.StringBuilder((OPEN_HEAD_TAG.Length + CLOSE_HEAD_TAG.Length + OPEN_TITLE_TAG.Length + CLOSE_TITLE_TAG.Length) +_config.DefaultTitle.Length); if(openHeadTagOffset == -1) { subHtml.Append(OPEN_HEAD_TAG); subHtml.Append(OPEN_TITLE_TAG); subHtml.Append(_config.DefaultTitle); subHtml.Append(CLOSE_TITLE_TAG); subHtml.Append(CLOSE_HEAD_TAG); //insert the output right //after the opening HTML tag htmlBuilder.Insert(OPEN_HTML_TAG.Length, subHtml.ToString()); } else { subHtml.Append(OPEN_TITLE_TAG); subHtml.Append(_config.DefaultTitle); subHtml.Append(CLOSE_TITLE_TAG); //insert the output right after //the opening Head Tag htmlBuilder.Insert(openHeadTagOffset, subHtml.ToString()); } } //insert our configuration metatags and //scripts/links after the closing title tag... //int closingTitleTagOffset = htmlBuilder.ToString().ToUpper().IndexOf(CLOSE_HEAD_TAG, 0,htmlBuilder.ToString().Length); htmlBuilder.Replace(CLOSE_HEAD_TAG, GetWebConfigLinks(htmlBuilder.ToString())); RenderBodyTagLinks(htmlBuilder); //replace the text in the literal //control with our new header htmlHeader.Text = htmlBuilder.ToString(); } } } this.Controls.Add((System.Web.UI.Control)obj); } #region HTML Header Parsing Code private void RenderBodyTagLinks(System.Text.StringBuilder htmlBuilder) { //rip out the body tag and replace it with our own //that has the attributes from the web config file //but allows the individual pages to override //these settings at the page level string bodyTag = htmlBuilder.ToString(); int bodyTagOffset = bodyTag.ToUpper().IndexOf("); bodyTag = bodyTag.Substring(bodyTagOffset, bodyTag.Length - bodyTagOffset); //create the attributes that will be dumped into the body tag //make sure it is not already in the body before entering it //if it is in the body then throw it out so the individual page //can override the web.config's settings System.Text.StringBuilder bodyTagBuilder = new System.Text.StringBuilder(SM_STR_BUFFER_SZ); bodyTagBuilder.Append(" foreach(string attribute in _config.BodyAttributes.Keys) if(bodyTag.IndexOf(attribute) == -1) { bodyTagBuilder.Append(" "); bodyTagBuilder.Append(attribute); bodyTagBuilder.Append("=/""); bodyTagBuilder.Append( _config.BodyAttributes.Get(attribute)); bodyTagBuilder.Append("/" "); } //append the global body tag attributes to the //end of the current attribute list in our body tag string newAttribList = bodyTag.Substring(5,bodyTag.Length-6); //remove the opening body tag and closing bracket //get the current attributes out of the old body tag //and add them to our bodytagbuilder bodyTagBuilder.Append(" "); bodyTagBuilder.Append(newAttribList); int bodytagoffset = htmlBuilder.ToString().IndexOf(bodyTag); //remove the old body tag from our string builder htmlBuilder.Remove(bodytagoffset,htmlBuilder.Length-bodytagoffset); string output = htmlBuilder.ToString(); htmlBuilder.Append(bodyTagBuilder.ToString()); } //takes the existing script links and returns a new string //containing the existing links merged with the ones in the web.config private string GetWebConfigLinks(string oldHtml) { System.Text.StringBuilder subHtml = new System.Text.StringBuilder((_config.Scripts.Count* DEFAULT_LINK_WIDTH)+CLOSE_HEAD_TAG.Length); this.GetMetaTags(subHtml,oldHtml); this.GetStyleSheetLinks(subHtml); this.GetScriptLinks(subHtml); subHtml.Append("/r/n/t"); subHtml.Append(CLOSE_HEAD_TAG); return subHtml.ToString(); } private void GetMetaTags(System.Text.StringBuilder htmlBuilder, string oldHtml) { foreach(string metaTag in _config.MetaTags.Keys) { if(oldHtml.IndexOf(metaTag) == -1) { htmlBuilder.Append("/r/n/t/t"); htmlBuilder.Append(" " + " htmlBuilder.Append("NAME=/""); htmlBuilder.Append(metaTag); htmlBuilder.Append("/""); htmlBuilder.Append(" CONTENT=/""); htmlBuilder.Append(_config.MetaTags.Get(metaTag)); htmlBuilder.Append("/"/>"); } } } private void GetStyleSheetLinks(System.Text.StringBuilder scriptLinks) { foreach(string key in this._config.StyleSheets.Keys) { scriptLinks.Append("/r/n/t/t " + " scriptLinks.Append("type=/"text/css/" "); scriptLinks.Append("rel=/"stylesheet/" "); scriptLinks.Append("href=/""); scriptLinks.Append(ParseRootPath( this._config.StyleSheets.Get(key))); scriptLinks.Append("/"); scriptLinks.Append(key); scriptLinks.Append("/""); scriptLinks.Append("/>"); scriptLinks.Append(Environment.NewLine); } } private void GetScriptLinks(System.Text.StringBuilder scriptLinks) { foreach(string key in this._config.Scripts.Keys) { scriptLinks.Append("/r/n/t/t "); } } #endregion #region Utility Methods private string ParseRootPath(string path) { if(path.IndexOf('~') == 0) { if(System.Web.HttpContext.Current.Request.ApplicationPath == "/") { path = path.Replace("~",""); } else path = path.Replace("~", System.Web.HttpContext.Current.Request.ApplicationPath); return path; } else return path; } private void InitFromConfiguration(string pageName) { this._config = (Configuration.BasePageConfiguration)Cache["BASE_CONFIGURATION_" + pageName]; if(this._config == null) { Configuration.BasePagesConfiguration baseConfiguration = (Configuration.BasePagesConfiguration) System.Configuration.ConfigurationSettings.GetConfig( "base.configuration"); if(baseConfiguration == null) return; //the base configuration was not set //in the current web.config - exit now... //load the current page's configuration and stick it //into cache so it does not have to be reloaded //on subsequent requests this._config = baseConfiguration[pageName]; Cache.Add("BASE_CONFIGURATION_" + pageName, this._config,null,DateTime.MaxValue, TimeSpan.FromDays(100), System.Web.Caching.CacheItemPriority.NotRemovable,null); } } #endregion #region Virutal Methods protected virtual void InitializeConfiguration(ref ConfigLoadingArgs configParams) {} /// /// override this method in our child pages to allow us /// to set base page state before any rendering takes place /// in the base page /// protected virtual void BasePreRender(BaseServerForm baseForm) {} /// /// override this method to allow the /// base page to load the base UI template /// the base UI template is of type BaseUITemplate /// BaseUITemplate is of type Usercontrol /// protected virtual void LoadBaseUITemplate(ref BasePageFramework.IBaseTemplate tmplt) {} /// /// override in the base page so you can load /// user controls at the derived base page /// where you want them to be loaded - this is done /// so the derived base page can subscribe to events /// fired by these controls /// protected virtual void LoadTemplatePanels() {} /// /// override this method to initialize the smart /// querystring with your derived smart querystring instance /// /// derived instance of a smart query string base /// class that Implements the ISmartQueryString interface protected virtual void InitSmartQueryString(ref ISmartQueryString isqs) {} /// /// override this method to initialized the smart session /// state with your derived smart session instance /// /// derirved smart session object that implements /// the ISmartSession Interface protected virtual void InitSmartSession(ref ISmartSession ises) {} /// /// override this method to initialize the smart /// application state with your derived smart application instance /// /// derived smart application object that /// implements the ISmartApplication interface protected virtual void InitSmartApplication(ref ISmartApplication iapp) {} #endregion }
Here is how you implement a page that derives from the SuperBasePage
:
public class AcmeBase : BasePageFramework.SuperBasePage { protected override void LoadBaseUITemplate(ref BasePageFramework.IBaseTemplate tmplt) { tmplt = (IBaseTemplate) LoadControl("~/BaseTemplateControl.ascx"); } protected override void InitializeConfiguration(ref BasePageFramework.Configuration.ConfigLoadingArgs configParams) { configParams.BasePageID = "AcmeBase"; } protected override void InitSmartApplication(ref BasePageFramework.SmartState.ISmartApplication iapp) { iapp = (ISmartApplication)new AcmeAppObject(); } protected override void InitSmartQueryString(ref BasePageFramework.SmartState.ISmartQueryString isqs) { isqs = (ISmartQueryString)new AcmeSmartQueryString(); } protected override void InitSmartSession(ref BasePageFramework.SmartState.ISmartSession ises) { ises = (ISmartSession)new AcmeSmartSession(); } }
And this is the derived base template implementation that gets loaded during the virtual LoadBaseUITemplate
call:
public class AcmeBaseTemplateMain : System.Web.UI.UserControl, BasePageFramework.IBaseTemplate { private PlaceHolder _header = new PlaceHolder(); private PlaceHolder _leftNavigation = new PlaceHolder(); private PlaceHolder _contentArea = new PlaceHolder(); private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region IBaseTemplate Members public PlaceHolder ContentArea { get { return _contentArea; //The IBaseTemplate Interface's ContentArea method //is used by the SuperBasePage to handle //content placement from the derived page } } public PlaceHolder Header { get{return _header;} //PLACEHOLDER THAT CONTAINS OUR HEADER'S CONTENT } public PlaceHolder LeftNav { get{return _leftNavigation;} //PLACEHOLDER THAT CONTAINS OUR LEFT NAV BAR } #endregion }
You can see that I am using a combination of overriding the AddParsedSubObject()
and the AddChildControls()
virtual methods. This is because we only need to use the AddParsedSubObject()
method to do one thing. Intercept our HTML header and HTML form before it gets added to our page. I got this idea from Micheal Earls (a fellow Magenicon from Atlanta). Check out his blog here. I have seen this method overridden in server controls for child control tags but not in a page class like this. I thought it was a very clever use of the method and it solves the problem of having to remove the outer HTML from around our content area. Now that we have the outer HTML intact it also gives us the opportunity to override the Base page configuration at the page level thus imitating the web.config settings/page directive pattern that currently exists in ASP.NET.
For those of you unfamiliar with this method, it gets fired whenever a handler encounters a child element. In the case of the System.Web.Page
class, it gets fired a total of three times.
As you may have already guessed, we only really care about the first two, when it is fired for the HTML tag, that is when we get our custom configuration settings and place them into the header. This part of the handler needs to really scream so I struggled for awhile on what would be the best way. I have used HtmlWriter
s in the past but I thought for this it was too much overhead since we are already using one in the render call, plus I am forced to parse all the HTML in order to make that approach effective (so clearly, it is not an option here).
After some experimentation I decided to go with StringBuilder
s since they are faster than vanilla string concatenation (in fact the performance of the StringBuilder
is comparable to using the old memcpy()
call in C). To truly take advantage of the StringBuilder
’s performance you need to estimate how much space you will need ahead of time. If you don’t the StringBuilder
will be moving a lot of character memory around when it has to resize itself internally to make more room. I use a combination of the default HTML content along with what is in the web.config to calculate a good initial size for my StringBuilder
’s buffer. The reason this is so important is because when the StringBuilder
reaches its limit during an append()
, it creates a new buffer twice the size of the old one and copies all the character data over to the new buffer (then destroys the old buffer). All this movement of character data negates the performance gains of using a StringBuilder
(although it is still probably faster than plain old string concatenation operators). Regardless, it’s better to be safe than sorry IMHO.
We are doing some initialization in the CreateChildControls
override as well. We do this to ensure that these methods are only called once when the request gets handled. This is done by calling EnsureChildControls()
from our init()
call. This call “ensures” that our child controls get created (in this case we are initializing the SmartQueryString
and SmartSessionState
). Since they are not critical to using the Base page and since I am trying to keep this short, I will go into more detail on these two classes in the final part.
The virtual methods in the SuperBasePage
are to be overridden in our derived SuperBasePage
class. Using these virtual methods allows us to define how and what our Base page loads when it is requested.
Here is what each method does…
protected virtual void InitializeConfiguration(ref ConfigLoadingArgs configParams);
Override this method so we can tell the Base page what page configuration to use. (Remember that we have more than one page element in our config section? This is where we specify what section to use.) In this example, the Base page name attribute we want from our configuration is “AcmeBase
”. We are passing the configParams
argument by reference so we can set it in our override (in the derived base page).
Here is an example of how to implement it.
protected override void InitializeConfiguration(ref BasePageFramework.Configuration.ConfigLoadingArgs configParams) { configParams.BasePageID = "AcmeBase"; }
This in turn will tell our Super Base page to load settings from the following page config section…