Welcome to Ultra Developers.

the company that developes your success

Read Blog


How to: Save Database Connection String to Application Configuration File using C#

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>
  1. Rename Form1 to ConnectionForm.
  2. Add a TextBox to the ConnectionForm and rename it to DataSourceTextBox.
  3. Add another TextBox to the ConnectionForm and rename it to UserIdTextBox.
  4. Add another TextBox to the ConnectionForm and rename it to PasswordTextBox and set the PasswordChar property to * character.
  5. Import the System.Configuration, System.Reflection namespaces using the following statement:
using System.Configuration;
using System.Reflection;
  1. The System.Configuration namespace contains the types that provide the programming model for handling configuration data.
  2. 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.
  3. 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.
  4. 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.
  5. 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);
    }
}
  1. In the above code:
    • First of all we clear any error in the errorProvider component by calling the Clear method of the errorProvider.
    • 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.
    • 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..
    • 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.
    • We create a string variable that holds the connection string that contains placeholders for data source, user Id and password.
    • Replace the place holders of the connString instance using string.Format method.
    • Create an instance of the Configuration class. This class represents a configuration file that is applicable to a particular computer, application, or resource.
    • 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.
    • Create an instance of the ConnectionStringsSection class and name it connSection. ConnectionStringsSection class provides programmatic access to the connection strings configuration-file section.
    • We then set the MyConnectionString section in connectionStrings section to the connString string variable.
    • MyConnectionString is the name of the connection string as written in the configuration file.
    • 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.
  2. Now compile and run the application.
  3. Enter any TNS Service Name in the DataSourceTextBox, user name in the UserIdTextBox and password in the PasswordTextBox and click on the SaveConnButton.
  4. 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.

Save Database Connection

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

Similar Posts