Introduction
Looking up on Google about XML serialization would give us many links about problems, questions, and other things about it. But nowhere, did I find an article that has it all. So if you are looking at how to serialize hashtables, GDI objects (GraphicsPath
, Font
s...), etc., read on.
Background
All the code has been verified under Microsoft FxCop 1.35. If you're not very familiar with XML or serialization, refer to MSDN.
Using the code
An XML file can store any of the following: basic type objects (like DateTime
...), GDI objects (GraphicsPath
, Font
, Pen
...), or complex objects (Hashtable
...).
The main serialization operation is is done inside Configuration.cs. All new XML object types are listed in XmlUtility.GetXmlTypes
. The Save
and Load
functions are not very difficult to understand.
You can have a Hashtable
of anything (integer, list). Just take a look at the code in the InitDefault
function in BasicConfiguration
, GdiConfiguration
, and OtherConfiguration
.
try
{
string strConfigurationFile = @"./config.XML";
Configuration Config = new Configuration ();
Configuration Config2;
Console.WriteLine ("Writing configuration file");
Config.Save (strConfigurationFile);
Console.WriteLine ("Reset values");
Config.BasicConfiguration.MyFloat = 0.0f;
Config.BasicConfiguration.MyString =String.Empty;
Config.BasicConfiguration.MyInt = 64;
Console.WriteLine ("Node test");
XmlNodeContainer ScreenNode = (XmlNodeContainer)
(Config.OtherConfiguration.XmlNodeContainer["Screen"]);
XmlKeyAndValue KeyAndValue1 = (XmlKeyAndValue)ScreenNode["ResolutionX"];
XmlKeyAndValue KeyAndValue2 = (XmlKeyAndValue)ScreenNode["ResolutionY"];
Console.WriteLine (string.Format ("Resolution saved : {0}x{1}",
KeyAndValue1.Value, KeyAndValue2.Value));
XmlKeyAndValue KeyAndValue3 = (XmlKeyAndValue)((XmlNodeContainer)
Config.OtherConfiguration.XmlNodeContainer["Network"])["MAC ADDRESS"];
Console.WriteLine (string.Format ("Network MAC ADDRESS saved : {0}",
KeyAndValue3.Value));
Console.WriteLine ("Reload default configuration");
Config2 = Configuration.Load (strConfigurationFile);
Console.WriteLine ("Ok");
}
catch (Exception e)
{
Console.WriteLine ("ERROR");
Console.WriteLine (e.ToString ());
}
Console.WriteLine ("Press Return to quit");
Console.ReadLine ();
I hope you'll find it useful.
Points of interest
I've tried to make the code as simple as possible so that anyone can upgrade it.
Bug report
There is one 'bug' where I need some help. In xmltranslatorelement.cs (line 111), FxCop returns this error: CollectionPropertiesShouldBeReadOnly
. So you'd prolly think that you could remove the set()
attribute, but here comes the trouble. We must implement the Add
and GetEnumerator
functions from IEnumerable
but we have a hashtable. If someone knows how to break this error...
History