ASP.NET: Change page title based on database to which you're connecting

On occasion, you may find it useful to provide a visual cue that the user is not in an application's production environment. This is especially useful during a late night crunch when the developers, system administrators, and the Q.A. team are distracted and tired.

Below is some code which allows you to change the page title and its style based on the database specified in a connection string. Note that we are parsing an Entity Framework connection string, not an ADO.NET connection string.

Site.Master

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a ID="lnkPageTitle" class="navbar-brand" runat="server" href="~/">Our Application</a>
        </div>
        ...
    </div>
    ...
</div>

Site.Master.cs

protected void Page_Load(object sender, EventArgs e)
{
    string connectionString = ConfigurationManager.ConnectionStrings["OurApplicationEntities"].ConnectionString;
    var efBuilder = new EntityConnectionStringBuilder(connectionString);
    string providerConnectionString = efBuilder.ProviderConnectionString;
    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(providerConnectionString);
    string database = sqlBuilder.InitialCatalog;
    switch (database.ToUpper())
    {
        case "OURDATABASE_PROD":
            // do nothing;
            break;
        default:
            lnkPageTitle.InnerText = "Our Application -- THIS IS NOT THE PRODUCTION ENVIRONMENT!";
            lnkPageTitle.Style.Add("background-color", "yellow");
            lnkPageTitle.Style.Add("color", "red");
            lnkPageTitle.Style.Add("font-weight", "bold");
            break;
    }
}

What the code above does is, if the initial catalog (database) is anything other than the production database then the page title (the HTML anchor tag in the Site.Master) is changed to "Out Application -- THIS IS NOT THE PRODUCTION ENVIRONMENT", plus the background color is set to yellow while the foreground is set to red.

Ideally, you could use an application variable in the application's web.config file to specify the initial catalog (again, the database) used by the production environment.

Comments

Popular posts from this blog

Using Reference Aliases

List of Visual Studio Keyboard Shortcuts