Saturday, May 31, 2008

Using an XML file for your ASP.NET settings


Step 1: Setup

To begin, I would create an XML file in the App_Data directory of your application. For this example, I will call the file Settings.xml. If you're using Visual Studio just right click the App_Data folder and Add a new item. The file will be pre-filled with the standard xml encoding:

<?xml version="1.0" encoding="utf-8" ?>

You should then add a root element to the XML file. I chose the root element to be <settings></settings>. Within those tags, all of your settings will be listed out as child elements. So far the file looks like this:

<?xml version="1.0" encoding="utf-8" ?>

Save the file to the App_Data folder.

Step 2: Create the Settings.cs class

Next, create a Settings class in your App_Code folder (or name it whatever you like). This class will be responsible for retrieving and updating the data in the Settings.xml file. Set the class to static so that it is only loaded once for the application.

Step 3: Define the setting elements and properties

You should now begin entering the settings you'll be using for the application. In the Settings.xml file, create an element for each of the settings you will need for your program and pre-populate them with defaults if you like.

Tip: If your setting contains any markup or unsafe characters, surround the settings in the <![CDATA[ your_setting_value_here ]]> tag to avoid xml errors.

I've added some example setting elements to my Settings.xml file below:

<?xml version="1.0" encoding="utf-8"?>

Next, for each of the settings you added to the Settings.xml file, create a property for it in the Settings.cs class. I'm assuming >= .NET 2.0 for the code here.

   1: public static class Settings
   2: {
   3:      /// <summary>
   4:     /// The maximum file size in KB for uploaded images. [Default: 1000KB]
   5:     /// </summary>
   6:     public static int MaxImageUploadSizeKB { get; set; }
   8:     /// <summary>
   9:     /// The whole number integer width of the image thumbnails [Default:100]
  10:     /// </summary>
  11:     public static int ThumbnailWidth { get; set; }
  13:     /// <summary>
  14:     /// The whole number integer height of the image thumbnails [Default:90]
  15:     /// </summary>
  16:     public static int ThumbnailHeight { get; set; }
  18:     /// <summary>
  19:     /// The directory to upload and read post images from/to [Default: ~/images/postImages/]
  20:     /// </summary>
  21:     public static string PostImageDirectory { get; set; }
  23:     /// <summary>
  24:     /// The number of minutes before a checkout session expires. [Default: 20]
  25:     /// </summary>
  26:     public static int SessionExpiresMinutes { get; set; }
  27: }

Step 4: Read the XML file into the properties

I'm sure I will catch some heat for using a DataSet to read the XML file as it seems to go against the whole point of using an XML file in the first place, but I like the simplicity and readability of the code it produces...Plus it's dead easy. The following function will assign the properties in the Settings class to the values in the XML file:

   1: /// <summary>
   2:     /// Load the settings from Settings.xml
   3:     /// </summary>
   4:     public static void LoadSettings()
   5:     {
   6:         DataSet ds = new DataSet();
   7:         ds.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/Settings.xml"));
   8:         if (ds != null && ds.Tables[0].Rows.Count > 0)
   9:         {
  10:             DataRow dr = ds.Tables[0].Rows[0];
  11:             MaxImageUploadSizeKB = Int32.Parse(dr["MaxImageUploadSizeKB"].ToString() ?? "1000");
  12:             ThumbnailWidth = Int32.Parse(dr["ThumbnailWidth"].ToString() ?? "100");
  13:             ThumbnailHeight = Int32.Parse(dr["ThumbnailHeight"].ToString() ?? "90");
  14:             PostImageDirectory = dr["UploadedImageDirectory"].ToString() ?? "~/images/postImages/";
  15:             SessionExpiresMinutes = Int32.Parse(dr["SessionExpiresMinutes"].ToString() ?? "20");
  16:         }
  17:     }

Note that the ?? operator will use the value following the ?? if the expression before it is null. This allows you to hard code defaults if you desire instead of having to do so in the XML file.

Now that you have the properties filled with data from the XML file, you can use them in your application just by referencing Settings.ThumbnailWidth for example.


No comments:

Post a Comment