I have a utility class, cleverly named Utility.cs, that is present in all my websites. I’ll present a sample as though this were the only method in the class (don’t want to give away too many secrets all at once, eh?). In my example, I exclude the constructor and remove some tabs to conserve valuable web page space and protect the environment.
Listing 4 – The utility method
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
namespace MyWebSite
{
public class Utility
{
public static string GetCustomConfigValue(string SectionName,string KeyName)
{
NameValueCollection myData = (NameValueCollection)
System.Configuration.ConfigurationSettings.
GetConfig(SectionName);
if (myData == null)
{
throw(new NullReferenceException("Section Name not found: " + SectionName));
}
string myValue = myData.Get(KeyName);
if (myValue == null)
{
throw(new NullReferenceException("Key Name not found: " + KeyName));
}
return myValue;
}
}
Note that we are raising exceptions here. It’s recommended, but you could just return a value like “Key name not found” so you present some value that indicates to you (when you are testing) that something didn’t work. Note the System namespaces imported at the top of the file. You need them.
Now, we go get those valuable little puppies of information!