Using an XML file for your ASP.NET settings

A very common requirement for web applications is that they be configurable in an easy way. A lot of times it doesn't make sense to use a database to store some simple settings for your web site, especially if the application doesn't require one in the first place. There are a ton of ways to accomplish this task, but it seems to me that XML is perfectly suited for this problem. I don't mean to presume that it is better than other solutions but in case it fits the bill for your project, here is once way it can be used.

In this post I'll demonstrate one simple way to use XML to retrieve, edit, and save settings for your ASP.NET application.

The Scenario

You're building an ASP.NET application in C# that needs to have some user configurable settings. You don't want to use a database to store these settings and you want the ability to edit and save the settings through a web page. The edit page should be created dynamically from the settings contained in the XML file so that the page will not have to be updated if a setting is added.

Limitations of this example

To begin, this is not a "killer" solution to settings management. You can find a much more capable approach to XML settings by viewing the source of BlogEngine.NET and its setting management system.

This example will not allow for a user to add settings on their own that will be automatically recognized by the code. If a new setting is to be added, it will need to have a property set up and defined in the Settings class as well as be added to the Settings.xml file.

This example will not cover the vast possibilities for sub-settings you can obtain using element attributes and many other XML features.

Mostly, this is just a demonstration of how to accomplish the simple goal of storing and retrieving settings in XML.

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" ?>
<settings>
</settings>

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"?>
<settings>
    <MaxImageUploadSizeKB>1000</MaxImageUploadSizeKB>
    <ThumbnailWidth>100</ThumbnailWidth>
    <ThumbnailHeight>90</ThumbnailHeight>
    <UploadedImageDirectory>~/images/postImages/</UploadedImageDirectory>
    <SessionExpiresMinutes>20</SessionExpiresMinutes>
</settings>

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.

public static class Settings
{
     /// <summary>
    /// The maximum file size in KB for uploaded images. [Default: 1000KB]
    /// </summary>
    public static int MaxImageUploadSizeKB { get; set; }

    /// <summary>
    /// The whole number integer width of the image thumbnails [Default:100]
    /// </summary>
    public static int ThumbnailWidth { get; set; }

    /// <summary>
    /// The whole number integer height of the image thumbnails [Default:90]
    /// </summary>
    public static int ThumbnailHeight { get; set; }

    /// <summary>
    /// The directory to upload and read post images from/to [Default: ~/images/postImages/]
    /// </summary>
    public static string PostImageDirectory { get; set; }

    /// <summary>
    /// The number of minutes before a checkout session expires. [Default: 20]
    /// </summary>
    public static int SessionExpiresMinutes { get; set; }
}

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:

    /// <summary>
    /// Load the settings from Settings.xml
    /// </summary>
    public static void LoadSettings()
    {
        DataSet ds = new DataSet();
        ds.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/Settings.xml"));
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataRow dr = ds.Tables[0].Rows[0];
            MaxImageUploadSizeKB = Int32.Parse(dr["MaxImageUploadSizeKB"].ToString() ?? "1000");
            ThumbnailWidth = Int32.Parse(dr["ThumbnailWidth"].ToString() ?? "100");
            ThumbnailHeight = Int32.Parse(dr["ThumbnailHeight"].ToString() ?? "90");
            PostImageDirectory = dr["UploadedImageDirectory"].ToString() ?? "~/images/postImages/";
            SessionExpiresMinutes = Int32.Parse(dr["SessionExpiresMinutes"].ToString() ?? "20");
        }
    }

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.

Step 5: Viewing / Editing the Settings file in a web page

To display the current settings in a way that will allow them to be editable, but also allow the page to work regardless of changes to the available settings, here is something you could do.

  1. Create a normal .aspx page for the purpose of editing the settings.
  2. Add a table to the page and set runat="server" and give it an ID.
  3. On the Page_load event, call a function to dynamically create the setting label along with a text box for changing the value.
  4. Provide a Save button that will write the changes back to the XML file.

The following function will accomplish the loading task (there are some css styles in this function that are not included here):

