Modifying Serialization

Hi guys,

I managed to get a program which can do Serialization for me:

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21850587.html

But now I need to either modify it a bit, so that I can store endless records, rather than static amounts of data, or if someone could show me a better way of storing endless records in a binary file, that would be great.

Anyone able to help me out please?
LVL 4
Cyber-DrugsAsked:
Who is Participating?
 
2266180Connect With a Mentor Commented:
yep. the error was on my part:
Article[] articles=new articles[1]; was obviosly wrong. it should have been Article[] articles=new Article[1];

also change
class Article : ISerializable
to
public class Article : ISerializable

Here is the modified and working verision:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using ReadingWritingCustomBinaryFile;
using System.IO;

namespace WindowsApplication5
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.Button button2;
            private System.Windows.Forms.OpenFileDialog openFileDialog1;
            private System.Windows.Forms.SaveFileDialog saveFileDialog1;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.button1 = new System.Windows.Forms.Button();
                  this.button2 = new System.Windows.Forms.Button();
                  this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
                  this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
                  this.SuspendLayout();
                  //
                  // button1
                  //
                  this.button1.Location = new System.Drawing.Point(184, 80);
                  this.button1.Name = "button1";
                  this.button1.TabIndex = 0;
                  this.button1.Text = "button1";
                  this.button1.Click += new System.EventHandler(this.button1_Click);
                  //
                  // button2
                  //
                  this.button2.Location = new System.Drawing.Point(200, 144);
                  this.button2.Name = "button2";
                  this.button2.TabIndex = 1;
                  this.button2.Text = "button2";
                  this.button2.Click += new System.EventHandler(this.button2_Click);
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 266);
                  this.Controls.Add(this.button2);
                  this.Controls.Add(this.button1);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.Load += new System.EventHandler(this.Form1_Load);
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void Form1_Load(object sender, System.EventArgs e)
            {
            
            }

            private void button1_Click(object sender, System.EventArgs e)
            {
                  int i;
                  Article[] articles = new Article[1];
                  articles[0] = new Article();
                  articles[0].Author = "first author";
                  articles[0].Text = "some text";
                  articles[0].Title = "some title";
                  if (saveFileDialog1.ShowDialog() != DialogResult.OK)
                        return;
                  FileStream f = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite);
                  for (i=0; i<articles.Length; i++)
                  {
                        articles[i].Serialize(f);
                  }            
            }

            private void button2_Click(object sender, System.EventArgs e)
            {
                  if (openFileDialog1.ShowDialog() != DialogResult.OK)
                        return;
                  ArrayList articles = new ArrayList();
                  FileStream f = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                  while (f.Position<f.Length)
                  {
                        articles.Add(Article.Deserialize(f));
                  }
                  Article a = (Article)articles[0];
            }
      }
}


------------

using System;
//using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;

namespace ReadingWritingCustomBinaryFile
{
      [Serializable]
      class Article : ISerializable
      {
            // any Fields
            private string author = String.Empty;
            private string text = String.Empty;
            private string title = String.Empty;

            #region these 2 constructors is needed for the deserialization used by the formater
            public Article(SerializationInfo info, StreamingContext context)
            {
                  Title = info.GetValue("Title", typeof(string)).ToString();
                  Author = info.GetValue("Author", typeof(string)).ToString();
                  Text = info.GetValue("Text", typeof(string)).ToString();
            }

            public Article()
            {
                  //Empty Constructor
            }
            #endregion


            public string Author
            {
                  get { return author; }
                  set { author = value; }
            }

            public string Text
            {
                  get { return text; }
                  set { text = value; }
            }

            public string Title
            {
                  get { return title; }
                  set { title = value; }
            }


            #region this method is needed for Serializationused by the formater
            void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
            {
                  info.AddValue("Title", Title);
                  info.AddValue("Text", Text);
                  info.AddValue("Author", Author);
            }
            #endregion

