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.

(130) Comments

Blog Message superstar 80s metal gris

Source: Rock City KicksAir Jordan 1 High OG Cyber MondayColor: Black/Black-WhiteStyle . superstar 80s metal gris http://la-crete-blanche.fr/superstar.asp?start=superstar-80s-metal-gris


Blog Message air max 90 size 7

Exotic yet refined, the classic running silhouette is featured in a premium rosey pink nubuck upper with the added touch of reptilian texture on the toe box. air max 90 size 7 http://lesjolieschoses.fr/lesjol.asp?alt=air-max-90-size-7


Blog Message air max one id

I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz answer back as I'm looking to design my own blog and would like to find out where u got this from. appreciate it air max one id http://nike.soldeweb.fr/Homme-Nike-Air-Max-1-2013-Blanc-Air-Max-One-Id-TO10230.html


Blog Message ballon de basket ball

Et le tee Prix rose shirt et le sweat Prix rose shirt ne sont pas les seules piegrave Blancheces agrave Blanche avoir droit de citeacute Blanche. ballon de basket ball http://bar-le-belem.com/temps.asp?id=ballon-de-basket-ball


Blog Message adidas nmd human race shop online

Today only and until supplies last, a select assortment of the follow shoes will be available for re. adidas nmd human race shop online http://cimorelli.com/acquisti.asp?p_id=adidas-nmd-human-race-shop-online-761789


Blog Message http://suba.me/

gDcD1N tarot tirada de cartas tarot tirada si o no


Blog Message http://forum.xoso.com/members/InerieBor667-1710789.html

Very good post.Really thank you! Much obliged.


Blog Message http://wiki2.gridology.ru/index.php?title=Locating_houses_for_rent_in_Orlando4119065

I cannot thank you enough for the post. Awesome.


Blog Message http://gamelab.info/story.php?id=112283

Im obliged for the blog.Really thank you! Will read on...


Blog Message http://www.lhasa.ru/board/tools.php?event=profile&pname=insendaRhyday691

A round of applause for your article post.Really thank you! Really Great.


Blog Message http://www.linkvaom88moinhat.com

Fantastic blog.Really looking forward to read more. Want more.


Blog Message http://www.3gassociation.ru/user/oyoarogpreyepa/

Thanks for the article post.Much thanks again. Will read on...


Blog Message http://www.kutsenko.ru/forum/index.php?showuser=5816106

Really enjoyed this article.Really thank you! Great.


Blog Message http://forum.xoso.com/members/esottpypeJaro104-1718623.html

I truly appreciate this blog post.Really looking forward to read more. Cool.


Blog Message http://www.bulksmmservice.com

I was suggested this blog by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are incredible! Thanks!

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