Handling with Connection String at Run-Time in developing desktop applications


Almost every desktop application deals with some kind of external memory to save data for further use. The most part of them, use a database. On the other hand an Application needs connection string to connect to the database, for handling its memory. So, how to use connection string and how to manipulate with it, that’s the question which this post wants to answer.

If we want to change the connection string during the application run-time, it is not a simple task, because the connection string is placed in to an application scope that is read only.

The reason why we need to change the connection string is the different settings and environment between users, as well as different environment between developer and end-user. So when we are planning application deployment we must have that in mind, and  provide the implementation custom modification of the connection string.

clip_image002

If we look files of an Application (for example on the picture above) we can see two exe file, and two corresponding configuration files. This is the .NET rule, that every exe file may have only one configuration file.

The structure of configuration file

clip_image004

The picture above shows content of the configuration file and the connection string data. .NET Application can access this data with the API placed in to System.Configuration namespace, by using specific XML schema developed by Microsoft for that purpose.

To access NorthwindConncetionString from the configuration file we can achieve that with the following code:

//Read connection string from configuration file
var connStringFromConfig = System.Configuration.ConfigurationManager.
ConnectionStrings["ConnStringDemo1.Properties.Settings.NorthwindConnectionString"];

If we want to change connection string, exception will throw with the following message:

clip_image005

So the question is how to change connection string anyway?

To change connection string we need to open configuration file with XML API functions, find the connection string and change the data manually then save changes back to file then restart the application. This is in short how to do that, the following code do exactly what we said before:

private bool ChangeConnectionString(string connStringName, string newValue)
{
 try
 {
 //CreateXDocument and load configuration file
 XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

 //Find all connection strings
 var query1 = from p in doc.Descendants("connectionStrings").Descendants()
 select p;

 //Go throught each connection string elements find atribute specified by argument and replace its value with newVAlue
 foreach (var child in query1)
 {
 foreach (var atr in child.Attributes())
 {
 if (atr.Name.LocalName == "name" && atr.Value==connStringName)
 if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
 atr.NextAttribute.Value = newValue;
 }
 }

 doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

 return true;
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 return false;
 }
}

Change connection string for Entity Framework at run-time

As you already know the connection string for Entity Framework is little bit different than the connection string used by DataSet and Lin2SQL. In order to modify the Entity framework connection string the previous code must be modified. The following code modified the entity framework connection string.

