Saturday, October 22, 2011

Managing your application settings in .net programs

Lets say you are writing code for your data layer. Ideally you'd be creating all the types this layer has to deal with, and most importantly, how these types get instantiated with data from your database. Hence there is always a connection string involved. But have you noticed where the connection string is stored?

For n-tier applications we mostly build the data layer as a dll (or a class library project), and finally add it to the presentation tier (just saying). However while you were doing development you would have used the dataset designer (or any similar designer) which allows you to manage your connection string for you. Our connection string, if you are using dataset designers, quietly becomes an application setting. But all of this is probably stored temporarily in your class project's app.config.

When the dll is added to another project, say a asp.net application, the dll will actually look for its configuration in the asp.net application's web.config. But its not there? One thing to note: simply adding the dll, VS doesn't copy its settings and merge it with the target application's config.

A strange fact to make note of again: the dll may not have its corresponding configuration. However this doesn't mean the application settings are completely absent. When we build the dll, the configuration at that instant, is actually written into the dll. Hence if we are trying to get the value of the connection string, we might get the string which belonged to the test db server. But anyhow, in production, we'd still want to change the setting value at some point or another.

This is quite possible in the target application config file again. In the sample solution I have shared below I have created a class library project which has an application setting. I have created a simple class which reads the application setting and returns this. I have directly outputted this value in ConsoleProjectA. You'll find that the display has the same string - this was the string we have set while making the class library project. In the 2nd console application project, the same code produces a different value. If you study the app.config of this project you'll understand how to change the application settings of the dll.

The zip file which has the sample solution which demonstrates this concept can be accessed here.



Post a Comment