Configuration with custom connection strings

ASP.NET Core has a very flexible, very extensive configuration system. It's a long read, but when working across projects where different styles may be favored, it's handy to know what options you have at your disposal.

One things that is clear is that like many flexible systems, generic strings abound. If you look at the bottom of the Conventions section, you'll see all values starts as strings, even if you eventually have ways to bind them to other types.

But because strings are very easy to use and copy/paste around, you'll see things like connection strings abound. These are really just short strings with a very old convention, used way back for data sources with OLE DB, ODBC and even before.

Anyway, my post for today is to remind people that the .NET Framework has a DbConnectionStringBuilder class that does all the work to turn strings into key/value pairs, properly considering escaping, and to allow you a way to also manipulate them and write them back to a string.

Using this is really handy to read out string values and make sense of a bunch of settings.

For example, when running this program (remember try.dot.net, which I'll integrate at some point I suppose) ...

using System;
using System.Data.Common;

public class Program
{
  public static void Main()
  {
    DbConnectionStringBuilder csb = new DbConnectionStringBuilder();
    csb.ConnectionString = "Path=C:\\foo;Backup=true;Read Only=true;";
    foreach (string k in csb.Keys) Console.WriteLine($"key='{k}' value={csb[k]}");
  }
}

You'll get this output:

key='path' value=C:\foo
key='backup' value=true
key='read only' value=true

If you need to encapsulate these things with a bit more strong typing, you can always the connection string builder and expose properties. For a fancy one with lots of properties and enumeration, see for example SqlConnectionStringBuilder.

Enjoy!

Tags:  designdotnet

Home