Friday, October 8, 2010

Using AdsConnectionStringBuilder

One of the classes included with the Advantage .NET Data Provider is the AdsConnectionStringBuilder. This class can be used to build connection strings or easily retrieve connection properties from a connection string. The AdsConnectionStringBuilder is a descendent of the DBConnectionStringBuilder class which is part of the .NET 2.0 framework, therefore you need to use the ADO.NET 2.0 version of the provider ( see July FAQs for more information ).

You may remember the example Advantage Configuration Forms I posted a couple of years ago. I was working with a new project and I decided to reuse one of these forms. As I read through the code I realized that I was storing each connection option in its own setting. In hindsight this seemed like the wrong approach, why not simply store the connection string itself. Not only does this make it unnecessary to parse the string myself, I just have to read it in and use it, it also makes the settings much clearer.

As it turns out the AdsConnectionStringBuilder is a perfect tool for doing this. It takes care of all the reading and writing of connection string options. See below for some simple examples.

// Loads the options
private void LoadConnectionOptions()
{
  AdsConnectionStringBuilder sbConn = 
    new AdsConnectionStringBuilder( Properties.Settings.Default.ConnString );

  txtDataPath.Text = sbConn.DataSource;
  txtUserName.Text = sbConn.UserID;
  txtPassword.Text = sbConn.Password;
  // Set other controls as needed
}

// Saves a connection string based on values in form controls
private void BuildConnectionString()
{
  AdsConnectionStringBuilder sbConn = new AdsConnectionStringBuilder();

  sbConn.DataSource = txtDataPath.Text;
  sbConn.UserID = txtUserName.Text;
  sbConn.Password = txtPassword.Text;
  // Gather other settings as needed

  Properties.Settings.Default.ConnString = sbConn.ConnectionString;
}

In this example I am storing the connection string as a regular application setting. You can also put connection strings in the connectionStrings section of the configuration file. However, I have found this more difficult to modify at run-time than the normal settings.

No comments: