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

A General Class Library to Save and Load an Object

, 14 Jun 2008
Rate this:
Please Sign up or sign in to vote.
A general class library to save and load an object in a file using XML or binary format.

Introduction

All programmer needs to save their application data or state in order to restore them at a later time. But writing methods to save an load data in a file is some time a really time costing procedure. This Class Library saves you a lot of time saving your data and loading them again.

Background

If you want to save your object state, it means that you should save all your object members, fields, and properties values to a file and then restore their value later.

Using the code

This class has two methods named 'SaveData' and 'LoadData'. All these methods want as parameters are the object you want to save, the path which you want to save your object data to, and the type of saving format: XML or binary.

namespace BabakTajalliNezhad.Tools
{
    public class ObjectController
    {
        DataSet Result = new DataSet("Object Save & Load - " + 
                                       "Programmed by Babak Tajalli Nezhad");
        DataTable CurrentTable;
        public enum SaveType { XML, Binary };

        #region .:: Object Load Methods ::.
        //------------------------Load Methods----------------------------------\\
        /// <summary>
        /// Used to Load Data from a file in to an instance of an object
        /// </summary>
        /// <param name="Target">The instance of an object
        ///           which you want to load the data into</param>
        /// <param name="Path">The File path of where
        ///               you saved your object</param>
        /// <param name="HowToSave">specifies the type of save
        ///              operation binary or xml</param>
        [Description("Used to Load Data from a file in to an instance of an object")]
        public void LoadData(object Target, string Path,SaveType HowToSave)
        {
            Result.Clear();
            if (HowToSave == SaveType.Binary)
            {
                string FileContent = System.IO.File.ReadAllText(Path);
                string XMLContent = "";
                for (int e = 0; e < FileContent.Length; e += 10)
                {
                    XMLContent += FileContent[e];
                }
                System.IO.StreamWriter TempWriter = 
                  new System.IO.StreamWriter(Environment.SystemDirectory + 
                                             @"\temp.xml");
                TempWriter.Write(XMLContent);
                TempWriter.Close();
                Result.ReadXml(Environment.SystemDirectory + @"\temp.xml");
                System.IO.File.Delete(Environment.SystemDirectory + @"\temp.xml");
            }
            else
            {
                Result.ReadXml(Path);
            }
            Type ObjectType = Target.GetType();
            System.Reflection.PropertyInfo[] ObjectProperties = 
                                             ObjectType.GetProperties();
            System.Reflection.FieldInfo[] ObjectFields = ObjectType.GetFields();
            //string Result
            CurrentTable = Result.Tables[ObjectType.Name + "_Fields"];
            for (int i = 0; i < ObjectFields.Length; i++)
            {
                try
                {
                    xmlToField(ObjectFields[i], Target);
                }
                catch { }
            }            

            CurrentTable = Result.Tables[ObjectType.Name + "_Properties"];
            for (int i = 0; i < ObjectProperties.Length; i++)
            {
                try
                {
                    xmlToProperty(ObjectProperties[i], Target);
                }
                catch { }
            }
        }        
        private object LoadData(string Name)
        {
            foreach (DataRow Dr in CurrentTable.Rows)
            {
                if (Dr["Name"].ToString() == Name)
                {                    
                    return Dr["Value"];
                }
            }
            return null;
        }
        private void xmlToField(System.Reflection.FieldInfo Field, object Target)
        {
            try
            {
                Type TargetType = Field.FieldType;
                if (!TargetType.IsPrimitive)
                {
                    if (TargetType.IsSerializable)
                    {
                        LoadSerializedData(Field.GetValue(Target) as Array, 
                          Field.ReflectedType.FullName + "." + Field.Name);
                    }
                    System.Reflection.FieldInfo[] TargetFields = TargetType.GetFields();
                    System.Reflection.PropertyInfo[] TargetProperties = 
                                                     TargetType.GetProperties();
                    for (int i = 0; i < TargetFields.Length; i++)
                    {
                        xmlToField(TargetFields[i], Field.GetValue(Target));
                    }
                    for (int j = 0; j < TargetProperties.Length; j++)
                    {
                        propertyToxml(TargetProperties[j], Field.GetValue(Target));
                    }
                }
                try
                {
                    object Value = LoadData(Field.ReflectedType.FullName + 
                                            "." + Field.Name);
                    Field.SetValue(Target, Convert.ChangeType(Value, Field.FieldType));
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }
            catch { }
        }

        private void LoadSerializedData(Array Target, string Caller)
        {
            try
            {
                for (int j = 0; j < Target.Length; j++)
                {
                    if (Target.GetValue(j) != null)
                    {
                        Type ObjectType = Target.GetValue(j).GetType();
                        if (!ObjectType.IsPrimitive)
                        {
                            System.Reflection.FieldInfo[] ObjectFields = 
                                                          ObjectType.GetFields();
                            System.Reflection.PropertyInfo[] ObjectProperties = 
                                              ObjectType.GetProperties();
                            for (int i = 0; i < ObjectFields.Length; i++)
                            {
                                xmlToField(ObjectFields[i], Target.GetValue(j));
                            }
                            for (int i = 0; i < ObjectProperties.Length; i++)
                            {
                                xmlToProperty(ObjectProperties[i], Target.GetValue(j));
                            }
                        }
                        try
                        {
                            object Value = LoadData(Caller + "[" + j.ToString() + "]");
                            Target.SetValue(Convert.ChangeType(Value, 
                                            Target.GetValue(j).GetType()), j);
                        }
                        catch (Exception ex)
                        {
                            //MessageBox.Show(ex.Message);
                        }
                    }
                }

            }
            catch { }
        }
        private void xmlToProperty(System.Reflection.PropertyInfo Property, object Target)
        {
            try
            {
                if (Property.CanWrite && Property.CanWrite)
                {
                    Type TargetProperty = Property.GetType();
                    System.Reflection.PropertyInfo[] TargetProperties = 
                                      TargetProperty.GetProperties();
                    System.Reflection.FieldInfo[] TargetFields = TargetProperty.GetFields();
                    for (int i = 0; i < TargetProperties.Length; i++)
                    {
                        xmlToProperty(TargetProperties[i], Property.GetValue(Target, null));
                    }
                    for (int j = 0; j < TargetFields.Length; j++)
                    {
                        xmlToField(TargetFields[j], Property.GetValue(Target, null));
                    }
                    try
                    {
                        object Value = LoadData(Property.ReflectedType.FullName + 
                                                "." + Property.Name);
                        Property.SetValue(Target, Convert.ChangeType(Value, 
                                                  Property.PropertyType), null);
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message);
                    }
                }

            }
            catch { }
        }
        #endregion

        #region .:: Object Save Methods ::.
        //-------------------------Save Methods----------------------------------\\
        /// <summary>
        /// Used to Save an instance of an object in to a file
        /// </summary>
        /// <param name="Target">The instance of an object which you want to save</param>
        /// <param name="Path">The File path of where you want to save your object</param>
        /// <param name="HowToSave">specifies the type of save operation binary or xml</param>
        [Description("Used to Save an instance of an object in to a file")] 
        public void SaveData(object Target, string Path,SaveType HowToSave)
        {
            Type ObjectType = Target.GetType();
            System.Reflection.PropertyInfo[] ObjectProperties = ObjectType.GetProperties();
            System.Reflection.FieldInfo[] ObjectFields = ObjectType.GetFields();
            //string Result
            DataTable ObjectTable = new DataTable(ObjectType.Name + "_Fields");
            SetTableFields(ref ObjectTable);
            CurrentTable = ObjectTable;
            for (int i = 0; i < ObjectFields.Length; i++)
            {
                try
                {
                    fieldsToxml(ObjectFields[i], Target);
                }
                catch { }
            }
            Result.Tables.Add(CurrentTable);
            DataTable PropertyTable = new DataTable(ObjectType.Name + 
                                           "_Properties");
            SetTableFields(ref PropertyTable);
            CurrentTable = PropertyTable;
            for (int i = 0; i < ObjectProperties.Length; i++)
            {
                try
                {
                    propertyToxml(ObjectProperties[i], Target);
                }
                catch { }
            }
            Result.Tables.Add(CurrentTable);
            if (HowToSave == SaveType.XML)
            {
                Result.WriteXml(Path);
            }
            else
            {
                string XMLObject = Result.GetXml();
                System.IO.StreamWriter MyWriter = 
                               new System.IO.StreamWriter(Path);
                Random MyRandomNumbr = new Random();
                for (int e = 0; e < XMLObject.Length; e++)
                {
                    MyWriter.Write(XMLObject[e]);
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                    MyWriter.Write(Convert.ToChar(MyRandomNumbr.Next(255)));
                }
                MyWriter.Close();
            }            
        }
        private void SetTableFields(ref DataTable Table)
        {
            Table.Columns.Add("Name");
            Table.Columns.Add("Value");
        }
        private void SaveData(string Name, object Value)
        {
            CurrentTable.Rows.Add(new object[] { Name, Value });
        }
        private void fieldsToxml(System.Reflection.FieldInfo Field, object Target)
        {
            try
            {
                Type TargetType = Field.FieldType;
                if (!TargetType.IsPrimitive)
                {
                    if (TargetType.IsSerializable)
                    {
                        SaveSerializedData(Field.GetValue(Target) as Array, 
                          Field.ReflectedType.FullName + "." + Field.Name);
                    }
                    System.Reflection.FieldInfo[] TargetFields = TargetType.GetFields();
                    System.Reflection.PropertyInfo[] TargetProperties = 
                                      TargetType.GetProperties();
                    for (int i = 0; i < TargetFields.Length; i++)
                    {
                        fieldsToxml(TargetFields[i], Field.GetValue(Target));
                    }
                    for (int j = 0; j < TargetProperties.Length; j++)
                    {
                        propertyToxml(TargetProperties[j], Field.GetValue(Target));
                    }
                }
                SaveData(Field.ReflectedType.FullName + "." + 
                         Field.Name, Field.GetValue(Target));
            }
            catch { }
        }
        private void SaveSerializedData(Array Target, string Caller)
        {
            try
            {
                for (int j = 0; j < Target.Length; j++)
                {
                    if (Target.GetValue(j) != null)
                    {
                        Type ObjectType = Target.GetValue(j).GetType();
                        if (!ObjectType.IsPrimitive)
                        {
                            System.Reflection.FieldInfo[] ObjectFields = 
                                              ObjectType.GetFields();
                            System.Reflection.PropertyInfo[] ObjectProperties = 
                                              ObjectType.GetProperties();
                            for (int i = 0; i < ObjectFields.Length; i++)
                            {
                                fieldsToxml(ObjectFields[i], Target.GetValue(j));
                            }
                            for (int i = 0; i < ObjectProperties.Length; i++)
                            {
                                propertyToxml(ObjectProperties[i], Target.GetValue(j));
                            }
                        }
                        SaveData(Caller + "[" + j.ToString() + 
                                 "]", Target.GetValue(j));
                    }
                }
            }
            catch { }
        }
        private void propertyToxml(System.Reflection.PropertyInfo Property, object Target)
        {
            try
            {
                if (Property.CanWrite && Property.CanWrite)
                {
                    Type TargetProperty = Property.GetType();
                    System.Reflection.PropertyInfo[] TargetProperties = 
                                                     TargetProperty.GetProperties();
                    System.Reflection.FieldInfo[] TargetFieds = TargetProperty.GetFields();
                    for (int i = 0; i < TargetProperties.Length; i++)
                    {
                        propertyToxml(TargetProperties[i], Property.GetValue(Target, null));
                    }
                    for (int j = 0; j < TargetFieds.Length; j++)
                    {
                        fieldsToxml(TargetFieds[j], Property.GetValue(Target, null));
                    }
                    SaveData(Property.ReflectedType.FullName + "." + 
                             Property.Name, Property.GetValue(Target, null));
                }
            }
            catch { }
        }
        #endregion
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Babak Tajalli Nezhad
Web Developer Pooyanhost Corporation
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
I Have established my Own Company and providing services in Web Designing and Network Solutions.

Comments and Discussions

 
GeneralNice Code PinmemberMember 29678471-Nov-09 2:32 
GeneralOther Properties Pinmembersamerbadawi15-Apr-09 12:13 
Generalquestion PinmemberStephan Poelwijk15-Jun-08 6:12 
GeneralRe: question PinmemberBabak Tajalli Nezhad15-Jun-08 21:50 

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
Web04 | 2.8.140709.1 | Last Updated 15 Jun 2008
Article Copyright 2008 by Babak Tajalli Nezhad
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid