web.config key values, usage and access web.config key values


Problem:
There are scenarios where you need to build your application flexible at runtime. ASP.NET provides a configuration system we can use in Sharepoint to do this task. Let us understand how best we can use it.


Solution:
The "appSettings" element of a web.config file is a place to store configurable items like connection strings, server names, file paths, and other miscellaneous settings that are needed by an application to perform work. The items inside appSettings called Keys are items that need to change depending upon the environment, for instance, an appsetting key can store a database connection string,which changes as you move your application from a testing or staging server into production.

The Web.config file, as aforementioned, is an XML-formatted file. At the root level is the "configuration" tag. Inside this tag you can add a number of other tags, the most common and useful one being the system.web tag, where you will specify most of the Web site configuration parameters. However, to specify application-wide settings you use the "appSettings" tag. Inside this tag you can specify zero to many settings by using the "add.." tag. For example, if we wanted to add a database connection string parameter we could have a Web.config file like so:
After setting up config values in web.config now the next step is how to access these values in your code. The latest code snippet to access web.config value is as below:
Please note that you need to add a reference to "System.Configuration" in your code behind file. See below the example in C#:
The advantage of using a web.config file to store such values is that as the code moves to different environments, one does not need to change these variables in the code each time. One can easily maintain a different web.config file for each environment with the relevant set of values.








Labels: