Question

How to change connectionstrings that are readonly in app.config

OK Here goes.

I have developped a VB.NET 2005 application which includes the fancy new "drag 'n drop" DataSet tool. When you first create a new dataset VB writes the connection string into the app.config file (visible through myproject.settings) as an "application scope" value. Application scope values are read only at runtime which is all well and good while I'm developping and my development server is available but completely useless when it comes to releasing the application to clients.

How can you change these connection strings at run time??

I've been searching now for ages to a proper answer to this question and a lot of time the answer is "you shouldn't do that....microsoft intended these to be fixed etc,etc" which is avoiding the issue. These values need to be changed!!!

One client has a need to set these values on a "per user" basis as the databases are replicted out to branch offices and the connectionstring needs to point at the replicated database.

The answer ould seem to be to change the values in the <programname>.exe.config file that is created in the user's directory and apply these in the settings.SettingsLoaded function but how exactly can this be done?

Simply assigning these values to a User Scope won't work as VB will continue to look at the application scope value for any updates effected on the dataset

I have seen Q_20954883 but it doesn't appear to address changing the connectionstring values (I accept that the app will need to be restarted the first time these are changed) as they don't appear to follow the normal XML structure rules.

Here's part of the app.config file...(values have been changed to protect the innocent)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=123456789" >
            <section name="System2.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=123456789" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <connectionStrings>
        <add name="Systemx.My.MySettings.ConnectionString"
            connectionString="Data Source=SQLSERVER;Initial Catalog=SystemXDB;Persist Security Info=True;User ID=xy;Password=abc"
            providerName="System.Data.SqlClient" />
        <add name="Systemx.My.MySettings.ConnectionString_OLE"
            connectionString="Provider=SQLOLEDB;Data Source=SQLSERVER;Initial Catalog=SystemXDB;Persist Security Info=True;User ID=xy;Password=abc"
            providerName="System.Data.OleDb" />
    </connectionStrings>
    <userSettings>
        <Systemx.My.MySettings>
            <setting name="Database" serializeAs="String">
                <value>SystemxDB</value>
            </setting>
         <setting name="RunBefore" serializeAs="String">
                <value>False</value>
            </setting>
        </System2.My.MySettings>
    </userSettings>
</configuration>


I'm assigning maximum points to this as there are a lot of other developers asking the same question on lots of other such sites but please do not say "you shouldn't be doing this!!!" - unless of course there is another way of getting VB to connect the dataset to a runtime connectionstring



Many thanks

Ian

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-08-19 at 11:18:32ID21960324
Tags

change

,

connectionstring

Topic

Microsoft Visual Basic.Net

Participating Experts
2
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Edit App.config
    Is it possible to edit an app.config file at runtime, I would like to use it as an editable file where a user can save his config parameters, do I have to create a separate config file for that. Appreciate the help vb
  2. Reading in app.config file
    i am using this app.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, C...
  3. Console App.Config C# 2.0
    I am using an app.config file in C# 2.0 console app. When I call the code below is comes up with null. string Computers = ConfigurationManager.AppSettings["EMEA"]; app.config file: <?xml version="1.0" encoding="utf-8" ?> <configuration&...
  4. VB.NET 2005-Using App.config to store connection …
    I am trying to use the APP.CONFIG file to store my VB.NET 2005 and an SQL Server 2005 DB connection string. After spending the past hour reading over 40 posts here, I'm now mixmashing 6 posts worth of information and still not getting it to work (and also creating a nice bow...
  5. configsource for user and application settings in vb.net 2…
    I currently use configsource in my app.config for storing the conn strings in an external file: <connectionStrings configSource="ConnectionStrings.config"/> in my app.config. In the external file, the format is as follows: <connectionStrings> connectio...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: SanclerPosted on 2006-08-19 at 16:59:37ID: 17349636

Ian

The only way I've found of doing this is via the .Connection.ConnectionString property of each TableAdapter.  

The Wizard embeds the ConnectionString as an Application Setting.  Although it can then be altered, I have only been able to do this at design time.  I have not been able to find any way of getting the Wizard to save it as a User Setting, or to retain amendments I made to the designer code to try to change it to a User Setting.  It's all done in the background - with Designer code and Private properties and methods - and fiddling with those either causes crashes or doesn't persist through a Build.  

But there is a "loophole".  Each TableAdapter's .Connection property is declared, in the DataSet.Designer code file (in the DataSetTableAdapters Namespace), as Friend, and with a Set as well as a Get.  So a sub on these lines for each TableAdapter (or one sub with a number of lines covering each of them)

    Private Sub changeConnection()
        myTableAdapter.Connection.ConnectionString = "<myUserConnectionString>"
    End Sub

called before any use is made of them allows the default, Application Setting value/s to be overwritten.  As the only access I can find is via the TableAdapter it means that the change (probably the same change) has to be made for each.  But I think this sort of "workaround" is essentially the line that you'll have to take.  Where and how you store and retrieve the value/s that you use for <myUserConnectionString> is up to you.

I'll be interested to hear if anyone else has found a more "pukka" approach.

Roger

 

by: RadicalSoftwareSolutionsPosted on 2006-08-19 at 23:12:37ID: 17350545

Thanks Roger

I have been using this approach up til now but I recently wasted time looking at why an app worked fine in development and not in live envionment only to find I'd forgotten to include the redirect on a newly added table.

I do not understand why Microsoft allows us to change so many parameters and system attributes in VB.NET but decided we're not to be trusted changing connnectionstrings!!

Ian

 

by: RadicalSoftwareSolutionsPosted on 2006-08-20 at 00:11:42ID: 17350669

Hi All

I have found a workaround to this but I'm still looking for a better solution (i.e changing the app.config files)

The solution I have used involves changing the settings.desogner.vb code which is created by the dataset design tool. The only reason my.settings.<connection string> are read only is that the designer only creates a "Get" property for them, its a 2 line change to add the "Set" property (since all we're doing is storing a string value there!). I then set the value to what I want in the settings.vb.settingsloaded function.

Ok it's not perfect as the settings.designer.vb gets re-written every time the designer is changed but you'll know if that's happened as the connectionstring will become readonly again and your code won't compile.

Obviously you'll have to do this for each connectionstring if you have more than one and don't forget to remove the "readonly" value from the property command

Ian

 

by: Ready1Posted on 2006-08-20 at 01:54:56ID: 17350793

i know this is in C# but this is what i use to save changes to the app.config during runtime:

what you can do is enable your application to read from a static variable which contains your connection string and allow you application to modify this variable during runtime and before your application exits save the value of the connection string back into the app.config for use next time round.

using System;
using System.Xml;  
using System.Configuration;
using System.Collections;
using System.Reflection;  
using System.Diagnostics ;

namespace BDS.Core.Config
{

      public enum ConfigFileType
      {
            WebConfig ,
            AppConfig
      }

      public class AppConfig : System.Configuration.AppSettingsReader
      {
            public string  docName = String.Empty;
            private  XmlNode node=null;

            private int _configType;
            public   int ConfigType
            {
                  get
                  {
                        return _configType;
                  }
                  set
                  {
                        _configType=value;
                  }
            }

            public bool SetValue(string key, string value)
            {
                  XmlDocument cfgDoc = new XmlDocument();
                  LoadConfigDoc(cfgDoc);
                  // retrieve the appSettings node
                  node =  cfgDoc.SelectSingleNode("//appSettings");
   
                  if( node == null )
                  {
                        throw new System.InvalidOperationException( "appSettings section not found");
                  }
   
                  try
                  {
                        // XPath select setting "add" element that contains this key    
                        XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +key +"']") ;
                        if (addElem!=null)
                        {
                              addElem.SetAttribute("value",value);    
                        }
                              // not found, so we need to add the element, key and value
                        else
                        {
                              XmlElement entry = cfgDoc.CreateElement("add");
                              entry.SetAttribute("key",key);
                              entry.SetAttribute("value",value);
                              node.AppendChild(entry);    
                        }
                        //save it
                        SaveConfigDoc(cfgDoc,docName);
                        return true;
                  }
                  catch
                  {
                        return false;
                  }
            }
 
            private void SaveConfigDoc(XmlDocument cfgDoc,string cfgDocPath)
            {
                  try
                  {    
                        XmlTextWriter writer = new XmlTextWriter( cfgDocPath , null );
                        writer.Formatting = Formatting.Indented;    
                        cfgDoc.WriteTo( writer );    
                        writer.Flush();
                        writer.Close();  
                        return;
                  }
                  catch
                  {
                        throw;
                  }
            }
 
            public bool RemoveElement ( string elementKey)
            {
                  try
                  {
                        XmlDocument cfgDoc = new XmlDocument();
                        LoadConfigDoc(cfgDoc);
                        // retrieve the appSettings node
                        node =  cfgDoc.SelectSingleNode("//appSettings");  
                        if( node == null )
                        {
                              throw new System.InvalidOperationException( "appSettings section not found");
                        }  
                        // XPath select setting "add" element that contains this key to remove  
                        node.RemoveChild( node.SelectSingleNode("//add[@key='" +elementKey +"']") );
   
                        SaveConfigDoc(cfgDoc,docName);
                        return true;
                  }
                  catch
                  {
                        return false;
                  }
            }


            private XmlDocument LoadConfigDoc( XmlDocument cfgDoc )
            {
                  // load the config file
                  if(  Convert.ToInt32(ConfigType)==Convert.ToInt32(ConfigFileType.AppConfig))
                  {
   
                        docName= ((Assembly.GetEntryAssembly()).GetName()).Name;
                        docName +=   ".exe.config";
                  }
                  else
                  {
                        docName=System.Web.HttpContext.Current.Server.MapPath("web.config");
                  }
                  cfgDoc.Load( docName );
                  return cfgDoc;
            }

      }
}

