Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Persist your objects/settings in XML

0.00/5 (No votes)
5 Sep 2012CPOL2 min read 14.9K  
A useful class for persisting your settings to XML config files.

Introduction

Many times we might want to quickly persist objects or settings for quick retrieval later, but don't want to go with a database request every time. For example we want to save a lookup table for "Countries" dropdown or "Titles" dropdown. Let's persist them into an XML config file so that later on we can retrieve them whenever needed. As request to or the respective XML config is a file request, it is relatively faster also.

Background

Here is an article which uses XML as a database to persist objects. Although this is just a repeat of my description there, in this tip I want to emphasize on XML Persister. As mentioned in the article, this XML persister is a cut down version of Persister from the My Web Pages Starter Kit project.

Using the code

Our Persistence class, Persister is a cut down version of the XML Persister from the My Web Pages StarterKit project.

This class is useful for persisting your settings to XML config files. In our case, we are using it to persist our POST data into an XML database (App_Data/Posts.config). It serializes and deserializes XML objects and abstracts a lot of functionality for us. All you need to do is:

  1. Provide the location of your XML data file in the constructor.
  2. Provide the type of the object to persist in the XML. E.g.:-
  3. C#
    Persister<Posts> currentPosts = new Persister<Posts>(_dataFileName);

And here is our Persister class. Once we create an instance of this class, what we get is:

  1. This class creates an instance of the type of object we supplied in the above statement (e.g., it creates a Persister of type Posts in the above example)
  2. The Persister.load method loads the existing List of persisted objects from the current XML config file. This method simply reads the target location config file, and uses the .NET XMLSerializer to serialize it into a list of the supplied type to our Persister.
  3. The Persister.save method simply loads the config file again. Serializes our current object list into XML to persist in our target config file.
C#
public class Persister<T>
{
    private string _dataFileName;
    private List<T> _objList;

    public List<T> objList
    {
        get { return (_objList); }
    }

    public Persister(string dataFileName)
    {
        // Sets the location of datafile into App_Data Directory of our Application 
        //(We can change the location of our datafiles to Other directory as well)
        // This constructor creates a Persister of supplied type
        //
        this._dataFileName = HttpContext.Current.Server.MapPath(
                string.Format("~/App_Data/{0}", dataFileName));
        this._objList = Activator.CreateInstance<List<T>>();
    }

    public void save()
    {
        lock (_dataFileName)
        {
            using (FileStream writer = File.Create(_dataFileName))
            {
                XmlSerializer serializer = new XmlSerializer(_objList.GetType());
                serializer.Serialize(writer, _objList);
            }
        }
    }

    public void load()
    {
        if (File.Exists(_dataFileName))
        {
            lock (_dataFileName)
            {
                using (FileStream reader = File.Open(_dataFileName, 
                         FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
                    _objList = (List<T>)serializer.Deserialize(reader);
                }
            }
        }
        else
        {
            _objList = new List<T>();
            save();
        }
    }
}

Here is how we use our Persister class to persist our objects (of type Posts in this example). Basically:

  1. We pass the type of target objects to persist and the name of our data file: Persister<Posts> persister = new Persister<Posts>(_dataFileName);
  2. Load the existing list of target objects into the list of our persister using persister.load().
  3. Save the newly updated list to our XML config using the persister.save() method.
C#
//Pass the type of object ("Posts") and Name of the datafile to be used, to the constructor of Persister
Persister<Posts> persister = new Persister<Posts>(_dataFileName);

//Load the objects of type Posts from the current Posts config
persister.load();
_posts = persister.objList;

if (Request.RequestType == "POST")
{
    //Fetch the request data
    string strName = Request.Form["txtName"];
    //....
    //Create a Posts object and assign values
    Posts post = new Posts();
    post.Name = strName;
    //....
    //Add it to the current loaded list and save the list using persister
    _posts.Add(post);
    persister.save();
}

Points of interest

You may like to try out this XML Persister in the demo project here:

History

  1. 13/Mar/2012: Initial post with introduction to the Persister class.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)