Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 880
  • Last Modified:

Serialize objects c#

I am writing a spec for a project tracking system in c#.

A project consists of many tasks, ideally these tasks need to be automatically created when the project is created in the software application.

I have a project class and a task class.

I was thinking of storing the "auto-generated" tasks in a database table "tblAutoTasks".  

However I have been tasked to try and serialize these tasks as part of the project class.  For example when I create a project, a generic collection is created holding these tasks.  Does any of this make sense?  Any pointers would be appreciated.
0
EugeneC
Asked:
EugeneC
  • 2
  • 2
1 Solution
 
2266180Commented:
Hi,

here are some examples with explanation on serialization:
http://www.codeproject.com/csharp/objserial.asp
http://www.c-sharpcorner.com/Language/serializingObjectsinCS.asp
You can find more info on the net if you need specific stuff (like serialization to xml or other format)

You will probably need to save the resulting serializaed data either in a blob like field (if your serialized objects are huge) or an array of bytes. (varchar) in your speific case, I dont think that a task could grow big enough to cause problems if stored in a varchar.
0
 
EugeneCAuthor Commented:
Hi

Thanks for that, could you provide me with an example?


All I need is a quick example of a project class that when created serializes a set of tasks.
0
 
2266180Commented:
the codeproject link comes with demo source code.
for you're case, you will have to modify the task class and add a  [Serializable()] to it
0
 
gbzhhuCommented:
This is stright from my project

namespace HGCA.Benchmark.Objects
{
#region Using directives
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;    
#endregion

/// <summary>
/// Abstract base class for all objects that require deep copying
/// </summary>
[Serializable]
public abstract class BenchmarkBase: ICloneable
{
      #region Constractor
      public BenchmarkBase()
      {
      }
      #endregion

      #region IClonable implementation
      /// <summary>
      /// Clone deep copy
      /// </summary
      public object Clone(bool doDeepCopy)
      {
            if (doDeepCopy)
            {
                  BinaryFormatter BF = new BinaryFormatter();
                  MemoryStream memStream = new MemoryStream();
                  BF.Serialize(memStream, this);
                  memStream.Flush();
                  memStream.Position = 0;
                  return (BF.Deserialize(memStream));
            }
            else
            {
                  return (this.MemberwiseClone());
            }
      }
            
      public object Clone()
      {
            return (Clone(true));
      }
      #endregion
}
}


using System;
using System.Xml.Serialization;
 
namespace HGCA.Benchmark.Objects
{
      /// <summary>
      /// Represents a crop, if we eventually have crops with different functionalities we will inherit this class
      /// </summary>
      [Serializable]
      public class CropBase: BenchmarkBase
      {
            public CropBase()
            {

            }

            /// <summary>
            /// Name of the crop
            /// </summary>
            private string name;
            private decimal ha;

            public string Name
            {
                  get
                  {
                        return name;
                  }
                  set
                  {
                        name = value;
                  }
            }

            public decimal Ha
            {
                  get
                  {
                        return ha;
                  }
                  set
                  {
                        ha = value;
                  }
            }


      }
}


THIS ONE IS RATHER BIG BUT YOU CAN EXTRACT THE CODE RELEVANT TO YOUR PROJECT  (FOR EXAMPLE SERIALIZING THE ARRAYLIST)

namespace HGCA.Benchmark.Objects
{
      #region Using Directives
      using System;
      using System.Collections;
      using System.Collections.Specialized;
      using System.IO;
      using System.Xml.Serialization;  
      #endregion

      /// <summary>
      ///  Base object for all benchmarks.
      /// </summary>
      [Serializable]
      [System.Xml.Serialization.XmlInclude( typeof( CropBase ) )]      
      public class Benchmark: BenchmarkBase
      {
            public Benchmark()
            {
                  this.CreatedDate = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
            }            
            #region Private Members
            private int  harvestYear;
            private ArrayList crops = new ArrayList();
            private string groupId = string.Empty;
            private int reportId;
            private bool hasBeensubmitted = false;
            private string createdDate = string.Empty;
            private string lastSavedDate = string.Empty;
            private string saveFile = string.Empty;
            private string comments = string.Empty;
            #endregion

            #region Public Properties
            /// <summary>
            /// Gets or sets the harvest year.
            /// </summary>
            public int HarvestYear
            {
                  get { return this.harvestYear; }
                  set { this.harvestYear = value; }
            }
            /// <summary>
            /// Gets or sets the crops collection in the benchmark.
            /// </summary>
            [XmlArrayItem(ElementName= "Crop", IsNullable=false, Type = typeof(CropBase), Namespace = "http://www.hgca.com")]
            [XmlArray(ElementName= "Crops")]
            public ArrayList Crops
            {
                  get { return this.crops; }
                  set { this.crops = value; }
            }            
            /// <summary>
            /// Gets or sets the ID of the group that the benchmark should be group with.
            /// </summary>
            public string GroupID
            {
                  get { return this.groupId; }
                  set { this.groupId = value; }
            }
            /// <summary>
            /// Gets or sets the report ID assigned when the benchmark is submitted.
            /// </summary>
            public int ReportID
            {
                  get { return this.reportId; }
                  set { this.reportId = value; }
            }
            /// <summary>
            /// Gets or sets whether the benchmark has been submitted.
            /// </summary>
            public bool HasBeenSubmitted
            {
                  get { return this.hasBeensubmitted; }
                  set { this.hasBeensubmitted = value; }
            }
            /// <summary>
            /// Gets or sets the date the benchmark was created.
            /// </summary>
            public string CreatedDate
            {
                  get { return this.createdDate; }
                  set { this.createdDate = value; }
            }
            /// <summary>
            /// Gets or sets the date the benchmark was last saved.
            /// </summary>
            public string SavedDate
            {
                  get { return this.lastSavedDate; }
                  set { this.lastSavedDate = value; }
            }
            /// <summary>
            /// Gets the file path and name of the file the benchmark is saved to.
            /// </summary>
            public string SaveFile
            {
                  get { return this.saveFile; }
                  set { this.saveFile = value; }
            }
            /// <summary>
            /// Gets or sets any comments for the benchmark.
            /// </summary>
            public string Comments
            {
                  get { return this.comments; }
                  set { this.comments = value; }
            }
            #endregion

            #region Public Methods
            /// <summary>
            /// Saves the benchmark data by serializing the object to an Xml file.
            /// </summary>
            /// <returns>True on success, else false</returns>
            public bool Save()
            {
                  bool saved = false;
                  StreamWriter file = null;

                  try
                  {
                        // Serialize the object to Xml.
                        XmlSerializer writer = new XmlSerializer(this.GetType());
                        // Set the path and name of the file to save to.
                        if (this.saveFile.Length == 0)
                        {
                              this.saveFile = Common.UserDataPath + Common.BenchmarkFilePrefix + DateTime.Now.ToFileTime().ToString() + ".Xml";
                        }

                        file = new StreamWriter(this.saveFile);

                        // Set the last saved date.
                        this.SavedDate = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
                        // Write the serialized object out to a file.
                        writer.Serialize(file, this);
                        saved = true;
                  }
                  catch (Exception ex)
                  {
                        saved = false;
                        ExceptionManager exception = new ExceptionManager();
                        exception.LogException(ex);
                  }
                  finally
                  {
                        if (file != null)
                        {
                              // Make sure we always close the file.
                              file.Close();
                        }
                  }

                  return saved;
            }

            /// <summary>
            /// Checks if the user has already submitted a benchmark to HGCA for the
            /// current harvest year. Only one benchmark can be submitted per harvest year.
            /// </summary>
            /// <returns>True if the benchmark can be submitted, else false</returns>
            public bool CanSubmit()
            {
                  bool canSubmit = true;
                  Benchmark benchmark = new Benchmark();

                  // Get a list of save files.
                  string[] saveFiles = Benchmark.GetSaveFiles();

                  // Loop over the saved files and check the harvest year and submit flag.
                  foreach (string file in saveFiles)
                  {
                        benchmark = Benchmark.Load(file);
                        if (benchmark.HasBeenSubmitted)
                        {
                              if (benchmark.HarvestYear == this.HarvestYear)
                              {
                                    canSubmit = false;
                              }
                        }
                  }

                  benchmark = null;
                  return canSubmit;
            }
            /// <summary>
            /// Loads benchmark data from the specified Xml file.
            /// </summary>
            /// <param name="filePath">Path and name of the Xml file to load</param>
            /// <returns>Benchmark object that was deserialized from the specified Xml file</returns>
            public static Benchmark Load(string filePath)
            {
                  Benchmark loaded = new Benchmark();
                  StreamReader file = null;

                  try
                  {
                        XmlSerializer reader = new XmlSerializer(loaded.GetType());
                        // Read the XML file.
                        file = new StreamReader(filePath);
                        // Deserialise the object.
                        loaded = (Benchmark)reader.Deserialize(file);
                        loaded.saveFile = filePath;
                  }
                  catch (Exception ex)
                  {
                        ExceptionManager exception = new ExceptionManager();
                        exception.LogException(ex);
                  }
                  finally
                  {
                        if (file != null)
                        {
                              file.Close();
                        }            
                  }

                  return loaded;
            }

            /// <summary>
            /// Returns an array of benchmark save files of the processing enterprise type.
            /// </summary>
            /// <returns>Array of file paths and names</returns>
            public static string[] GetSaveFiles()
            {
                  ArrayList files = new ArrayList();
                  string[] fileList;

                  try
                  {
                        // Get information for the data directory.
                        DirectoryInfo dirInfo = new DirectoryInfo(Common.UserDataPath);

                        foreach (FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
                        {
                              // Check we are working with a file (could be a directory).
                              if (fsi is FileInfo)
                              {
                                    if (fsi.Name.StartsWith(Common.BenchmarkFilePrefix))
                                    {
                                          // Add the file to our list.
                                          files.Add(fsi.FullName);
                                    }
                              }
                        }

                        fileList = new string[files.Count];
                        files.CopyTo(fileList);
                        return fileList;
                  }
                  catch (Exception ex)
                  {
                        ExceptionManager exception = new ExceptionManager();
                        exception.LogException(ex);
                        return new string[0];
                  }
            }
            #endregion
      }
}

0
 
EugeneCAuthor Commented:
Thanks a lot for your replies - currently I am on holiday and will be back at the end of the month - I look forward to trying your suggestions and will keep you informed.  
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now