private bool ChangeEFConnectionString(string connStringName, string newValue)
{
try
{
//CreateXDocument and load configuration file
XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

//Find all connection strings
var query1 = from p in doc.Descendants("connectionStrings").Descendants()
select p;

//Go through each connection string elements find atribute specified by argument and replace its value with newVAlue
foreach (var child in query1)
{
foreach (var atr in child.Attributes())
{
if (atr.Name.LocalName == "name" && atr.Value == connStringName)
if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
{
// Create the EF connection string from existing
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder(atr.NextAttribute.Value);
//
entityBuilder.ProviderConnectionString= newValue;
//back the modified connection string to the configuration file
atr.NextAttribute.Value = entityBuilder.ToString();
}
}
}

doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}

In the previous code we used the EntityConnectionStringBuilder which is very handy in this situation.

The source code for this post you can find on SkyDrive.

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 30/01/2011, in .NET, C#, CodeProject, WPF and tagged , , , , . Bookmark the permalink. 13 Comments.

  1. Hello my friend! I want to say that this post is awesome, nice written and come with almost all vital infos.
    I’d like to see extra posts like this .

  2. That’s 52 cases in a row that resulted in punishes.
    Unfortunately, the internet with all its wonderful qualities has made getting hacks very easy for
    even the most inexperience player a way to be the best.
    Manchester United midfielder Michael Carrick married Lisa Roughead on June 16, 2007, the same day as England team mates Steven Gerrard
    and Gary Neville married their partners.

  3. Quite a few treatment centers impose as per the time required each meeting.
    Exercise is important to improve nutrient absorption and can aid in combating stress.

    The best secrets to great health is in quality, not quantity.

  4. Greetings from Florida! I’m bored at work so I decided to browse your site on my iphone during lunch break.
    I enjoy the info you provide here and can’t wait to take a look when I get home.
    I’m amazed at how fast your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyways, amazing blog!

  5. Just re-cover the counter with a new laminate sheet.
    How do shooting is getting worse, falls into folds and the
    chin line to create an area of the jaw, jaw lines, marionette.
    Information You Should Know About Plastic Surgery is another excellent instance of this.

  6. I blog quite often and I genuinely thank you for your content.
    The article has truly peaked my interest. I am going to bookmark your blog and keep checking
    for new details about once a week. I opted in for your Feed
    as well.

  7. Renting a cabin in the woods is nice for the summer; buying one that you only
    use two weeks out of the year is not. David Beckham Talks Daughter Harper In WSJ Magazine November 2011.
    As said above, India is a preferred choice for outsourcing for many big firms abroad.

    Last year, militants attacked a UN guesthouse in Kabul and five foreign UN
    staff were killed. This includes polystyrene, tube steel, aluminum steel, and aluminum excursion. Online you get
    far more choice and can find the entire Sanderson Towels range online, something
    you cannot do on the High Street. The Garmin Forerunner 310XT is known as a
    great training aid for multi-sport practitioners. Currently, American might like to think that the menace of racial discrimination in their country is a long forgotten issue but the
    reality of the matter is racial discrimination in American cities
    is deeply rooted. The divorce can be a drawn out process for months to even years.
    Make sure that the pricing is strictly determined in the contract you sign so that you do not
    end up paying more than you have expected.

  8. naturally like your web site however you need to take a look at the spelling on quite a few of your posts.
    A number of them are rife with spelling problems and I to find it very troublesome to tell the truth however I
    will certainly come again again.

  9. Thanks for the auspicious writeup. It actually used
    to be a entertainment account it. Glance advanced to far delivered agreeable
    from you! However, how could we keep in touch?

  10. Employees can quickly obtain information and documents necessary,
    increase productivity and less time spent on business processes that would normally be entered manually.
    On the other hand, some may deal in nutraceuticals and cosmecuticals that fall in the category of
    specialty products. Every equity release scheme contains
    some advantages and disadvantages. If you are looking for new heating solutions,
    this buying guide may come handy. After architecture your dream home it’s important to booty the
    home allowance action that consists of the rebuilding costs, any affectionate of annexation or blow of the acreage etc’ In some of the allowance behavior the home allowance
    will be covered with the freeholder allowance but you accept to accomplish abiding about the coverage.

    Whether you are living in NYC for years or you have just moved in, you should always bear in mind
    that it’s not easy to secure a good job in this part of the world.
    The installation of this would require the assistance of professionals who bring
    the fiberglass shell to your home. And if people today had to
    wander miles to get to their desired destination, the creation of
    vehicles modified that and made life for
    individuals a little bit simple. Search online using your favourite property websites
    and have a chat with agents in person. So,if you are looking for reliable company offering solutions related to storage Melbourne, make extensive search over the internet.

  11. Hey there! I know this is kinda off topic but I was wondering which blog platform are you using for this site?
    I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at options
    for another platform. I would be awesome if you could point me in the direction of
    a good platform.
    online installment loans payday loans same day loans personal loan no credit check car title loans near
    me car title loans cheap loan bad credit auto loans guaranteed approval
    fast cash advance bad credit loans short term installment loans unsecured personal loan payday loans
    online personal loans for bad credit loans with bad credit bad
    credit personal loan money lenders for bad credit
    personal loans with bad credit cheap loan money lenders short
    term loans online car title loans loan max title loans personal loans
    for bad credit cash advance online payday loans online direct lenders personal loans with bad
    credit personal loans for people with bad credit hard money lenders
    installment loans for bad credit

  12. Fantastic. VS makes it so easy to setup a connection, but then not allowing a user to change the application setting was causing problems. Great workaround just rewriting the XML file.

  1. Pingback: Tweets that mention Handling with Connection String at Run-Time in developing the desktop applications | Bahrudin Hrnjica Blog -- Topsy.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s