// this is how you use it

AppConfig ac = new AppConfig();
ac.ConfigType = (int)ConfigFileType.AppConfig;
appConfigDataSet = ac.GetAppSettings();
// set the value of the ConnString key
ac.SetValue("ConnString","this is my connection string");

REgards,
Ready1

 

by: RadicalSoftwareSolutionsPosted on 2006-08-20 at 04:35:00ID: 17351113

Hi

Thank you for post. I've run it through a c# to vb.net convertor but it appears to be missing the .getsettings function which is described in your "how to use" instructions.

Ian

 

by: Ready1Posted on 2006-08-20 at 20:32:56ID: 17353494

sorry mate, posted an old one: The method GetAppSettings is just returning the config file in a dataset which is not needed.

using System;
using System.Xml;  
using System.Configuration;
using System.Collections;
using System.Reflection;  
using System.Diagnostics ;
using System.Data;

namespace BDS.Core.Config
{

      public enum ConfigFileType
      {
            WebConfig ,
            AppConfig
      }

      public class AppConfig : System.Configuration.AppSettingsReader
      {
            public string  docName = String.Empty;
            private  XmlNode node=null;

            private int _configType;
            public   int ConfigType
            {
                  get
                  {
                        return _configType;
                  }
                  set
                  {
                        _configType=value;
                  }
            }

            public DataSet GetAppSettings()
            {
                  XmlDocument cfgDoc = new XmlDocument();
                  LoadConfigDoc(cfgDoc);

                  // store it in a dataset
                  DataSet ds = new DataSet();

                  // create the dataset
                  DataTable table = ds.Tables.Add();
                  table.Columns.Add("Key");
                  table.Columns.Add("Value");

                  // retrieve the appSettings node
                  node =  cfgDoc.SelectSingleNode("//appSettings");

                  foreach(XmlElement elem in node.ChildNodes)
                  {                        
                        string[] data = {elem.Attributes[0].Value,elem.Attributes[1].Value};
                        table.Rows.Add(data);
                  }

                  return ds;
            }

