Saturday, March 8, 2008

Web.config's appSettings section to avoid hard coded memory variable

It's not a good programming practice to use hard coded memory variable which will end up a non scalable maintenance nightmare.

appSettings section in web.config is a key value pair as show below.

Once you have created the appSetting you can access the value from code.

SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
da = new SqlDataAdapter("sp_helpdb", cnn);
da.Fill(ds, "Cat");
listBox1.DataSource = ds.Tables["Cat"];
listBox1.DataTextField = "name";

AppSettings and WebSite Administration Tool

You need not manually edit the web.config file. There is a tool available form Asp .net 2.0 called Web Site Administration tool which can be used to edit the web.config file.

Go to WebSite menu and select Asp .Net Configuration.

Web Site Administration tool will appear. Select Application Configuration.

Select Create Application Settings.

In the page you can specify the Name and value by typing in the textboxes and the values will be updated in web.config file.

Windows Forms and App.Config file

Similar option is there for Windows Forms and WPF. Except that the file is App.Config instead of Web.Conif and you have set a reference to System.Configuration by selecting Project, Add Reference menu option.

Happy Programming