private void LoadSettings()
    {
        XmlDocument xDoc = new XmlDocument();
        try
        {
            xDoc.Load(Server.MapPath("~/App_Data/Settings.xml"));
        }
        catch { xDoc.LoadXml("<Settings></Settings>"); }

        int alt = 0;
        XmlNodeReader nodeReader = new XmlNodeReader(xDoc);
        while (nodeReader.Read())
        {
            if (nodeReader.NodeType == XmlNodeType.Element && nodeReader.Name != "settings")
            {
                HtmlTableRow tr = new HtmlTableRow();
                HtmlTableCell c1 = new HtmlTableCell();
                HtmlTableCell c2 = new HtmlTableCell();
                TextBox tb = new TextBox();

                c1.InnerHtml = "<strong>" + nodeReader.Name + "</strong>";
                if (alt % 2 == 0)
                {
                    c1.Attributes.Add("class", "postDetailsLabel");
                    c2.Attributes.Add("class", "postDetailsReview");
                }
                else
                {
                    c1.Attributes.Add("class", "postDetailsLabel");
                    c2.Attributes.Add("class", "postDetailsReview");
                }

                c1.Attributes.Add("style", "padding-right:20px;");

                tb.ID = nodeReader.Name;
                tb.Text = nodeReader.ReadString();
                tb.Width = 400;

                c2.Controls.Add(tb);
                tr.Controls.Add(c1);
                tr.Controls.Add(c2);
                settingsTable.Rows.Add(tr);
                alt++;
            }
        }
        nodeReader.Close();
    }

You could use the meat of that function in a number of ways to produce the html markup that fits your style. This function will produce a table with a row for each setting, a column for the setting label, and a column with a text box holding the current setting value (editable).

Step 6: Saving the setting to the XML file

Finally, the edit page should be able to save the settings back to the XML file.

private void UpdateSettings()
    {
        string filename = "~/App_Data/Settings.xml";
        XmlWriterSettings writerSettings = new XmlWriterSettings(); ;
        writerSettings.Indent = true;

        //------------------------------------------------------------
        //    Create XML writer against file path
        //------------------------------------------------------------
        using (XmlWriter writer = XmlWriter.Create(Server.MapPath(filename), writerSettings))
        {
            writer.WriteStartElement("settings");

            foreach (HtmlTableRow row in settingsTable.Rows)
            {
                foreach (HtmlTableCell cell in row.Cells)
                {
                    foreach (Control ctrl in cell.Controls)
                    {
                        if (ctrl is TextBox)
                        {
                            TextBox tb = ctrl as TextBox;
                            writer.WriteElementString(tb.ID, tb.Text.Trim());
                        }
                    }
                }
            }
            writer.WriteEndElement();
        }
        Settings.LoadSettings();
    }

This function iterates through each table row which should represent a setting per row and gets the value from the text box control. The value is then written to the XML file as an element value using the text box id as the element name. Finally, the LoadSettings() function is called to reload the app settings with the new values.

Conclusion

You can use this technique to store all kinds of data in XML files. I'm sure many people will disagree with this method of settings management but the concepts presented here can be used for many different types of data. The core functions in this post will probably make it back into my helper class project in some form or another.

kick it on DotNetKicks.com


Related posts

Comments

May 31. 2008 09:55 AM

Vlad

Thank you
This is a simple concept which can be useful in some projects

Vlad

September 21. 2008 08:27 AM

laptop cases

great post and very Thank you for good extension. It's very usefull.

laptop cases

October 19. 2008 03:23 PM

khalil

Thanks, it very simply and useful article

khalil

October 20. 2008 02:02 PM

Nisar Khan

i dont see the source the link (helper class project) is a wrong ref to the subject.

would you email me the correct link please?

thanks.

Nisar Khan

November 1. 2008 04:57 PM

pingback

Pingback from internetmarketersbootcamp.com

Internet Marketers Bootcamp » Blog Archive » Do Follow List

internetmarketersbootcamp.com

November 11. 2008 12:27 AM

Mari Ann Lisenbe

Nice Post..

It will really help me a lot 'coz I'm using ASP to for my Websites..

BTW,

Feel Free to visit my website, <a href="www.YourLegacyBuilder.com Ann “Recession Proof” Lisenbe</a>


Thanks!!!

Mari Ann Lisenbe

November 12. 2008 10:23 AM

Webdesign Ireland

Very nice example - quite interesting approach! Thank you

Webdesign Ireland

November 12. 2008 10:45 PM

morgellons

Thank you so much for such a thoughtful piece on asp. Though I prefer php. I did learn thing or two.

morgellons

November 15. 2008 01:52 PM

Busby SEO Test

Sharing this post to my friend to see what is new here coz.. i love it.. thanks

Busby SEO Test

November 20. 2008 05:18 PM

nadja007

I don't much knowledge about this kind of a thing. But thanks you you it help me and it give's me additional knowledge.

nadja007

November 28. 2008 07:21 AM

suhail

PLZ provide complete info about doing in asp.net.

suhail

November 29. 2008 09:10 PM

Scott

Thank you for this. Great explanation.

Scott

December 2. 2008 05:06 PM

vardis

This isn't perfect but certainly useful.

vardis

December 3. 2008 03:12 AM

asasasas

fgfgfsdgdgfgfgfgf

asasasas

December 3. 2008 03:13 AM

asasasas

gfdgfdgfdgfdg

asasasas

December 3. 2008 03:13 AM

ankit

thanxxx

ankit

December 3. 2008 12:17 PM

Busby SEO Test

Very nice example - quite interesting approach! Thank you

Busby SEO Test

December 14. 2008 02:49 PM

Best Phone Number Tracker

Thanks a lot for sharing this. I've always been interested to learn ASP.net but seems confusing to me sometimes.

Best Phone Number Tracker

December 16. 2008 02:55 PM

busbySeo test

many thanks for share.

busbySeo test

December 24. 2008 03:51 AM

Busby SEO Test

yo! what a post!

Busby SEO Test

December 28. 2008 01:24 PM

Chris

Nice post. Any chance you could post a complete sample for us to look at in its entirety?

Chris

December 28. 2008 08:59 PM

Chris

One thing worth mentioning... between the update and the load function you need to clear out your table. If not you will end up with duplicate entries in your table which could get saved as duplicate values in your config file...

I added the syntax tblSettings.Rows.Clear(); to my load function and it seems to work fine.

Chris

Chris

January 1. 2009 11:40 PM

Busby SEO Test

Good XML Bozz

Busby SEO Test

January 3. 2009 05:12 PM

unique pet products

Thank you for the info. I didn't know you can do that.

unique pet products

January 7. 2009 12:17 PM

Busby SEO Test

Thank you for this great explanation.

Busby SEO Test

January 16. 2009 07:55 AM

gigabit ethernet

this looks great and really easy to follow - thanks a lot for posting and sharing it

gigabit ethernet

January 16. 2009 09:52 PM

scholarship

Thanks for code, very useful

scholarship

January 20. 2009 03:18 AM

renantech

thanks for sharing this great information.

renantech

January 28. 2009 12:44 PM

Kabon SEO

Thank you for your code and work. Hope it will help me then

Kabon SEO

February 16. 2009 03:17 AM

PC Errors

Thanks for this helpful post!

PC Errors

February 23. 2009 08:36 AM

Learning Selling

thank you! i've been looking for this.

Learning Selling

February 25. 2009 09:28 AM

asp.net coder

Thanks for the demo. Not sure I understand the use of the settings class since it is not instantiated in any of your examples above.

asp.net coder

March 9. 2009 01:20 PM

car rental in israel

This looks great, thanks a bunch.

I'm having issues converting this to vb. Anyone have this?

car rental in israel

March 9. 2009 01:21 PM

caesarea property

Thank you so much for such a thoughtful piece on asp. Though I prefer php. I did learn thing or two.

caesarea property

March 9. 2009 01:22 PM

jammer

lovely thing
lovely girl

jammer

March 10. 2009 05:10 AM

Find a email address

That' all I need. Thank you so much for sharing.

Find a email address

March 10. 2009 11:04 AM

Kampanye Damai Pemilu Indonesia 2009

i dont have many learning about xml

Kampanye Damai Pemilu Indonesia 2009

March 15. 2009 04:55 AM

code music friendster

so very usefull this informations..

code music friendster

March 16. 2009 09:54 AM

pat testing

Very good post, very well written and good clear examples A++ will bookmark this for future reference!

pat testing

March 16. 2009 09:55 AM

Shutters

Thanks for posting this it is going to save me loads of time and stress!

Shutters

March 16. 2009 09:56 AM

legal separation

Cool post thanks for sharing you are so kind, it going to make my homework so much easier

legal separation

March 17. 2009 11:14 PM

Global Cash Mavericks

this is a good source. thanks for the direction., it truly helps me., thanks again.

Global Cash Mavericks

March 20. 2009 05:19 AM

giving4prosperity

Thanks for this post, this is really great.Smile

giving4prosperity

March 20. 2009 08:24 AM

G-Land

thanks i really enjoy reading your article!!

G-Land

March 26. 2009 01:09 AM

teen pinoy bigbrother

Hi, thanks for the information. I got many ideas for my blog or website. I visit again to this site if there a new improvement.

teen pinoy bigbrother

March 28. 2009 12:29 PM

Jacksonville movers

love it
thanks
great post
made my day

Jacksonville movers

March 29. 2009 10:58 PM

Kampanye Damai Pemilu Indonesia 2009

Thank you my friend it's a great post

Kampanye Damai Pemilu Indonesia 2009

April 16. 2009 04:00 AM

cash4trends

Keep up the good work.

cash4trends

April 16. 2009 04:17 AM

goodpeoplegives

This is a great post.

goodpeoplegives

April 16. 2009 04:26 AM

billrainier

Continue your good job.

billrainier

April 17. 2009 08:23 PM

fabs

very usefull this informations..thank you for script

fabs

April 18. 2009 04:52 AM

Leadership

Thankyou very much this advice on using xml.files, thanks.

Leadership

April 23. 2009 05:09 AM

tnomeralc web design toys

Some are good and some are bad.. Really interesting post..

tnomeralc web design toys

April 23. 2009 05:50 AM

high blood sugar

Nice Read

Regards

michel

high blood sugar

April 23. 2009 06:22 PM

low cost franchises

Heya - Just looking through some blogengine.net blogs, seems to be a fairly nice platform, certainly better than blogger but still playing with the idea of wordpress. Any major plus points you have found over WP at all?

Thanks

Matthew

low cost franchises

April 27. 2009 02:52 PM

MD Answering Service

I got your blog from google.com i am doing a thesis on this niche can i have more info ?

Regards

Billi

MD Answering Service

April 28. 2009 08:22 AM

cctv suppliers

I am to submit a report on this niche your post has been very very helpfull

Regards

Brond

cctv suppliers

April 28. 2009 10:42 PM

RisingHot

This looks great, thanks a bunch.

RisingHot

April 29. 2009 08:17 PM

auto repair manual

I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

auto repair manual

April 30. 2009 06:26 AM

bips

I needed this info thanks mate

Regards
music downloads

bips

May 5. 2009 03:39 AM

Medical alarm systems

I bookmarked this already dude great work

Regards
Bomm

Medical alarm systems

May 7. 2009 09:01 AM

tukang nggame

Im just like xml

tukang nggame

May 7. 2009 11:07 PM

free ps3

Glad to read such a nice piece of information.
This is exciting news.

free ps3

May 9. 2009 06:03 PM

Make Money Online

Just bookmarked this post.

Make Money Online

May 11. 2009 01:55 PM

RA

If I could rate this article 10/5 I would - great stuff! I used the XmlDocument to navigate the DOM however, I find this a bit more intuitive, but your design is great - thanks very much!!!

RA

May 12. 2009 05:53 AM

MA Videographers

Is this true ?


Regards


Sam

MA Videographers

May 12. 2009 07:47 PM

casi casi

Thx for sharing

casi casi

May 14. 2009 12:21 AM

Simulation pret immobilier

Thanks a lot for this thread. I will definitely recommend it to my friends.

Simulation pret immobilier

May 15. 2009 06:16 AM

interior designers los angeles

This seems like the most comprehensive blog on this niche

Regards
Dani

interior designers los angeles

May 16. 2009 01:33 AM

Cheer leading Scholarship

Is this true ?


Regards
Dock

Cheer leading Scholarship

May 16. 2009 01:07 PM

provillus for women

this help a lot, thanks

provillus for women

May 18. 2009 03:56 PM

tukang nggame

very useful for us
thanks for sharing this

tukang nggame

May 19. 2009 05:19 AM

katekyo hitman reborn 137

hello
your design nice & good post

katekyo hitman reborn 137

May 28. 2009 04:06 AM

american child adoption


I bookmarked this already dude great work

Regards

Brane

american child adoption

May 28. 2009 11:32 AM

Prada Handbags

Thanks for such a nice post.

Regards
Gimes

Prada Handbags

May 29. 2009 10:58 PM

tukang nggame

NIce xmml

tukang nggame

May 30. 2009 10:54 PM

belajar SEO para pemula

thanks you to help me and it give's me additional knowledge.

belajar SEO para pemula

May 31. 2009 06:34 PM

Left handed electric guitar

This is great info. Keep it up!

Left handed electric guitar

June 2. 2009 01:58 AM

asta online al ribasso

Thanks for such a nice post.

Regards
Willam

asta online al ribasso

June 5. 2009 08:07 PM

Tukang Nggame

what a great blog, i really like it.

Tukang Nggame

June 10. 2009 12:19 PM

how to grow taller

That is a great post

how to grow taller

June 10. 2009 12:20 PM

how to grow taller

That is a great post

how to grow taller

June 10. 2009 12:43 PM

Gadis

thank for this info sir Smile

Gadis

June 13. 2009 03:24 AM

Reverse Phone lookup

Its quite easy to do now..

Reverse Phone lookup

June 15. 2009 01:12 AM

tiffany

good!

tiffany

June 17. 2009 09:28 PM

rusli zainal sang visioner

thanks for sharing great code

rusli zainal sang visioner

June 17. 2009 10:34 PM

tiffany jewelry

I have read this article,itis very good!

tiffany jewelry

June 18. 2009 02:50 AM

club penguin

Well... I don't much knowledge about this kind of a thing. But thanks you you it help me and it give's me additional knowledge.

club penguin

June 18. 2009 06:56 PM

kabinet 2009

The post that I need.
Very clear explanation.
You're very clever.

kabinet 2009

June 19. 2009 12:46 AM

jackmilney

hI.........


Its quite easy to do now..

Thanks..

jackmilney

June 19. 2009 12:47 AM

jackmilney

Helloooooooo.......


I have read this article,itis very good!

Thanks.

jackmilney

June 19. 2009 12:49 AM

jackmilney

This seems like the most comprehensive blog on this niche


Thanks....

jackmilney

June 19. 2009 12:50 AM

jackmilney

Helloo...............


Well... I don't much knowledge about this kind of a thing. But thanks you you it help me and it give's me additional knowledge.


thanks.

Regards

jackmilney

June 19. 2009 12:56 AM

tiffany jewellry

thank you for giving us a comment place.
i support your idea.hope you everying goes well.

tiffany jewellry

June 21. 2009 03:42 AM

tiffany jewellery

I apppraciate your comment ,your idea is wonderful.
wish you everything goes smoothly !

tiffany jewellery

June 21. 2009 08:52 PM

tiffany rings


Thanks for the great widget! Going to add it to my installation next week.
I've also posted about it on the BlogEngine Forums

tiffany rings

June 22. 2009 04:38 AM

Tiffany Earrings

Thanks for the great widget! Going to add it to my installation next week.
I've also posted about it on the BlogEngine Forums

Tiffany Earrings

June 25. 2009 03:39 AM

Vic >>>>>Click

This is great! thanks for the tips and keep on posting more tricks here.
http://www.24hpayday.com

Vic >>>>>Click

June 25. 2009 05:57 AM

seo

very nice information. thanks for sharing.

seo

June 27. 2009 04:02 AM

Borrow money online

Thanks for posting this, it really gives help to me and i really enjoy reviewing the code that was really great and i have learned a new tips from it, thanks a lot keep on posting more info here.





http://www.24hpayday.com

Borrow money online

June 27. 2009 06:51 AM

Las Vegas real estate foreclosures

The step by step guide is good and works well. Thanks a ton for keeping things simple as always.

Las Vegas real estate foreclosures

June 29. 2009 09:12 AM

web hosting unlimited

thank you for giving us a comment place.

I have read this article,itis very good!

Thanks.

Anu

web hosting unlimited

June 30. 2009 12:37 AM

key biscayne homes

Thanks for providing this wonderful tutorial. From next time I am going to try xml file.

key biscayne homes

July 1. 2009 10:10 PM

Tiffany

It was a very nice idea! Just wanna say thank you for the information you have shared. Just continue writing this kind of post. I will be your loyal reader. Thanks again.

Tiffany

July 2. 2009 08:43 PM

linksoflondon

Thanks for providing your suggestions!I am agreet with your idears!

linksoflondon

July 2. 2009 11:58 PM

hkdedicatedhosting

thanks for sharing
i like it
it is very useful
thanks again

hkdedicatedhosting

July 3. 2009 08:43 AM

Pharm

Simple and clear. thanks for this info

Pharm

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 3. 2009 10:57 PM

Search

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009