Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C#

DataStorage: Store settings type-safe

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
8 Aug 2012GPL33 min read 26.1K   234   9  
Shows how to use the DataStorage classes to generate type-safe settings classes.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;

namespace pdfforge.DataStorage
{
    public class XmlFiles : DataReader, DataWriter
    {
        public Data data = null;

        public void setData(Data data)
        {
            this.data = data;
        }

        public void readData()
        {
            throw new Exception("This may not be called without path");
        }

        public void readData(string path, bool clear)
        {
            if (clear)
                data.clear();

            try
            {
                XmlTextReader xml = new XmlTextReader(path);
                readXmlData(xml);
                xml.Close();
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private bool isSubsection(XmlReader xml)
        {
            string type = xml.GetAttribute("type");
            return (!String.IsNullOrEmpty(type) && type.Equals("section"));
        }

        private string composeSectionName(List<string> sections)
        {
            string name = "";
            
            //foreach (string section in sections)
            //    name += section + "\\";

            // the first xml section "DataStorage" will be ignored
            for (int i = 1; i < sections.Count; i++)
            {
                string section = sections[i];
                name += section + "\\";
            }

            return name;
        }

        private void readXmlData(XmlReader xml)
        {
            List<string> sections = new List<string>();

            while (xml.Read())
            {
                //Console.WriteLine(xml.NodeType);
                switch (xml.NodeType)
                {
                    case XmlNodeType.Element:
                        if (isSubsection(xml))
                        {
                            sections.Add(xml.Name);
                            string sectionName = composeSectionName(sections);
                            //Console.WriteLine("Entering: " + xml.Name);
                            //Console.WriteLine("Section: " + sectionName);
                            data.addSection(sectionName);
                        }
                        else
                        {
                            string valueName = composeSectionName(sections) + xml.Name;
                            string value = xml.ReadElementContentAsString();
                            data.setValue(valueName, value);
                            //Console.WriteLine(valueName + "=" + value);
                        }
                        break;
                    //
                    //you can handle other cases here
                    //
                    case XmlNodeType.EndElement:
                        //Console.WriteLine("Leaving: " + xml.Name);
                        sections.RemoveAt(sections.Count - 1);
                        break;
                    //case XmlNodeType.Text:
                    //    break;
                    default:
                        break;
                }

            }
            /*while (xml.Read())
            {
                switch (xml.NodeType)
                {
                    case XmlNodeType.Element: // Der Knoten ist ein Element.
                        Console.Write("<" + xml.Name);

                        while (xml.MoveToNextAttribute()) // Attribute lesen.
                            Console.Write(" " + xml.Name + "='" + xml.Value + "'");
                        Console.Write(">");
                        Console.WriteLine(">");
                        break;
                    case XmlNodeType.Text: //Anzeige des Textes in jedem der Elemente.
                        Console.WriteLine(xml.Value);
                        break;
                    case XmlNodeType.EndElement: //Ende der Elementanzeige.
                        Console.Write("</" + xml.Name);
                        Console.WriteLine(">");
                        break;
                }
            }// */
        }

        public void readData(string path)
        {
            readData(path, true);
        }

        public void writeData()
        {
            throw new Exception("This may not be called without path");
        }

        public void writeData(string path)
        {
            string xmlData = buildXmlData();
            File.WriteAllText(path, xmlData);
        }

        private string buildXmlData()
        {
            XmlStringBuilder xml = new XmlStringBuilder();
            xml.openSubSection("DataStorage");
            
            buildXmlData("", xml);
            
            xml.closeSubSection();
            return xml.ToString();
        }

        private void buildXmlData(string section, XmlStringBuilder xml)
        {
            List<string> sections = new List<string>();
            sections.AddRange(data.getSubSections(section));

            foreach (string s in sections)
            {
                int depth = s.Substring(section.Length).Split('\\').Length - 1;
                if (depth == 1)
                {
                    xml.openSubSection(Data.getSubsectionName(s));
                    buildXmlData(s, xml);
                    xml.closeSubSection();
                }
            }

            if (!String.IsNullOrEmpty(section))
            {
                foreach (KeyValuePair<string, string> p in data.getValues(section))
                {
                    xml.addValue(p.Key, p.Value);
                }
            }
        }

        public override string ToString()
        {
            return buildXmlData();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
pdfforge GbR
Germany Germany
Philip is a Software Architect with severaly years of experience. He studied business IT in the University of Wedel, Germany, and has reached his Masters degree in 2010. Back in 2002, he started his so far best-known software PDFCreator. The second developer joined two years later and since then, both constantly improve this piece of open source software.

Comments and Discussions