            public bool SetValue(string key, string value)
            {
                  XmlDocument cfgDoc = new XmlDocument();
                  LoadConfigDoc(cfgDoc);
                  // retrieve the appSettings node
                  node =  cfgDoc.SelectSingleNode("//appSettings");
   
                  if( node == null )
                  {
                        throw new System.InvalidOperationException( "appSettings section not found");
                  }
   
                  try
                  {
                        // XPath select setting "add" element that contains this key    
                        XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +key +"']") ;
                        if (addElem!=null)
                        {
                              addElem.SetAttribute("value",value);    
                        }
                              // not found, so we need to add the element, key and value
                        else
                        {
                              XmlElement entry = cfgDoc.CreateElement("add");
                              entry.SetAttribute("key",key);
                              entry.SetAttribute("value",value);
                              node.AppendChild(entry);    
                        }
                        //save it
                        SaveConfigDoc(cfgDoc,docName);
                        return true;
                  }
                  catch
                  {
                        return false;
                  }
            }

            public bool CreateValue(string key, string value)
            {
                  XmlDocument cfgDoc = new XmlDocument();
                  LoadConfigDoc(cfgDoc);
                  // retrieve the appSettings node
                  node =  cfgDoc.SelectSingleNode("//appSettings");
   
                  if( node == null )
                  {
                        throw new System.InvalidOperationException( "appSettings section not found");
                  }
   
                  try
                  {
                        // XPath select setting "add" element that contains this key    
                        XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +key +"']") ;
                        // not found, so we need to add the element, key and value
                        if (addElem==null)
                        {
                              XmlElement entry = cfgDoc.CreateElement("add");
                              entry.SetAttribute("key",key);
                              entry.SetAttribute("value",value);
                              node.AppendChild(entry);    
                        }
                        //save it
                        SaveConfigDoc(cfgDoc,docName);
                        return true;
                  }
                  catch
                  {
                        return false;
                  }
            }
 
            private void SaveConfigDoc(XmlDocument cfgDoc,string cfgDocPath)
            {
                  try
                  {    
                        XmlTextWriter writer = new XmlTextWriter( cfgDocPath , null );
                        writer.Formatting = Formatting.Indented;    
                        cfgDoc.WriteTo( writer );    
                        writer.Flush();
                        writer.Close();  
                        return;
                  }
                  catch
                  {
                        throw;
                  }
            }
 
            public bool RemoveElement ( string elementKey)
            {
                  try
                  {
                        XmlDocument cfgDoc = new XmlDocument();
                        LoadConfigDoc(cfgDoc);
                        // retrieve the appSettings node
                        node =  cfgDoc.SelectSingleNode("//appSettings");  
                        if( node == null )
                        {
                              throw new System.InvalidOperationException( "appSettings section not found");
                        }  
                        // XPath select setting "add" element that contains this key to remove  
                        node.RemoveChild( node.SelectSingleNode("//add[@key='" +elementKey +"']") );
   
                        SaveConfigDoc(cfgDoc,docName);
                        return true;
                  }
                  catch
                  {
                        return false;
                  }
            }


            private XmlDocument LoadConfigDoc( XmlDocument cfgDoc )
            {
                  // load the config file
                  if(  Convert.ToInt32(ConfigType)==Convert.ToInt32(ConfigFileType.AppConfig))
                  {
   
                        docName= ((Assembly.GetEntryAssembly()).GetName()).Name;
                        docName +=   ".exe.config";
                  }
                  else
                  {
                        docName=System.Web.HttpContext.Current.Server.MapPath("web.config");
                  }
                  cfgDoc.Load( docName );
                  return cfgDoc;
            }

      }
}

// this should work

AppConfig ac = new AppConfig();
ac.ConfigType = (int)ConfigFileType.AppConfig;

// create a new key
ac.CreateValue("MyKey","This is the value");
// set the value of the ConnString key
ac.SetValue("ConnString","this is my connection string");

 

by: RadicalSoftwareSolutionsPosted on 2006-08-21 at 01:05:02ID: 17354186

Many thanks - that works a treat. Hopefully it'll help out all the other web searchers looking for the answer to this problem

 

by: SanclerPosted on 2006-08-21 at 01:52:23ID: 17354367

Ready1

My thanks too.

Roger

 

by: Ready1Posted on 2006-08-21 at 04:19:10ID: 17354899

no probs mate glad to be of some assistance

Regards,
Ready1

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...