Click here to Skip to main content
12,451,425 members (60,474 online)
Click here to Skip to main content
Add your own
alternative version

Stats

78.7K views
558 downloads
27 bookmarked
Posted

Option Library

, 1 Aug 2002
Rate this:
Please Sign up or sign in to vote.
Provides methods to save and load option classes

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

Share

About the Author

leppie
Software Developer
South Africa South Africa
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralError if Value is 56 character Long Pin
Chandru.BK2-Aug-05 20:27
memberChandru.BK2-Aug-05 20:27 
GeneralRe: Error if Value is 56 character Long Pin
leppie2-Aug-05 21:00
memberleppie2-Aug-05 21:00 
GeneralNice Pin
eirikhm21-Mar-05 5:46
membereirikhm21-Mar-05 5:46 
GeneralNice Job Pin
Nick Parker13-Jul-03 3:50
editorNick Parker13-Jul-03 3:50 
JokeRe: Nice Job Pin
Marcelo Miorelli29-Aug-06 22:47
memberMarcelo Miorelli29-Aug-06 22:47 
GeneralReduce Indent Pin
Shog92-Aug-02 5:11
memberShog92-Aug-02 5:11 
GeneralRe: Reduce Indent Pin
leppie2-Aug-02 6:38
memberleppie2-Aug-02 6:38 
GeneralRe: Reduce Indent Pin
Shog92-Aug-02 6:41
memberShog92-Aug-02 6:41 
GeneralRe: Reduce Indent Pin
Paul Watson19-Nov-02 5:55
sitebuilderPaul Watson19-Nov-02 5:55 
GeneralRe: Reduce Indent Pin
Shog919-Nov-02 6:03
memberShog919-Nov-02 6:03 
GeneralRe: Reduce Indent Pin
peterchen20-Dec-05 7:36
memberpeterchen20-Dec-05 7:36 
GeneralRe: Reduce Indent Pin
Shog920-Dec-05 8:31
sitebuilderShog920-Dec-05 8:31 
GeneralClass changes Pin
Todd Smith2-Aug-02 4:21
memberTodd Smith2-Aug-02 4:21 
GeneralRe: Class changes Pin
leppie2-Aug-02 6:39
memberleppie2-Aug-02 6:39 
GeneralRe: Class changes Pin
kabocyahoto10-Aug-04 15:04
memberkabocyahoto10-Aug-04 15:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web02 | 2.8.160826.1 | Last Updated 2 Aug 2002
Article Copyright 2002 by leppie
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid