Andrej Tozon's blog

In the Attic


ConnectionString builders

Implementing database login functionality in your application usually requires you to build your database connection string in code. There are many ways to do that, and new classes in .NET Framework 2.0 (or better - ADO.NET) adds another one.

ADO.NET introduces a new class to build your database connection strings: DBConnectionStringBuilder, which serves as a base class for other, strongly typed builders, like SqlConnectionStringBuilder, OleDBConnectionStringBuilder,  and others - even OracleConnectionStringBuilder. While DBConnectionStringBuilder operates in in key/value mode - you can set any connection string property using string values:

.Add("Data Source", "ServerName") -

strongly typed builders help you build your connection string for your database using specific properties. For example, you could build the SqlServer connection string using the code like this:

string username = "Username";
string password = "Password";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "SqlServerName";
builder.InitialCatalog = "Database";
builder.UserID = username;
builder.Password = password;
builder.IntegratedSecurity = (user.Length + password.Length == 0);
builder.ApplicationName = Application.ProductName;
string connectionString = builder.ConnectionString;

It also works backwards - setting the ConnectionString property also initializes all other properties which you can later inspect for additional information. Using the following code, for example:

string connectionString = "Data Source=SqlServerName;Initial Catalog=Database;User Id=Username;Password=Password";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
bool allowAsync = builder.AsynchronousProcessing;
bool supportMARS = builder.MultipleActiveResultSets;

we find out that MARS is enabled by default, and asynchronous execution is turned off.

ConnectionString builders present a useful addition to the ADO.NET classes. Time to update some old code again…