星期五, 十二月 23, 2011

Serialize and DeSerialize generic Array

We often use things like Configuration[] configs and like to manage that in a xml file you can edit. Two simple extension methods can help you.

        public static string SerializeArray(this T[] list)
        {
            System.Xml.XmlDocument doc = new XmlDocument();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(list.GetType());
            System.IO.MemoryStream stream = new System.IO.MemoryStream();

            try
            {
                serializer.Serialize(stream, list);
                stream.Position = 0;
                doc.Load(stream);
                return doc.InnerXml;
            }
            catch { throw; }
            finally
            {
                stream.Close();
                stream.Dispose();
            }
        }

        public static T[] DeSerializeArray(string serializedData)
        {
            T[] list = null;
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T[]));
            XmlReader xReader = XmlReader.Create(new StringReader(serializedData));

            try
            {
                list = (T[])serializer.Deserialize(xReader);
            }
            catch
            {
                throw;
            }
            finally
            {
                xReader.Close();
            }

            return list;
        }


Code to serialize the data:

string xml1 = _environments.SerializeArray();
StreamWriter writer = new StreamWriter("config.xml");
writer.Write(xml1);
writer.Close();

To DeSerialize the data:

string xml = File.ReadAllText("config.xml");
_environments = Extensions.DeSerializeArray(xml);



If you don't like the root "ArrayOfConfiguration" you can change the extension methods to use a XmlRootAttribute like:
            XmlRootAttribute root = new XmlRootAttribute(rootName);
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T[]), root);

You need to use the matching name in both methods to get it working.

星期五, 十二月 16, 2011

S.C.A.M 9

Government should ban union's enforcement at work. So every one can be part of an union at work or choose not to be. Same thing for doctors and lawyers. They shouldn't only allow those permitted by the committee or bar