            // to serialize this instance
            public void Serialize(string Filename)
            {
                  Stream s = null;
                  try
                  {
                        s = File.Open(Filename, FileMode.Create, FileAccess.ReadWrite);
                        BinaryFormatter b = new BinaryFormatter();
                        b.Serialize(s, this);
                  }
                  finally
                  {
                        s.Close();
                  }
            }

            public void Serialize(Stream s)
            {
                  try
                  {
                        BinaryFormatter b = new BinaryFormatter();
                        b.Serialize(s, this);
                  }
                  finally
                  {
                  }
            }

            // to deserialize from a file and return object
            public static Article Deserialize(string Filename)
            {
                  Stream s = null;
                  try
                  {
                        s = File.Open(Filename, FileMode.Open, FileAccess.Read);
                        BinaryFormatter b = new BinaryFormatter();
                        return (Article)b.Deserialize(s);
                  }
                  finally
                  {
                        s.Close();
                  }
            }

            public static Article Deserialize(Stream s)
            {
                  try
                  {
                        BinaryFormatter b = new BinaryFormatter();
                        return (Article)b.Deserialize(s);
                  }
                  finally
                  {
                  }
            }
      }
}

was compiled with VS2003 .NET FW 1.1
0
 
2266180Commented:
well .. something like this would do?

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ReadingWritingCustomBinaryFile
{
    [Serializable]
    class Article : ISerializable
    {
        // any Fields
        private string author = String.Empty;
        private string text = String.Empty;
        private string title = String.Empty;

#region these 2 constructors is needed for the deserialization used by the formater
        public Article(SerializationInfo info, StreamingContext context)
        {
            Title = info.GetValue("Title", typeof(string)).ToString();
            Author = info.GetValue("Author", typeof(string)).ToString();
            Text = info.GetValue("Text", typeof(string)).ToString();
        }

        public Article()
        {
            //Empty Constructor
        }
#endregion


        public string Author
        {
            get { return author; }
            set { author = value; }
        }

        public string Text
        {
            get { return text; }
            set { text = value; }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }


        #region this method is needed for Serializationused by the formater
        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Title", Title);
            info.AddValue("Text", Text);
            info.AddValue("Author", Author);
        }
        #endregion

        // to serialize this instance
        public void Serialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Create, FileAccess.ReadWrite);
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
                s.Close();
            }
        }

        public void Serialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
            }
        }

        // to deserialize from a file and return object
        public static Article Deserialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Open, FileAccess.Read);
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
                s.Close();
            }
        }

        public static Article Deserialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
            }
        }
    }
}

and using it would be something like:

create a list of articles
Article[] articles;
then
FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);
for (i=0; i<articles.lentgh; i++)
  articles[i].Serialize(f);
and loading:
for (i=0; i<articles.lentgh; i++)
  articles[i] = Article.Deserialize(f);


not tested but should work right out of the box (don't have a VS IDE handy)
0
 
Cyber-DrugsAuthor Commented:
About to test it, but before I do, is this correct?

FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);

Or did you mean to put...

FileStream f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);


?
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
2266180Commented:
the 2 lines look the same to me ...
0
 
Cyber-DrugsAuthor Commented:
Filestram

Filestream
0
 
2266180Commented:
oh. sorry :D you are right it was a typo. may bad.
0
 
Cyber-DrugsAuthor Commented:
OK, I get one error when I compile...


Use of unassigned local variable 'articles'
0
 
2266180Commented:
well  of ocurse, I just outlined the use of the variables. that was not a full implementation but a sketch.

here is a more complete example of use (still in a sketch form):

create a list of articles

save articles (you must create some. I will only create one)
Article[] articles=new articles[1];
articles[0] = new Article();
articles[0].Author = "first auth";
articles[0].Text = "some text";
articles[0].Title = "some title";
FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);
for (i=0; i<articles.lentgh; i++)
  articles[i].Serialize(f);

