Truemag

  • Categories
    • Tips And Tricks
    • Internet
    • PHP
    • Javascript
    • CSharp
    • SQL Server
    • Linux
  • Lastest Videos
  • Our Demos
  • About
  • Contact
  • Home
  • Write With Us
  • Job Request
Home CSharp Asp.net Load Connection String Dynamically For Different Environments

Asp.net Load Connection String Dynamically For Different Environments

I’m working on a project that must be test and implemented on different environments (local, development, staging and production). It means all functions and piece of codes need to be done on local environment then be moved to development environment. Only everything is working well on staging environment then it is moved to production. The process is quite complicated, isn’t it?

In order to avoid creating several web.config for different environments or renaming web.config file when move your web application among environments, we need a way to detect the environment (local, development, staging and production) automatically then return an appropriate connection string for that environment.

Below is an idea that I’m using for my project, it may save your time and avoid some unexpected errors while update the web.config file:

1. Define all environment URLs and Connection String for each

Open your web.config file (or create a new one if it isn’t existed) and add some key/value in the appSettings section as below:

[xml][/xml]
<?xml version="1.0"?>
 
<configuration>
 
    <appSettings>
        <add key="envLocal" value="localhost"/>
        <add key="envDev" value="dev.4rapiddev.com"/>
        <add key="envSG" value="staging.4rapiddev.com"/>
        <add key="envProd" value="4rapiddev.com"/>
        <add key="csLocal" value="Data Source=localhost;Initial Catalog=4rapiddev;Persist Security Info=True;User ID=sa; Password=123456;"/>
        <add key="csDev" value="Data Source=localhost;Initial Catalog=db_development;Persist Security Info=True;User ID=db_user; Password=db_pass;"/>
        <add key="csSG" value="Data Source=localhost;Initial Catalog=db_staging;Persist Security Info=True;User ID=db_user; Password=db_pass;"/>
        <add key="csPRod" value="Data Source=localhost;Initial Catalog=db_production;Persist Security Info=True;User ID=db_user; Password=db_pass;"/>
    </appSettings>
    <system.web>
        <compilation debug="true" />
    </system.web>
 
</configuration>

<?xml version="1.0"?> <configuration> <appSettings> <add key="envLocal" value="localhost"/> <add key="envDev" value="dev.4rapiddev.com"/> <add key="envSG" value="staging.4rapiddev.com"/> <add key="envProd" value="4rapiddev.com"/> <add key="csLocal" value="Data Source=localhost;Initial Catalog=4rapiddev;Persist Security Info=True;User ID=sa; Password=123456;"/> <add key="csDev" value="Data Source=localhost;Initial Catalog=db_development;Persist Security Info=True;User ID=db_user; Password=db_pass;"/> <add key="csSG" value="Data Source=localhost;Initial Catalog=db_staging;Persist Security Info=True;User ID=db_user; Password=db_pass;"/> <add key="csPRod" value="Data Source=localhost;Initial Catalog=db_production;Persist Security Info=True;User ID=db_user; Password=db_pass;"/> </appSettings> <system.web> <compilation debug="true" /> </system.web> </configuration>

2. Create a static function that returns a proper connection string base on environment URL automatically

This function will be called every time create a new SqlConnection (or SqlDatabase) instance.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
 
/// <summary>
/// Summary description for common
/// </summary>
public class common
{
    public static string LoadConnectionString()
    {
        string urlPath = HttpContext.Current.Request.Url.AbsoluteUri.ToLower();
        string connStr = "";
        if (urlPath.Contains(ConfigurationManager.AppSettings["envLocal"]))
            connStr = ConfigurationManager.AppSettings["csLocal"];
        else if (urlPath.Contains(ConfigurationManager.AppSettings["envDev"]))
            connStr = ConfigurationManager.AppSettings["csDev"];
        else if (urlPath.Contains(ConfigurationManager.AppSettings["envSG"]))
            connStr = ConfigurationManager.AppSettings["csSG"];
        else if (urlPath.Contains(ConfigurationManager.AppSettings["envProd"]))
            connStr = ConfigurationManager.AppSettings["csProd"];
        else
            connStr = ConfigurationManager.AppSettings["csProd"];
        return connStr;
    }
}

using System; using System.Collections.Generic; using System.Configuration; using System.Web; /// <summary> /// Summary description for common /// </summary> public class common { public static string LoadConnectionString() { string urlPath = HttpContext.Current.Request.Url.AbsoluteUri.ToLower(); string connStr = ""; if (urlPath.Contains(ConfigurationManager.AppSettings["envLocal"])) connStr = ConfigurationManager.AppSettings["csLocal"]; else if (urlPath.Contains(ConfigurationManager.AppSettings["envDev"])) connStr = ConfigurationManager.AppSettings["csDev"]; else if (urlPath.Contains(ConfigurationManager.AppSettings["envSG"])) connStr = ConfigurationManager.AppSettings["csSG"]; else if (urlPath.Contains(ConfigurationManager.AppSettings["envProd"])) connStr = ConfigurationManager.AppSettings["csProd"]; else connStr = ConfigurationManager.AppSettings["csProd"]; return connStr; } }

3. Example

Check out an example below that demonstrates How to detect the environment and change the connection string for that environment automatically.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connString = common.LoadConnectionString();
 
        using (SqlConnection conn = new SqlConnection(connString))
        {
            string cmdText = "SELECT * FROM tbl_customers";
            SqlCommand cmd = new SqlCommand(cmdText, conn);
            cmd.Connection.Open();
            SqlDataReader reader = cmd.ExecuteReader();
 
            while (reader.Read())
            {
                Response.Write(reader["name"].ToString() + "<br>");
            }
            reader.Close();
            cmd.Connection.Close();
        }
    }
}

using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string connString = common.LoadConnectionString(); using (SqlConnection conn = new SqlConnection(connString)) { string cmdText = "SELECT * FROM tbl_customers"; SqlCommand cmd = new SqlCommand(cmdText, conn); cmd.Connection.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Response.Write(reader["name"].ToString() + "<br>"); } reader.Close(); cmd.Connection.Close(); } } }

Download all source code above

Sep 20, 2011Hoan Huynh
Facebook Like Button And Recommend Button With fb:like, iframe and html5ASP.NET Web Request Post/Get HTTP Example
You Might Also Like:
  • C# How to Get key/value pairs from app.config and web.config
  • MSSQL Connection String For ODBC, OLEDB, SqlConnection
  • String To Lower Case In PHP, JavaScript And .Net (CSharp)
  • String To Upper Case In PHP, JavaScript And .Net (CSharp)
  • Get Or Read AppSettings Item Value From The Web.Config File
  • Implement Google Captcha (reCAPTCHA) With ASP.NET
  • C# Parse Item Value And Name In XML String
  • C# Get File Extension Without Sub String Or Split Function
  • C# Get List of databases in SQL Server
  • Replace String In MySQL
Hoan Huynh

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at [email protected]

9 years ago CSharpAppSettings, ConfigurationManager, SqlCommand, SqlConnection, Web.config204
0
GooglePlus
0
Facebook
0
Twitter
0
Digg
0
Delicious
0
Stumbleupon
0
Linkedin
0
Pinterest
Most Viewed
PHP Download Image Or File From URL
21,918 views
Notepad Plus Plus Compare Plugin
How To Install Compare Text Plugin In Notepad Plus Plus
19,746 views
Microsoft SQL Server 2008 Attach Remove Log
Delete, Shrink, Eliminate Transaction Log .LDF File
15,584 views
JQuery Allow only numeric characters or only alphabet characters in textbox
13,094 views
C# Read Json From URL And Parse/Deserialize Json
9,557 views
4 Rapid Development is a central page that is targeted at newbie and professional programmers, database administrators, system admin, web masters and bloggers.
Recent Posts
  • Research Paper Writing Service
  • Annotated Bibliography Example – How it Can Help You
  • Essay Writing Online Tips – How to Write Essays Online With Essay Proof Editing
  • Get Research Paper Assistance From Professional Help
  • Customized Essay Writing Agency – Why You Want It
Categories
  • CSharp (45)
  • Facebook Graph API (19)
  • Google API (7)
  • Internet (87)
  • iPhone XCode (8)
  • Javascript (35)
  • Linux (28)
  • MySQL (16)
  • PHP (84)
  • Problem Issue Error (29)
  • Resources (32)
  • SQL Server (25)
  • Timeline (5)
  • Tips And Tricks (141)
  • Uncategorized (62)
Recommended
  • Custom Software Development Company
  • Online Useful Tools
  • Premium Themes
  • VPS
2014 © 4 Rapid Development