Click here to Skip to main content
Click here to Skip to main content

Option Library

By , 1 Aug 2002
Rate this:
Please Sign up or sign in to vote.

Sample Image - OptionLib.jpg

Introduction

I have looked around for a way of saving my application settings, but there are several stumbling blocks. The class should overcome them all. There are only 2 static methods. Load and Save.

Problems

  1. All serializable objects should be serialized.
  2. BinaryFormatter works fine as long as class is not changed in structure.
  3. XmlSerializer do provide methods to serialize classes without a default constructor.

Option class requirements

  • Class MUST have default constructor.
  • An instance of the class must exist before calling Load

Source code

public static void Save(string filename, object options)
{

  Byte[] buffer = new Byte[80];
  MemoryStream ms;
  BinaryFormatter bf = new BinaryFormatter();

  System.Xml.XmlTextWriter xmlwriter = 
    new XmlTextWriter(filename, System.Text.Encoding.Default);

  xmlwriter.Formatting = Formatting.Indented;
  xmlwriter.WriteStartDocument();

  xmlwriter.WriteComment("Option File. Do not edit!");
  xmlwriter.WriteStartElement(options.ToString());
		
  PropertyInfo[] props = options.GetType().GetProperties(
    BindingFlags.Public | 
    BindingFlags.Instance | 
    BindingFlags.SetField);

  foreach (PropertyInfo prop in props)
  {
    xmlwriter.WriteStartElement(prop.Name);

    object da = prop.GetValue(options, null);

    if (da != null) 
    {
      xmlwriter.WriteAttributeString("Value", da.ToString());

      ms = new MemoryStream();
      try 
      {
        bf.Serialize(ms, da);
        ms.Position = 0;
        int count = 0;
        do 
        {
          count = ms.Read(buffer, 0, buffer.Length);
          xmlwriter.WriteBase64(buffer, 0, count);
        }
        while ( count == buffer.Length);
      } 
      catch (System.Runtime.Serialization.SerializationException e)
      {
        Console.WriteLine("SERIALIZATION FAILED: {0}", prop.Name);
      }

    }
    else xmlwriter.WriteAttributeString("Value", "null");

    xmlwriter.WriteEndElement();
  }
  xmlwriter.WriteEndElement();
  xmlwriter.WriteEndDocument();
  xmlwriter.Flush();
  xmlwriter.Close();
}

public static void Load(string filename, object options)
{
  Byte[] buffer = new Byte[80];
  MemoryStream ms;
  BinaryFormatter bf = new BinaryFormatter();

  System.Xml.XmlTextReader reader = new XmlTextReader(filename);

  while (reader.Read())
  {
    switch (reader.NodeType)
    {
      case XmlNodeType.Element:

        if (reader.HasAttributes)
        {
          string name = reader.Name;
          string val = reader.GetAttribute("Value");

          ms = new MemoryStream();
		
          int count = 0;
          do 
          {
            count = reader.ReadBase64(buffer, 0 , buffer.Length);
            ms.Write(buffer, 0,count);
          }
          while (count == buffer.Length);

          ms.Position = 0;

          if (val != "null") 
          {
            try 
            {
              object da = bf.Deserialize(ms);

              Console.Write("Applying {0} : ", name);
              options.GetType().GetProperty(name).SetValue(options, da, null);
              Console.WriteLine("OK");
            }
            catch (System.Runtime.Serialization.SerializationException e)
            {
              Console.WriteLine("FAIL: {0}",e.Message);
            }
          }
        }
        break;
    }
  }
  reader.Close();
}

Implementation

  • static Load(string filename, object optionclass);
  • static Save(string filename, object optionclass);

That's it. Any problems, let me know.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

leppie
Software Developer
South Africa South Africa
No Biography provided
Follow on   Twitter

Comments and Discussions

 
GeneralError if Value is 56 character Long PinmemberChandru.BK2-Aug-05 20:27 
GeneralRe: Error if Value is 56 character Long Pinmemberleppie2-Aug-05 21:00 
GeneralNice Pinmembereirikhm21-Mar-05 5:46 
GeneralNice Job PineditorNick Parker13-Jul-03 3:50 
JokeRe: Nice Job PinmemberMarcelo Miorelli29-Aug-06 22:47 
GeneralReduce Indent PinmemberShog92-Aug-02 5:11 
GeneralRe: Reduce Indent Pinmemberleppie2-Aug-02 6:38 
GeneralRe: Reduce Indent PinmemberShog92-Aug-02 6:41 
GeneralRe: Reduce Indent PinsitebuilderPaul Watson19-Nov-02 5:55 
GeneralRe: Reduce Indent PinmemberShog919-Nov-02 6:03 
GeneralRe: Reduce Indent Pinmemberpeterchen20-Dec-05 7:36 
GeneralRe: Reduce Indent PinsitebuilderShog920-Dec-05 8:31 
GeneralClass changes PinmemberTodd Smith2-Aug-02 4:21 
GeneralRe: Class changes Pinmemberleppie2-Aug-02 6:39 
GeneralRe: Class changes Pinmemberkabocyahoto10-Aug-04 15:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 2 Aug 2002
Article Copyright 2002 by leppie
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid