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.

(303) Comments

Blog Message http://bookmarks.webhubllc.com/story.php?title=kitchen-renovation#discuss

Thanks-a-mundo for the blog post.Much thanks again. Keep writing.


Blog Message http://seatoskykiteboarding.com/

Really appreciate you sharing this article.Really looking forward to read more. Cool.


Blog Message http://merinteg.com/blog/view/81460/precisely-how-silage-is-produced-and-stored

Really informative blog article.Really looking forward to read more. Really Cool.


Blog Message http://kraftpaket.ru/bitrix/rk.php?goto=http://phillipwainwright.blogspot.com

uncertainty very quickly it will be famous, due to its feature contents.


Blog Message https://recordtile40.blogfa.cc/2018/08/13/exactly-why-you-need-the-help-of-a-taobao-agent/

I really liked your article.Much thanks again. Awesome.


Blog Message http://adsposting.cf/story.php?title=how-to-download-video-in-instagram#discuss

Way cool! Some very valid points! I appreciate you writing this article plus the rest of the website is also very good.


Blog Message http://www.vibet25.com/board_ONVM01/745463

in the daylight, as i enjoy to find out more and more.


Blog Message http://0233.1go.co.kr/link.php?url=http://franciscostubbs.blogspot.com

Intriguing post reminds Yeah bookmaking this


Blog Message https://www.townplanner.com/directorypreview/business-to-business/docpath-corp/49995/

so when I have time I will be back to read more,


Blog Message http://www.pickmeweb.com/info/ulthera-220401/

I simply couldn at depart your web site prior to suggesting that I really enjoyed the


Blog Message https://www.digitalcurrencycouncil.com/members/cafellama3/activity/726549/

Really interesting info! Perfect exactly what I was trying to find!


Blog Message https://www.facebook.com/mabel.marcinko.9/posts/234066837446565

I value the article.Really looking forward to read more. Will read on


Blog Message http://swimlyric1.bravesites.com/entries/general/one-should-be-careful-when-taking-tadalista-60-mg-since-it-has-a-strong-drug-interaction-with-other-medications

Im obliged for the blog post. Really Great.


Blog Message https://www.digitalcurrencycouncil.com/members/cinemaauthor52/activity/726310/

ohenk you foo ohw oipt. Io hwkpwt mw e koo.


Blog Message http://www.westernalu.com/plus/guestbook.php

very couple of internet sites that come about to become comprehensive beneath, from our point of view are undoubtedly very well really worth checking out

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