Click here to Skip to main content
15,880,427 members
Articles / Programming Languages / Visual Basic
Article

How to persist changes to My.Settings.ConnectionString

Rate me:
Please Sign up or sign in to vote.
4.75/5 (32 votes)
1 Aug 2007CPOL2 min read 281.5K   1.4K   62   96
This article describes a solution for persisting changes to the ReadOnly My.Settings.ConnectionString with nearly trivial code.

Introduction

Connection strings in the My.Settings class are Application scoped. This causes a problem when deploying an application because the development machine only rarely will have the same connection string as the deployment target machine of your customer. Add to this the fact that strongly typed datasets' table adapters get their connection string from the My.Settings class, and this creates the need for some kind of workaround. The most common workaround I have seen involves setting the TableAdapter.Connection.ConnectionString property with the appropriate connection string before calling Fill(). However, this is non-intuitive for most people, and for very large projects, updating these commands can be problematic.

Here is a better way to persist changes to application scoped connection strings for strongly typed datasets. This will handle any number of connection string overrides you want, with only trivial editing. No need to modify or re-modify the settings.designer.vb file or set TableAdapter.Connection.ConnectionString settings on every table adapter in your project.

Background

How does it work? Well, all the settings, including the application scoped settings, are not kept in memory as read-only. So, the run-time value can be modified, and all future calls to the My.Settings item will get the modified value. What the application scoping does is refuse to persist them. So, this little addition to the MySettings class allows you to:

  1. Update the runtime value of the application scoped setting.
  2. Apply any saved user scoped override setting via the SettingsLoaded event before they are ever referenced by table adapters.
  3. Persist any modified application scoped setting to the user scoped override setting via the SettingsSaving event.

Using the Code

  1. Go to your project Properties, Settings, and make a user scoped string entry for each Application scoped connection string with the same base name plus an added suffix. For example, I use the suffix "UserOverride". If I have two application scoped connection settings called "ConnectionString1" and "ConnectionString2", then I create two user scoped strings (not (connection strings)) called "ConnectionString1UserOverride" and "ConnectionString2UserOverride".
  2. Create a new module called Settings.UserOverride.vb, and insert this code:
  3. VB
    Option Strict On
    Option Explicit On
    Namespace My
        Partial Friend NotInheritable Class MySettings
            Inherits Global.System.Configuration.ApplicationSettingsBase
    
            Private Shared userOverrides() As String = { _
                "ConnectionString1", _
                "ConnectionString2" _
            }
    
            Private Shared userOverrideSuffix As String = "UserOverride"
    
            Public Sub SetUserOverride(ByVal [property] As String, _
                                       ByVal value As String)
                Me([property]) = value
            End Sub
    
            Private Sub userOverride_SettingsLoaded(ByVal sender As Object, _
                    ByVal e As System.Configuration.SettingsLoadedEventArgs) _
                Handles Me.SettingsLoaded
                Dim userProperty As String
                For Each appProperty As String In userOverrides
                    userProperty = appProperty & userOverrideSuffix
                    If CType(Me(userProperty), String).Length > 0 Then
                        Me(appProperty) = Me(userProperty)
                    End If
                Next
            End Sub
    
            Private Sub userOverride_SettingsSaving(ByVal sender As Object, _
                    ByVal e As System.ComponentModel.CancelEventArgs) _
                Handles Me.SettingsSaving
                Dim userProperty As String
                For Each appProperty As String In userOverrides
                    userProperty = appProperty & userOverrideSuffix
                    Me(userProperty) = Me(appProperty)
                Next
            End Sub
        End Class
    End Namespace
  4. Edit the userOverrides() array to include the names of the Application scoped connection strings in your application for which you have created user overrides. If you used a different suffix for your overrides, then change the userOverrideSuffix value also.
  5. Now, wherever you need to update your connection string, call SetUserOverride(). For example, whenever you would want to call My.Settings.ConnectionString1 = "My new string", which is not allowed, you instead call My.Settings.SetUserOverride("ConnectionString1", "My new string").
  6. VB
    ' This doesn't work because ConnectionStrings are ReadOnly
    'My.Settings.ConnectionString1 = "My new string"
    
    ' This works!
    My.Settings.SetUserOverride("ConnectionString1", "My new string")
  7. Go to your My Project, Application Settings, and make sure that Save My.Settings on Shutdown is enabled.

