Click here to Skip to main content
15,888,113 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 282.4K   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

 
GeneralRe: Translate in C#... Pin
mjmeans20-Sep-07 7:25
mjmeans20-Sep-07 7:25 
GeneralThanks a lot Pin
ismailkirkan12-Sep-07 5:22
ismailkirkan12-Sep-07 5:22 
GeneralWhy just don't use app.config file Pin
ivan.bolcina6-Aug-07 21:53
ivan.bolcina6-Aug-07 21:53 
GeneralRe: Why just don't use app.config file Pin
mjmeans7-Aug-07 15:38
mjmeans7-Aug-07 15:38 
GeneralRe: Why just don't use app.config file Pin
ivan.bolcina7-Aug-07 20:32
ivan.bolcina7-Aug-07 20:32 
QuestionRe: Why just don't use app.config file Pin
PhilK_Oregon8-Oct-07 12:54
PhilK_Oregon8-Oct-07 12:54 
QuestionHow do I edit an existing connection String? Pin
fluffeishere31-Jul-07 13:47
fluffeishere31-Jul-07 13:47 
AnswerRe: How do I edit an existing connection String? Pin
mjmeans1-Aug-07 11:39
mjmeans1-Aug-07 11:39 
I am not sure what you are asking for. If you need to change the connection string on a production machine that is already installed and you are unable to add this class to your project and distribute an update, then this calss will not help you. If you can distribute an update to your client with the above class then 1) add a new user override string as shown above so that the class can use it to override the connection string you setup during development; 2) add a dialog to allow your user to change the connection string; 3) remember to use the SetUserOverride() function to save the user setting or the connection string will not be read by your strongly typed datasets or table adapters; 4) remember to set the project properties to save setting on exit or the change will not be persisted.

Also, table adapters get their connection string information when they are first used to get or fill a datasest, rather than when the New function is called. So if you do not want to limit your user to setting up the connection string before any tables are opened, then you will need to re-initialize your table adapters if the user changes the connection string (i.e. 'MyTableAdapter1 = New MyTableAdapter').

I am working on a connection properties dialog that works like VS 2005 connection properties but it is not ready to post. It only works for SQL Native Client databases and only with integrated security. Work is killing me right now so I dont know when I will be able to post that, so for the time being you are on your own as to how to ask the user for the proper connection string if you want that under user control.

If the production connection string needs to be hard coded, but different that the development connection string, then 1) add a registry setting into your installer; 2) in your form_load event, read the registry setting and call SetUserOverride. Loading it in the form_load event handler should guarantee that the table adapters have not yet tried to get or fill a dataset.

Hopefully your scenario is one of those I mentioned here. If I have misunderstood what you are trying to do, please try to restate it or give me some more details about your specific problem.

GeneralRe: How do I edit an existing connection String? Pin
fluffeishere1-Aug-07 11:50
fluffeishere1-Aug-07 11:50 
GeneralRe: How do I edit an existing connection String? Pin
mjmeans3-Aug-07 14:12
mjmeans3-Aug-07 14:12 
GeneralRe: How do I edit an existing connection String? - Solved Pin
fluffeishere6-Aug-07 11:38
fluffeishere6-Aug-07 11:38 
AnswerIMPORTANT Pin
mjmeans1-Aug-07 11:46
mjmeans1-Aug-07 11:46 
GeneralCorrection Pin
mjmeans26-Jul-07 15:31
mjmeans26-Jul-07 15:31 
GeneralThank you... Pin
Larry Sevilla25-Jul-07 4:12
Larry Sevilla25-Jul-07 4:12 
GeneralRe: Thank you... Pin
mjmeans25-Jul-07 9:19
mjmeans25-Jul-07 9:19 
QuestionRe: Thank you... Pin
dondon9818-Oct-07 6:30
dondon9818-Oct-07 6:30 
AnswerRe: Thank you... Pin
Larry Sevilla10-Nov-07 2:19
Larry Sevilla10-Nov-07 2:19 
AnswerRe: Thank you... Pin
Larry Sevilla10-Nov-07 2:45
Larry Sevilla10-Nov-07 2:45 
Generalthanks Larry Pin
dondon9810-Nov-07 7:43
dondon9810-Nov-07 7:43 
QuestionWhere do you declare the connectionOverrides() array? Pin
sohst17-Jul-07 10:48
sohst17-Jul-07 10:48 
AnswerRe: Where do you declare the connectionOverrides() array? Pin
mjmeans17-Jul-07 13:49
mjmeans17-Jul-07 13:49 
QuestionRe: Save Settings on Shutdown does not work on tier application layer Pin
Member 80095228-Jan-10 10:41
Member 80095228-Jan-10 10:41 
AnswerRe: Save Settings on Shutdown does not work on tier application layer Pin
mjmeans28-Jan-10 16:12
mjmeans28-Jan-10 16:12 
Generalproblems from Stephen King Pin
Sean Ewington17-Jul-07 9:26
staffSean Ewington17-Jul-07 9:26 
GeneralRe: problems from Stephen King Pin
mjmeans17-Jul-07 13:53
mjmeans17-Jul-07 13:53 

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.