I want to discuss a simple solution for accessing global application settings from your web pages using ASP.NET page inheritance and XML files as a storage medium for your settings. Before I can do that, however, I need to discuss XML serialization and deserialization as a method of persisting and fetching application settings from XML.
XML serialization essentially allows us to convert objects in our applications into an XML representation that we can send over the “wire”, persist to a file, etc. Later on we can use a process, called deserialization, to convert the XML back into the object if we so desire. There are some gotchas about how you need to set up your objects, how deeply XML serialization will “copy” your objects, etc., but that is out of the scope of this article.
The following code below shows an example of serializing the object siteSettings to a file. First, we create a new SiteSettings object that we are going to serialize to a file. We then create a new XMLSerializer object and pass it the type of the object we are going to serialize. And last, we open up a new stream and write the XML to our configuration file. You can see the code and output below.
So now we have serialized the contents of the object into a file and we need to get it back. As you can tell in the SiteSettings Class above, I already have a static Fetch() method that converts the XML back into an object. Below is the Fetch() method repeated. Nothing exciting here, except for how easy it is. We are essentially doing the exact opposite – reading the xml from the file and calling Deserialize to re-create the siteSettings object.
Here is some code you can run in Snippet Compiler that will allow you to see it happen:
It is probably quite obvious how to use this now in your base pages for retrieving global application settings for your ASP.NET pages, but I will toss up a code example in my next post in case it might not be so clear.