Points of Interest

Las Vegas! Walt Disnet World Florida! Maybe I'll think of some REALLY interesting ones later. :)

History

  • July 12, 2007: Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Systems Engineer Mark J Means Consulting
United States United States
I have been a software consultant since 1985 working on everything from the Commodore VIC-20 & RadioShack CoCo games to 8051 Embedded USB Microcontrollers to Windows Vista database applications. I have written over a half million lines of code since 2004. Please see my DataConnectionDialog control at http://mjmeans.com/dcd.aspx.

Comments and Discussions

 
AnswerRe: C# version works great! Pin
dmageiras17-Mar-09 6:28
dmageiras17-Mar-09 6:28 
GeneralRe: C# version works great! Pin
Jlrray17-Mar-09 9:17
Jlrray17-Mar-09 9:17 
GeneralGREAT solution Pin
Charles Carr17-Jan-09 10:24
Charles Carr17-Jan-09 10:24 
GeneralRe: GREAT solution Pin
mjmeans18-Jan-09 17:22
mjmeans18-Jan-09 17:22 
GeneralReally Great Solution [modified] Pin
George_Botros4-Dec-08 2:28
George_Botros4-Dec-08 2:28 
GeneralRe: Really Great Solution Pin
mjmeans4-Dec-08 8:26
mjmeans4-Dec-08 8:26 
Generalplease help me i cant know where is the error Pin
seman7117-Nov-08 2:07
seman7117-Nov-08 2:07 
GeneralRe: please help me i cant know where is the error Pin
mjmeans19-Nov-08 20:40
mjmeans19-Nov-08 20:40 
It is probably step 3 that you have not understood. You need to check to see the name of the connection string you used when you created your datasets. This is the name that your strongly types dataset and table adapter expect to use. And it is that name that must be used instead of connectionString1 or connectionString2 in the examples above.

This example ONLY works with strongly typed database access. It could be adapted to use other datasets, but that is project left to the reader to accomplish on their own.
GeneralYour code. Pin
Rogerio P16-Oct-08 12:56
Rogerio P16-Oct-08 12:56 
GeneralRe: Your code. Pin
mjmeans19-Nov-08 20:34
mjmeans19-Nov-08 20:34 
GeneralSettings not saving... Pin
JacquesVorster6-Aug-08 2:42
JacquesVorster6-Aug-08 2:42 
GeneralRe: Settings not saving... Pin
dudeddy14-May-09 2:05
dudeddy14-May-09 2:05 
GeneralHelp Pin
Bruno Ricardo Filipe das Neves8-Jul-08 8:56
Bruno Ricardo Filipe das Neves8-Jul-08 8:56 
GeneralRe: Help Pin
mjmeans8-Jul-08 10:53
mjmeans8-Jul-08 10:53 
QuestionCode variance Pin
dlcarp3-Jul-08 10:26
dlcarp3-Jul-08 10:26 
AnswerRe: Code variance Pin
mjmeans3-Jul-08 20:40
mjmeans3-Jul-08 20:40 
GeneralRe: Code variance Pin
dlcarp4-Jul-08 8:04
dlcarp4-Jul-08 8:04 
GeneralProblem Pin
crosurfer18-Jun-08 2:40
crosurfer18-Jun-08 2:40 
GeneralRe: Problem Pin
mjmeans18-Jun-08 9:08
mjmeans18-Jun-08 9:08 
GeneralRe: Problem [modified] Pin
crosurfer18-Jun-08 22:31
crosurfer18-Jun-08 22:31 
GeneralRemarkable Pin
pgraves9-Apr-08 2:31
pgraves9-Apr-08 2:31 
GeneralRe: Remarkable Pin
mjmeans9-Apr-08 15:37
mjmeans9-Apr-08 15:37 
GeneralPerfect ! Right out of the box. Pin
David Mujica5-Apr-08 5:40
David Mujica5-Apr-08 5:40 
GeneralThx (and variation) Pin
Mr.PoorEnglish8-Jan-08 5:06
Mr.PoorEnglish8-Jan-08 5:06 
GeneralRe: Thx (and variation) Pin
mjmeans8-Jan-08 6:20
mjmeans8-Jan-08 6:20 

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.