Jeff's SQL Server Blog

Random Thoughts & Cartesian Products with Microsoft SQL Server
posts - 157, comments - 2686, trackbacks - 64

My Links

Advertisement

News

Welcome to my weblog. My name is Jeff Smith, I am software developer in Boston, MA and I was recently named a 2009 SQL Server MVP. Check in frequently for tips, tricks, commentary and ideas on SQL Server and .NET programming.


Subscribe





Archives

Post Categories

Programming

Sports

SQL

ASP.NET 1.1 -- Appsettings in Web.config

It's great to be able to put settings in the Web.Config file for my ASP.NET projects.  The problem for me, though, is that when I use

System.Configuration.ConfigurationSettings.AppSettings(name)

to return a setting that doesn't exist in the file, an empty string ("") is returned, when ideally I would like an exception to let me know that something is missing or mispelled in my config file (or application code).  A lot of times, that empty string will cause errors or other odd behavior that can be tough to detect.  This happened to me the other day where I spent hours trying to figure out why the heck something simple wasn't working, when I realized it was because one of the setting names was spelled wrong in the config file.  Also, string values are always returned which often need to be cast to the proper datatype.  

For these reasons, I have found it very handy to instead access your web.config AppSettings through a couple of functions, such as these:

    Public Function GetSetting(ByVal Name As String) As String
        Dim s As String = System.Configuration.ConfigurationSettings.AppSettings(Name)

        If s = "" Then
            Throw New Exception("Error: App Setting not found: " & Name)
        Else
            Return s
        End If
    End Function

    Public Function GetSettingInt(ByVal Name As String) As Integer
        Return Convert.ToInt32(Setting(name))
    End Function

This way, at runtime you get an exception when you ask for a setting that doesn't exist in your file.  In addition, multiple versions of this function allow you to avoid the need to cast those string values to other datatypes.

For this to work, of course, you must be sure that you don't need to store empty strings in your Web.Config file.  If you do, you might come up with a standard such as "N/A" or something, and then have this function convert that value to an empty string when returning the result.

Run-time checking is good, but of course compile-time checking is even better.   Another trick you can do is to define an enumeration to represent each of your settings:

Public Enum AppSettingInt
  MinFileSize
  MaxFileSize
  DefaultAmount
End Enum

Public Enum AppSettingStr
  SMTPServer
  DBConnect
  EmailAddress
End Enum

You can then make your previous Setting() functions private, and then define public versions of your GetSetting() functions like this:

    Public Function GetSetting(ByVal Name As AppSettingStr) As String
        Return GetSetting([Enum].GetName(GetType(AppSettingStr), Name))
    End Function

    Public Function GetSettingInt(ByVal Name As AppSettingInt) As Integer
        Return SettingInt([Enum].GetName(GetType(AppSettingInt), Name ))
    End Function

The GetName() method of the [Enum] class returns a string representing the name of the enumerated value passed in.

Now, you have compile-time checking of your web.config settings.   Previously, you would write:

debug.WriteLine(GetSetting("SMTPServer"))

which would not return an exception until the code is executed if that key doesn't exist.  But with the enumerations, you would write:

debug.WriteLine(GetSetting(SMTPServer))

which returns a compile-time error if that setting doesn't exist.  Note the lack of quotations. In addition, you get the benefit of Intellisense when writing your code, which is useful for typo-prone guys like myself.

There is a bit more maintenance needed for this approach -- you would have to add values to your enumerations whenever you add them in your Web.Config file.  But I feel it is well worth it.

Finally, you can also do things like storing different settings depending on the HostName of the web application as well, and use this global function to determine which value to pull from the web config. For example, you might have 3 different database connection strings for your different environments (dev, staging, prod) and you could do something like this:

    <add key="dbconn-productiondomain.com" value=" ...."/>
    <add key="dbconn-10.10.1.39" value=".." />
    <add key="dbconn-localhost" value="..." />

where "productiondomain.com" is your production host name, "10.10.1.39" is your staging server's IP, and "localhost" is of course your local development box.  By accessing settings through helper functions, you can create a function that pulls the right setting for "dbconn" depending on the host that is running the web application and you only have to maintain 1 web.config file and not worry about the differences between your different environments.

Well, those are just some ideas and some of the things I have found useful in ASP.NET 1.1.  I have just begun to really explore and work with ASP.NET 2.0, so I am not fully aware of all the configuration differences and possibilities there, but I suspect that lots of this may apply in that environment as well.

Any other tricks or advice for working with configuration settings?  Or, have I re-invented the wheel here?

see also:

