Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

ConnectionString Class - .NET Framework

RSS
Modified on Tue, Dec 01, 2009, 3:02 PM by Administrator Categorized as ASP·NET Web Forms, Class Library, ·Net Framework
This page is part of the Class Library Pages collection.
Click the icon to see the index.

Features

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.

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

Code to get Connection String Name

VB.NET

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

C#

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

Source Code

VB.NET

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"
        Else
            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

C#

TODO

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.