and loading:
using System.Collenctions;
ArrayList articles = new ArrayList;
FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.Read);
while (f.Position<f.Length)//some EOF like check
  articles.add(Article.Deserialize(f));

to access an element from the arraylist, you just do a cast like:
Article article = (Article)articles.Itme[0];

you should be able to compile this and run it (after integrating it in your test app). the code might conatin typos. Sorry if there are any.
0
 
Cyber-DrugsAuthor Commented:
Still getting one error:

Error      1      The type or namespace name 'articles' could not be found (are you missing a using directive or an assembly reference?)      C:\Documents and Settings\Justin Nel\My Documents\Visual Studio 2005\Projects\CustomFile\CustomFile\Form1.cs      57      38      CustomFile


Sorry for the slow reply, had a busy day in the office today.
0
 
2266180Commented:
I am sure you forgot to copy something as in my examples (both of them) articles is defined. in the first one as an array of Article and in the second as an ArrayList. check your code. alternativly, post it here so we can see it
0
 
Cyber-DrugsAuthor Commented:
I checked, but I couldn't see the problem, so here is what I have in the code so far....


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections;

namespace ReadingWritingCustomBinaryFile
{
    [Serializable]
    class Article : ISerializable
    {
        // any Fields
        private string author = String.Empty;
        private string text = String.Empty;
        private string title = String.Empty;

        #region these 2 constructors is needed for the deserialization used by the formater
        public Article(SerializationInfo info, StreamingContext context)
        {
            Title = info.GetValue("Title", typeof(string)).ToString();
            Author = info.GetValue("Author", typeof(string)).ToString();
            Text = info.GetValue("Text", typeof(string)).ToString();
        }

        public Article()
        {
            //Empty Constructor
        }
        #endregion


        public string Author
        {
            get { return author; }
            set { author = value; }
        }

        public string Text
        {
            get { return text; }
            set { text = value; }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }


        #region this method is needed for Serializationused by the formater
        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Title", Title);
            info.AddValue("Text", Text);
            info.AddValue("Author", Author);
        }
        #endregion

        // to serialize this instance
        public void Serialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Create, FileAccess.ReadWrite);
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
                s.Close();
            }
        }

        public void Serialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
            }
        }

        // to deserialize from a file and return object
        public static Article Deserialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Open, FileAccess.Read);
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
                s.Close();
            }
        }

        public static Article Deserialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
            }
        }
    }
}









and on the form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ReadingWritingCustomBinaryFile;
using System.IO;
using System.Collections;

namespace CustomFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Article CurrentArticle = new Article();

        private void btnSerialize_Click(object sender, EventArgs e)
        {
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SaveArticle();
                CurrentArticle.Serialize(this.saveFileDialog1.FileName);
            }
        }

        private void btnDeserialize_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                CurrentArticle = Article.Deserialize(this.openFileDialog1.FileName);
                LoadArticle();
            }
        }

        private void LoadArticle()
        {
            txtAuthor.Text = CurrentArticle.Author;
            txtText.Text = CurrentArticle.Text;
            txtTitle.Text = CurrentArticle.Title;
        }

        private void SaveArticle()
        {
            CurrentArticle.Author = txtAuthor.Text;
            CurrentArticle.Text = txtText.Text;
            CurrentArticle.Title = txtTitle.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int i;
            Article[] articles = new articles[1];
            articles[0] = new Article();
            articles[0].Author = "first author";
            articles[0].Text = "some text";
            articles[0].Title = "some title";
            FileStream f = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite);
            for (i=0; i<articles.Length; i++)
            {
                articles[i].Serialize(f);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ArrayList articles = new ArrayList;
            FileStream f = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
            while (f.Position<f.Length)
            {
                articles.Add(Article.Deserialize(f));
            }
        }
    }
}
0
 
Cyber-DrugsAuthor Commented:
Works absolutely beautifully!!!

Thank you VERY much!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.