News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
How to: Save Database Connection String to Application Configuration File using C#

Sometimes your application connects to database for querying, inserting and deleting data from tables. Embedding connection strings in your application's code can lead to security vulnerabilities and maintenance problems. Unencrypted connection strings compiled into an application's source code can be viewed using the MSIL Disassembler (Ildasm.exe) tool. Moreover, if the connection string ever changes, your application must be recompiled.

A Good rule of thumb is to store connection strings in an application configuration file. Application configuration files contain settings that are specific to a particular application. The following section shows the connection strings section in the application configuration file.

<connectionStrings>

  <add name="MyConnectionString"

       connectionString="Data Source=[TNSServiceName];Persist Security Info=True;User ID=[UserName];Password=[Password]"/>

</connectionStrings>

You need to save the connection string to configuration file at runtime and provide the user with a user interface to do so

Using the Code:

To make your application save the connection string to configuration file at runtime, follow these steps:

1.       Create a new windows application using Visual Studio 2005/2008/2010.

2.       Add a new Application Configuration file by right click on the project and click Add then New Item.

3.       Select Application Configuration File, name the configuration file and then click Add.

4.       Place the following section in the application configuration file you have just created.

<connectionStrings>

  <add name="MyConnectionString"

       connectionString="Data Source=[TNSServiceName];Persist Security Info=True;User ID=[UserName];Password=[Password]"/>

</connectionStrings>

5.       Rename Form1 to ConnectionForm.

6.       Add a TextBox to the ConnectionForm and rename it to DataSourceTextBox.

7.       Add another TextBox to the ConnectionForm and rename it to UserIdTextBox.

8.       Add another TextBox to the ConnectionForm and rename it to PasswordTextBox and set the PasswordChar property to * character.

9.       Import the System.Configuration, System.Reflection namespaces using the following statement:

using System.Configuration;

using System.Reflection;

10.   The System.Configuration namespace contains the types that provide the programming model for handling configuration data.

11.   The System.Reflection namespace contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata. These types also can be used to manipulate instances of loaded types, for example to hook up events or to invoke methods.

12.   Add an ErrorProvider component to the ConnectionForm and name it errorProvider. The Error Provider  provides a user interface for indication that a control on the form has an error associated with it.

13.    Add a Button to the ConnectionForm and name it SaveConnButton and double click the SaveConnButton in the designer to create the Click event handler in the code.

14.   Add the following code to the SaveConnButton Click Event Handler:

private void SaveConnButton_Click(object sender, EventArgs e)

{

    try

    {

        errorProvider.Clear();

 

        if (string.IsNullOrEmpty(DataSourceTextBox.Text))

        {

            errorProvider.SetError(DataSourceTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(UserIDTextBox.Text))

        {

            errorProvider.SetError(UserIDTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(PasswordTextBox.Text))

        {

            errorProvider.SetError(PasswordTextBox, "Required");

            return;

        }

 

        string connString = "Data Source={0};Persist Security Info=True;User ID={1};Password={2}";

        connString = string.Format(connString, DataSourceTextBox.Text, UserIDTextBox.Text, PasswordTextBox.Text);

 

        Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);

        ConnectionStringsSection connSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

        connSection.ConnectionStrings["MyConnectionString"].ConnectionString = connString;

        config.Save(ConfigurationSaveMode.Modified);

 

        MessageBox.Show("Successfully Completed", "Success",

            MessageBoxButtons.OK, MessageBoxIcon.Information);

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, ex.GetType().ToString(),

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

a.       First of all we clear any error in the errorProvider component by calling the Clear method of the errorProvider.

b.      We then check that the user enters a value in the DataSourceTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

c.       We then check that the user enters a value in the UserIdTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text..

d.      We then check that the user enters a value in the PasswordTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

e.      We create a string variable that holds the connection string that contains placeholders for data source, user Id and password.

f.        Replace the place holders of the connString instance using string.Format method.

g.       Create an instance of the Configuration class. This class represents a configuration file that is applicable to a particular computer, application, or resource.

h.      We use the ConfigurationManager Class that provides access to configuration files for client applications to get the application configuration file in the application folder using the Assembly class which represents an assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application.

i.         Create an instance of the ConnectionStringsSection class and name it connSection.  ConnectionStringsSection class provides programmatic access to the connection strings configuration-file section.

j.        We then set the MyConnectionString section in connectionStrings section to the connString string variable.

k.       MyConnectionString is the name of the connection string as written in the configuration file.

l.         We then call the Save method of the config object and pass to it one of ConfigurationSaveMode enumeration members. The ConfigurationSaveMode enumeration determines which properties are written out to a configuration file, We choose to save only modified sections only.

 

15.   Now compile and run the application.

16.   Enter any TNS Service Name in the DataSourceTextBox, user name in the UserIdTextBox and password in the PasswordTextBox and click on the SaveConnButton.

17.   You will be notified if the connection string has been saved to the configuration file or not.

 

Note:

You can Combine this article with the previous one and disable the SaveConnButton and enable it only if the user successfully tests establishing a connection to the database.

Now you have an application that can save database connection strings to application configuration file.

(333) Comments

Blog Message http://darustire.ru/bitrix/rk.php?goto=http://163.30.113.10/inteam98/userinfo.php?uid=457955

Major thanks for the post.Really thank you! Really Great.


Blog Message http://usdental.net/__media__/js/netsoltrademark.php?d=www.lasoracesira.it%2Findex.php%3Foption%3Dcom_k2%26view%3Ditemlist%26task%3Duser%26id%3D1507930&&fromurl=redirect.asp

Very nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I all be subscribing to your rss feed and I hope you write again soon!


Blog Message https://news.bitcoin.com/bitfinex-fee-bitmex-rejects-claims-trades-against-customers/

Im grateful for the blog post.Really thank you!


Blog Message http://wiki.sirrus.com.br/index.php?title=Consider_the_bobsweep_pro_review_at_this_time_using_the_web9067313

Really enjoyed this article post.Really looking forward to read more. Awesome.


Blog Message https://skirtcoach21.tumblr.com/post/179926375208/advantages-of-tungsten-bracelet-for-robust-and

I view something really special in this internet site.


Blog Message http://hhcn.cbtvnetwork.com/hhcncommunity/blog/view/339130/advantages-of-glass-fencing

This is really fascinating, You are an overly skilled blogger. Ive joined your rss feed and stay up for looking for more of the good post. Also, Ive shared your website in my social networks!


Blog Message https://www.isaacsandisaacs.com/truck-accident-lawyer

I think this is a real great blog article.Really looking forward to read more. Fantastic.


Blog Message https://ask.fm/fibercolt7

There is certainly a great deal to find out about this topic. I love all of the points you made.


Blog Message http://www.salontakeout.com/__media__/js/netsoltrademark.php?d=ayamakram.com%2Findex.php%3Fqa%3Duser%26qa_1%3Dcheyennemackson

Perfectly composed subject material , thankyou for selective information.


Blog Message http://nottsgroups.com/story/300912/#discuss

Way cool! Some very valid points! I appreciate


Blog Message http://harborrose9.jigsy.com/entries/general/A-Spotlight-On-Uncomplicated--Ceiling--Fan--Programs

This website was how do you say it? Relevant!! Finally I have found something that helped me. Appreciate it!


Blog Message http://swampinsect4.thesupersuper.com/post/the-significance-of-business-tax-accounting

Thank you for your blog post.Really thank you! Awesome.


Blog Message https://www.youtube.com/watch?v=3ogLyeWZEV4

this content Someone left me a comment on my blogger. I have clicked to publish the comment. Now I wish to delete this comment. How do I do that?..


Blog Message http://rkr.in.ua/user/outfiffgalf183/

You are my inspiration , I have few blogs and often run out from to brand.


Blog Message http://adep.kg/user/quetriecurath193/

Just wanna state that this is handy , Thanks for taking your time to write this.

First Previous 1 2 3 4 5 6 7 8 9 10  ... Next Last 
Rating
Name
Email
Comment