?
Solved

Modifying Serialization

Posted on 2006-05-22
12
Medium Priority
?
313 Views
Last Modified: 2010-04-16
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?
0
Comment
Question by:Cyber-Drugs
  • 6
  • 6
12 Comments
 
LVL 28

Expert Comment

by:2266180
ID: 16733020
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
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 16733059
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
 
LVL 28

Expert Comment

by:2266180
ID: 16733123
the 2 lines look the same to me ...
0
Industry Leaders: 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!

 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 16733777
Filestram

Filestream
0
 
LVL 28

Expert Comment

by:2266180
ID: 16734274
oh. sorry :D you are right it was a typo. may bad.
0
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 16735943
OK, I get one error when I compile...


Use of unassigned local variable 'articles'
0
 
LVL 28

Expert Comment

by:2266180
ID: 16737898
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
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 16746174
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
 
LVL 28

Expert Comment

by:2266180
ID: 16748841
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
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 16749502
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
 
LVL 28

Accepted Solution

by:
2266180 earned 2000 total points
ID: 16749752
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
 
LVL 4

Author Comment

by:Cyber-Drugs
ID: 16755332
Works absolutely beautifully!!!

Thank you VERY much!
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
Suggested Courses

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question