Click here to Skip to main content
Click here to Skip to main content
Go to top

ASP.NET - C# Application Environment Backsplash

, 6 Jul 2005
Rate this:
Please Sign up or sign in to vote.
Demonstrates how to diplay a backsplash image in an ASP.NET application by taking advantage of inheritance.

Introduction

How often have you or the users of the application thought you were in development mode of your ASP.NET application but were actually in production? This could be a very costly mistake, especially if someone modifies data. Most companies developing software have multiple application environments such as: Development, Certification "Testing", Demonstration, and Production. It is very critical that developers, quality assurance analysts, users, etc. know what environment they are in. You might think, everyone should know this because they go to a specific URL or it is displayed on the login screen. Guess what, we are all human and often can forget we are in production because there is little variation between the user interfaces in development and production.

This article demonstrates how easy it is to demonstrate the application environment in your ASP.NET applications. By taking advantage of inheritance, each WebForm in the application can derive from a custom base page. This allows the code to be written in one location and reduces redundancy by not coding every page to output the environment. The BasePage class will render a backsplash image with the application environment repeated as the background. The BasePage class utilizes a static AppConfig class to get the ApplicationEnvironment variable from the Web.config file. The Web.config file contains an appSetting node. I added a custom application_environment node to the appSettings. The application_environment modes in this example are:

  1. Development - "DEV"
  2. Certification - "CERT"
  3. Demonstration - "DEMO"
  4. Production - "PROD"

The BasePage only renders a backsplash "watermark" image for DEV, CERT, and DEMO. We do not want to see a backsplash while in production.

The Code

As stated above, the code is quite simple. It consists of two classes. The BasePage class and the AppConfig class. WebForms that want to display the backsplash inherit from the BasePage.

BasePage

This class overrides the Render method and outputs a backsplash image dependent upon the application environment.

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Text;

namespace DevEnvWebApp
{
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Description: BaseClass all webforms can derive from.
    ///                 This example is given in C#. This class
    ///                 demonstrates the simplicity to view the
    ///                 current application environment state.
    ///                 
    /// Programmer:  Kenny Young
    /// E-mail:      ken.g.young@gmail.com
    /// <span class="code-SummaryComment"></summary>
</span>
    public class BasePage : System.Web.UI.Page
    {
        public BasePage()
        {
            
        }

        /// <span class="code-SummaryComment"><summary>
</span>
        /// Returns the current application environment's state.
        /// <span class="code-SummaryComment"></summary>
</span>
        protected string ApplicationEnvironment
        {
            get
            {
                try
                {
                    AppConfig config = AppConfig.GetInstance;
                    return config.ApplicationEnvironment.ToUpper();
                }
                catch
                {
                    return "";
                }
            }
        }


        /// <span class="code-SummaryComment"><summary>
</span>
        /// Override the System.Web.UI.Page's Render method. This method
        /// outputs a backsplash depending on the application environment.
        /// <span class="code-SummaryComment"></summary>
</span>
        /// <span class="code-SummaryComment"><PARAM name="writer">HtmlTextWriter</PARAM>
</span>
        protected override void Render(HtmlTextWriter writer)
        {
            string appEnv = this.ApplicationEnvironment;
        
            try
            {
                string backImage = "";
                    
                switch(appEnv)
                {
                    // Are we in production mode?
                    case "PROD" :
                        base.Render(writer);
                        return;
                    // Are we in development mode?
                    case "DEV" :
                        backImage = "/images/dev.gif";
                        break;
                    // Are we in certification mode?
                    case "CERT":
                        backImage = "/images/cert.gif";
                        break;
                    // Are we in demo mode?
                    case "DEMO":
                        backImage = "/images/demo.gif";
                        break;
                }

                StringBuilder sbWater = new StringBuilder();
                sbWater.Append(" style=\"");
                sbWater.Append("background-attachment: scroll;" + 
                        " background-image: url(" + 
                        this.Request.ApplicationPath + 
                        backImage + "); background-repeat: " + 
                        "repeat; background-color: transparent;\"");
    
                System.Text.StringBuilder sb = 
                       new System.Text.StringBuilder();
                System.IO.StringWriter sw = new System.IO.StringWriter(sb);
                HtmlTextWriter newWriter = new HtmlTextWriter(sw);
            
                base.Render(newWriter);
        
                // Find the body tag and anything inbetween 
                // the greater than sign.
                Match match = Regex.Match(sb.ToString(), 
                      @"(<<bB>[oO][dD][yY](.*?)>

WebForm - Derived Class

This class derives from the BasePage. It automatically inherits the functionality to render the backsplash image. Any WebForm you want to display the backsplash should derive from BasePage.

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DevEnvWebApp
{
    /// <span class="code-SummaryComment"><SUMMARY>
</span>
    /// Summary description for WebForm1.
    /// <span class="code-SummaryComment"></SUMMARY>
</span>
    public class MainForm : BasePage
    {
        protected System.Web.UI.WebControls.Button btnClickMe;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <span class="code-SummaryComment"><SUMMARY>
</span>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// <span class="code-SummaryComment"></SUMMARY>
</span>
        private void InitializeComponent()
        {    
            this.btnClickMe.Click += new System.EventHandler(this.btnClickMe_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private void btnClickMe_Click(object sender, System.EventArgs e)
        {
            Response.Redirect("AnotherForm.aspx");
        }
    }
}

AppConfig Class

This class is a static class that acts as an interface to the Web.config file. It has properties to retrieve the values from the appSettings node in the Web.config XML. The Application Environment is stored in the config file.

using System; 
using System.Configuration; 
using System.Collections; 
using System.Text; 
using System.Xml; 

namespace DevEnvWebApp 
{ 
    public class AppConfig 
    { 
        public static AppConfig GetInstance = new AppConfig(); 
        private const string APP_NAME = "application_name"; 
        private const string APPLICATION_ENVIRONMENT = "application_environment"; 
        private Hashtable collection = null; 

        private AppConfig() 
        { 
            try 
            { 
                collection = new Hashtable(); 

                foreach (string key in 
                  ConfigurationSettings.AppSettings.AllKeys) 
                { 
                    collection.Add(key, 
                      ConfigurationSettings.AppSettings[key]); 
                } 
            } 
            catch (Exception e) 
            { 
                throw new Exception("Exception caught " + 
                         "in AppConfig constructor.", e); 
                
            } 
        } 

        public string ApplicationName 
        { 
            get
            {
                return GetValue(APP_NAME); 
            }
        } 

        public string ApplicationEnvironment
        { 
            get
            {
                return GetValue(APPLICATION_ENVIRONMENT); 
            }
        } 

        public string GetValue(string key) 
        { 
            try 
            { 
                return collection[key].ToString(); 
            } 
            catch (Exception e) 
            { 
                throw new Exception("Exception caught" + 
                           " in AppConfig.GetValue", e); 
            } 
        } 
    } 
}

Web.config appSettings

Contains an appSettings section that allows custom variables. The application environment is stored here as the application_environment key.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="application_environment" value="CERT"/>
    </appSettings>
    <system.web>

Screenshots

Below is an example of the backsplash seen on the web pages. The application mode is Development - DEV.

Backsplash - DEV

Another WebForm with an application mode of Development - DEV.

Backsplash - DEV

Below is an example of the first screenshot but in Certification mode - CERT.

Backsplash - DEV

That's it! A simple solution to an overlooked problem.

Enjoy!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Kenny Young

United States United States
Ken currently works as the Director of Software Engineering at the Pediatrics Epidemiology Center at the University of South Florida. He is involved in the architecture and design on numerous clinical trial projects. Some of the project include:
 
1. Rare Diseases Clinical Research Network
2. TrialNet - Diabetes
3. Teddy - Diabetes
4. CCOP - Cancer
5. AIDA - Diabetes

Comments and Discussions

 
QuestionHttpModule implementation? PinmemberMike Ellison6-Jul-05 13:38 
AnswerRe: HttpModule implementation? PinmemberKenny Young7-Jul-05 4:06 
GeneralGreat - and maybe you can use machine.comfig PinmemberMark Focas27-Jun-05 13:06 
GeneralRe: Great - and maybe you can use machine.comfig PinmemberKenny Young27-Jun-05 13:28 
GeneralGreat article Pinmemberjdeer27-Jun-05 9:55 
GeneralRe: Great article PinmemberKenny Young27-Jun-05 13:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 6 Jul 2005
Article Copyright 2005 by Kenny Young
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid