Click here to Skip to main content
15,868,141 members
Articles / Web Development / ASP.NET
Article

ASP.NET - C# Application Environment Backsplash

Rate me:
Please Sign up or sign in to vote.
4.63/5 (11 votes)
6 Jul 20052 min read 67.2K   416   53   6
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.

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

namespace DevEnvWebApp
{
    /// <summary>
    /// 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
    /// </summary>
    public class BasePage : System.Web.UI.Page
    {
        public BasePage()
        {
            
        }

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


        /// <summary>
        /// Override the System.Web.UI.Page's Render method. This method
        /// outputs a backsplash depending on the application environment.
        /// </summary>
        /// <PARAM name="writer">HtmlTextWriter</PARAM>
        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](.*?)>)");
                // The result.
                string result = match.Value;
                string resultBgColor = Regex.Match(result, 
                  @"(<bB>[gG][cC][oO][lL][oO][rR][=][""](.*?)[""])").Value;
                string newResult = "";
                
                // Did we find a bgcolor in the string?
                if(resultBgColor.Length > 0)
                {
                    // Replace it with our version.
                    newResult = result.Replace(resultBgColor, "");
                }
                
                newResult = result.Substring(0, result.Length - 1);
                newResult = newResult + sbWater.ToString() + ">";

                sb.Replace(result, newResult);
                // Remove the BgColor.
                sb.Replace("bgColor", "bggColor");
                // Output the new html.
                Response.Write(sb.ToString());
            }
            catch(Exception ex)
            {
                string err = ex.Message;
            }
        }

    }
}

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.

C#
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
{
    /// <SUMMARY>
    /// Summary description for WebForm1.
    /// </SUMMARY>
    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);
        }
        
        /// <SUMMARY>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </SUMMARY>
        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.

C#
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
<?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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHttpModule implementation? Pin
Mike Ellison6-Jul-05 13:38
Mike Ellison6-Jul-05 13:38 
AnswerRe: HttpModule implementation? Pin
Kenneth Young7-Jul-05 4:06
Kenneth Young7-Jul-05 4:06 
GeneralGreat - and maybe you can use machine.comfig Pin
Mark Focas27-Jun-05 13:06
Mark Focas27-Jun-05 13:06 
GeneralRe: Great - and maybe you can use machine.comfig Pin
Kenneth Young27-Jun-05 13:28
Kenneth Young27-Jun-05 13:28 
GeneralGreat article Pin
Member 207692927-Jun-05 9:55
Member 207692927-Jun-05 9:55 
GeneralRe: Great article Pin
Kenneth Young27-Jun-05 13:31
Kenneth Young27-Jun-05 13:31 

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

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