A week ago I talked about using XML Serialization as a means to persist and retrieve application settings. Using that example as a stepping stone, I want to extend this idea further by exposing these settings via a base ASP.NET page class for use in your web applications.
In general, base page classes in your web applications help you to remove code smells in your web applications by allowing you to “Move Up” or “Pull Up” code that is common to all your web pages. Often, accessing application settings is one such action you do in all your web pages and is better exposed via a base page class.
I am going to take the same SiteSettings Class we used before and just expand the static methods a bit more to include saving the configuration in cache with a dependency on our sitesettings.config file in the application directory. This will improve performance so we don’t have to access the application settings from the file each time, but also have the application settings refreshed when a change is detected in the underlying file.
Here is our base page class, called BasePage, that essentially fetches the application settings and exposes the entire class via the protected field settings. As all protected fields, settings is accessible to any class that derives from BasePage.
Last, we create a page that derives from BasePage, called WorkingPage, that essentially just displays the current application settings on a web page. The settings are grabbed from the protected field settings in BasePage and displayed accordingly.
And just to be complete, here is sitesettings.config and the sitesettings.aspx page used in the example:
Application settings aren’t the only things you can place in your base pages, but it’s a good place to start if base page classes are new to you.