Print | posted on Wednesday, March 28, 2007 12:09 PM | Filed Under [ .NET (C# / VB) ASP.NET Code Library - ASP.NET ]

Feedback

Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

what about adding default value....
publc string GetSetting(string key)
{
return GetSetting(key, String.Empty)
}
publc string GetSetting(string key, string defaultValue)
{
..........
}

Then, when you are ready to move to 2.0 you can do generics...
public T GetSetting<T>(string key, T defaultValue)
{
.....
}
4/4/2007 3:40 PM | Jonathan
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

Dear Sir,
I am pursuing Msc.IT(finnal year) in india (Madras University). I have one doubt in asp.net how to connect database connection string in web.config file . I kindly request you to provide me any soluction for my problem


Your's faithfully,

G.BalaKishna
4/27/2007 6:24 PM | balakrishna
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

Good Atricle
9/17/2007 6:28 AM | sandep
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

There's actually a simpier way - use ClassFromConfig tool to generate your strongly typed config class wrapper from your Web.config (or App.config). So you can access your app settings like Config.MinFileSize, Config.MaxFileSize, Config.SMTPServer, EmailAddress, etc.

Check it out: ClassFromConfig
10/20/2007 4:46 AM | Mikhail Diatchenko
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

Hello all,

i am new in asp.net shall i get some help regarding database connectivity with two feilds so that i add, delete, modify , save.

Ganesh.S

10/27/2008 3:00 AM | GANESH
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

Throwing an exception if the setting you are looking for does not exist is a horrible approach to solving your problem. Exceptions should only be used for exceptional circumstances that are largely beyond your control. In this case, you control the source code that is accessing the settings so you do not need to throw an exception. Instead, you could do something like this:

Public Function GetSetting(ByVal name As String, ByRef value As String) As Boolean

Dim result As Boolean = False

value = System.Configuration.ConfigurationSettings.AppSettings(name)
result = (value IsNot Nothing)

Return result

End Function

Note that System.Configuration.ConfigurationSettings.AppSettings(name) returns a null reference (not an empty string) if the specified setting does not exist. On the other hand, it does return an empty string if the setting exists but contains a blank value.
2/25/2009 2:38 PM | April
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

April -- you are missing the point. I am not suggesting that we use exceptions to check if an appsetting exists or not! I am suggesting throwing an Exception to prevent your application from blissfully ignoring a mispelt config entry, or invalid config file, that is missing required settings.

I think we can agree that having your app try to reference an application setting that does not exist is not a good thing. (unless, of course, the setting is optional) Now, ideally, at compile-time, this error or typo or issue would be caught. However, we cannot do it at compile-time, so the next best thing we can do is ensure that the missing app setting is not ignored by throwing an exception. These exceptions are not part of the normal program flow, they should not be placed in a TRY/CATCH block, they are designed to immediately terminate the application to let you know you have a missing app settings in your config file. Having a missing app setting is a very "exceptional" situation that should never occur and should be fixed.
2/25/2009 3:12 PM | Jeff S
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

This may help u....


in web.config

&amp;amp;lt;appSettings&amp;amp;gt;
&amp;amp;lt;add key=&amp;amp;quot;YourString&amp;amp;quot; value=&amp;amp;quot;server=YOUR_SERVER_NAME;database=YOUR_DATABASE_NAME;uid=USERNAME;pwd=PASSWORD;&amp;amp;quot;/&amp;amp;gt;
&amp;amp;lt;/appSettings&amp;amp;gt;

in cs file u can access it using



SqlConnection scnConn = new SqlConnection();

scnConn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings[&amp;amp;quot;YourString&amp;amp;quot;].toString();

or if u r using Connection String u can do it in this way

&amp;amp;lt;connectionStrings&amp;amp;gt;
&amp;amp;lt;add name=&amp;amp;quot;YourString&amp;amp;quot; connectionString=&amp;amp;quot;server=YOUR_SERVER_NAME;database=YOUR_DATABASE_NAME;uid=USERNAME;pwd=PASSWORD;&amp;amp;quot;/&amp;amp;gt;
&amp;amp;lt;/connectionStrings&amp;amp;gt;

n u can retrive this on c# page using

SqlConnection scnConn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings[&amp;amp;quot;YourString&amp;amp;quot;].ConnectionString;);





8/14/2009 4:37 AM | Rutvij
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

sorry i dont know what happen to previous post...it showing some different words....

so chk it out below 4 proper code


This may help u....


in web.config

<appSettings>
<add key="YourString" value = "server=YOUR_SERVER_NAME;database=YOUR_DATABASE_NAME;uid=USERNAME;pwd=PASSWORD;"
</appSettings>


in cs file u can access it using



SqlConnection scnConn = new SqlConnection();

scnConn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["YourString"].toString();



or if u r using Connection String u can do it in this way

<connectionStrings>
<add name="YourString" connectionString="server=YOUR_SERVER_NAME;database=YOUR_DATABASE_NAME;uid=USERNAME;pwd=PASSWORD;"/>
</connectionStrings>


n u can retrive this on c# page using

SqlConnection scnConn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["YourString"].ConnectionString;);





8/14/2009 4:44 AM | Rutvij
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

PLEASE HELP ME SET MY CUSTOMERROSMODE (OFF)
10/11/2009 5:13 PM | azeez jamiu oladejo
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

AND <configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration>
10/11/2009 5:17 PM | azeez jamiu oladejo
Gravatar

# re: ASP.NET 1.1 -- Appsettings in Web.config

Hello all,

i am new in asp.net shall i get some help regarding database connectivity with two feilds so that i add, delete, modify , save.
6/2/2010 2:46 AM | MIRA
Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET