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.

(256) Comments

Blog Message http://www.ligakita.org

It is laborious to search out knowledgeable folks on this matter, but you sound like you recognize what you are speaking about! Thanks


Blog Message http://heatherbenson.blogdon.net/more-information-on-the-flyttfirma-pris-is-here-7951851

Thanks so much for the blog article.Really thank you! Really Cool.


Blog Message http://tyresecraig.unblog.fr/2018/07/12/easy-way-to-use-the-cc-remains/

Most likely You Also Make These kind of Slip ups With the bag ?


Blog Message http://rexdeleon.blogkoo.com/genial-cialis-disponible-sur-internet-8684675

Real wonderful information can be found on weblog.


Blog Message http://celebwired.com/news/nyc-custom-glass-doors-storefront-door-and-window-installation-services-launched/0069124/

Muchos Gracias for your blog article. Awesome.


Blog Message http://www.seoinvancouver.com/

You are amazing! Thanks! Feel free to visit my web blog wordpress developer


Blog Message http://www.findervenue.com/london-event-space/

Way cool! Some extremely valid points! I appreciate you penning this post and the rest of the website is extremely good.


Blog Message http://www.seoinvancouver.com/

Usually I don at learn post on blogs, but I would like to say that this write-up very compelled me to take a look at and do it! Your writing style has been surprised me. Thank you, quite nice post.


Blog Message http://www.seoinvancouver.com/

very few sites that come about to become detailed below, from our point of view are undoubtedly nicely really worth checking out


Blog Message http://eukallos.edu.ba/

Muchos Gracias for your blog article.Much thanks again. Will read on


Blog Message http://www.vegas831.com/news

Looking forward to reading more. Great article post.Thanks Again. Cool.


Blog Message http://www.seoinvancouver.com/

when new comments are added- checkbox and from now on whenever a comment is added I get four


Blog Message http://markets.housingwire.com/housingwire/news/read/36082537

Wow, fantastic blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is fantastic, as well as the content!


Blog Message http://redshiftdaily.com/news/new-2018-school-uniform-fashion-trends-for-boys-and-girls/0067940/

This is really interesting, You are a very skilled blogger. I ave joined your feed and look forward to seeking more of your excellent post. Also, I ave shared your web site in my social networks!


Blog Message http://www.seoinvancouver.com/

Some truly great info, Gladiolus I detected this.

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