Friday, June 27, 2008

VS 2005: Connection String Modifications in Class Libraries


An excellent practice in coding is to centralize and conseal data access code so that you do not have to reset configuration or in our case the "connection string" all over the places. You've probably experiencd that if you created a DataSet in the same project as all your main forms, connection string is in the Application's Settings file. And upon the form inialization, you can just change the connection string property then you are all set for the rest of the code.

What happens though if you placed the DataSet in a separate library. In this case you don't see the connection string any more in your Application's config file or Settings.

My Solution:

There are many different ways of doing this, from creating a factory class to overriding some config class objects that returns the correct (dynamically changed) connection string.

My solution is quite minimum compared to those but it does work and it does not require a lot of lines of code.

If you have created a Class Library on its own project then there is a namespace that is assigned to that project. If you create a DataSet in this project then it will create a local settings directory.

I usually have a database locally and so when I am developing I set my SQL hostname by default to (local) and when I go in production I just need to repoint the host name. The following code then will replace that with another hostname.

The property setting values are singletons (at least they seem to be) so if you run this once early on in your program execution, all the TableAdapters that use the connection string will take the new value from it.

namespace MyClassLib{
public class DBConnections
static public void SetDBHost(string hostName)
string cs =

cs = cs.Replace("(local)", hostName);
Properties.Settings.Default["ConnectionString"] = s; }

No comments: