ConnectionString Class - .NET Framework

This page is part of the Class Library Pages collection.
Click the icon to see the index.


Allows the developer to specify all application connection strings at once (by machine name and environment), rather than having to keep changing the connection string when deploying to production, then changing it back to continue development work.

Sample Implementation

Config File Settings

The following is an excerpt from the web.config or app.config file. Note that machine names are expected to be entirely in uppercase.

    <add key="Environment.default" value="Dev"/>
    <add key="Environment.debugger" value="Dev"/>
    <add key="Environment.DEVELOPMENTWEBSERVER" value="Dev"/>
    <add key="Environment.PRODUCTIONWEBSERVER" value="Prod"/>
    . . .
    <add name="DatabaseName.Dev" connectionString="DevelopmentConnectionString"/>
    <add name="DatabaseName.Prod" connectionString="ProductionConnectionString"/>
  . . .

Code to get Connection String Name


Dim csName As String = ConnectionString.GetName("DatabaseName") 


string csName = ConnectionString.GetName("DatabaseName"); 

Source Code


Imports Microsoft.VisualBasic

Public Class ConnectionString

    Public Shared Function GetName(ByVal dbName As String) As String

        Dim result As String = ""
        Dim envKey As String = GetEnvironmentKey()

        If envKey.Length > 0 Then

            result = ConfigurationManager.AppSettings(envKey)

            If result IsNot Nothing And result.Length > 0 Then
                result = dbName & "." & result
            End If

        End If

        Return result

    End Function

    Private Shared Function GetEnvironmentKey() As String

        Dim result As String = ""

        If System.Diagnostics.Debugger.IsAttached Then
            result = "Environment.debugger"
            result = "Environment." + Environment.MachineName.ToUpper()
        End If

        If result Is Nothing Then
            result = ""
        ElseIf ConfigurationManager.AppSettings(result) Is Nothing Then
            result = "Environment.default"
        End If

        Return result

    End Function

End Class