Nevron Chart
Skip Navigation Links
Home
Forum Home
Latest 50
Unanswered
Win Prizes
All Time Leaders
Jump to CategoryExpand Jump to Category
Login 
    Welcome Guest!
 Search Forum For :  
X
 Login
Please login to submit a new post, reply and edit exiting posts, see user profiles, and access more features. If you are not a registered member, Register here.
User Id / Email:
Password:  
Forgot Password | Forgot UserName
   Home » C# Language » Serialization, Deserialization Exception
       
Author Reply
Jessica Green
posted 5 posts
since Apr 30, 2008 
from

 Serialization, Deserialization Exception
  Posted on: 30 Apr 2008       
I have to make this assignment:
Visit this link for the JPG of the assignment so you know what exactly I'm supposed to do..

http://i25.tinypic.com/21owwg5.jpg

I've done much of the program but I keep getting an unhandled exception when i run it.

Here's the code:


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

namespace HomeWork_2
{
    public abstract class Person
    {
        public abstract string Name { set; get; }
        public abstract string PhoneNumber { set; get; }
        public virtual void PrintInfo() { ;}
    }

    class PersonInfo : Person
    {
        private string personName;
        private string phoneNumber;

        public PersonInfo() { }

        public override string Name
        {
            set
            {
                personName = value;
            }
            get
            {
                return personName;
            }
        }

        public override string PhoneNumber
        {
            set
            {
                phoneNumber = value;
            }
            get
            {
                return phoneNumber;
            }
        }

        public override void PrintInfo()
        {
            Console.WriteLine("Name: {0} \nPhoneNumber: {1}", personName, PhoneNumber);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            bool quit = false;
            PersonInfo empInfo = new PersonInfo();
            PersonInfo[] info = new PersonInfo[10];

            try
            {
                using (Stream input = File.OpenRead("membership.dat"))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    info = (PersonInfo[])bf.Deserialize(input);
                }
            }
            catch (FileNotFoundException)
            {
            }

            while (!quit)
            {
                Console.Write("   Main Menu\n\t(1) Add \n\t(2) Search \n\t(3) Print All \n\t(4) Exit\n\t-> ");
                int option = Int32.Parse(Console.ReadLine());
               
                switch (option)
                {
                    case 1:
                        Console.Write("\nEnter Employee name: ");
                        empInfo.Name = Console.ReadLine();

                        Console.Write("\nEnter the employee's phone #: ");
                        empInfo.PhoneNumber = Console.ReadLine();

                        break;

                    case 2:
                        Console.WriteLine("Enter the name of the employee whose record you want to find\n-> ");
                        empInfo.Name = Console.ReadLine();

                        if (empInfo.Equals(empInfo))
                        {
                            Console.WriteLine("Record Found");
                        }
                        else
                            Console.WriteLine("Record not found...");
                        break;

                    case 3:
                        break;

                    case 4:
                        using (Stream output = File.Create("membership.dat"))
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            formatter.Serialize(output, empInfo);
                        }
                        quit = true;
                        break;
                }

            }
        }
    }
}

Scott Lysle
posted  751 posts
since  Dec 16, 2005 
from 

Re: Serialization, Deserialization Exception
  Posted on: 30 Apr 2008      0 0    

Well, for the issue you are discussing in this post, you need to mark your classes as serializable (e.g.):

[Serializable]
public abstract class Person
{

To avoid the unhandled exception, put the code into a try catch block.

using (Stream output = File.Create(@"c:\Temp\membership.dat"))
{
   try
   {
      BinaryFormatter formatter = new BinaryFormatter();
      formatter.Serialize(output, empInfo);
   }
   catch (Exception ex)
   {
      Console.Write(ex.Message);
      Console.ReadLine();
   }
}

 

slysle
Jessica Green
posted  5 posts
since  Apr 30, 2008 
from 

Re: Serialization, Deserialization Exception
  Posted on: 01 May 2008      0 0    
Thanks 4 the helpul reply...
I hope I'm not asking too much but can you look at the jpg picture I posted about the assignment I have to do.. I don't think I"m doing it right..

Thanks...

Jessica Green
posted  5 posts
since  Apr 30, 2008 
from 

Re: Serialization, Deserialization Exception
  Posted on: 01 May 2008      0 0    
I'm stuck
I really don't know how to load (serialize) the Personal Information data from a file called “membership.dat” into the array of objects PersonInfo.

&

At the end of the program serialize the array of PersonInfo objects into the file “membership.dat”.

I don't understand how to load and write with arrays...
Please Help.. Thanks..
Jessica Green
posted  5 posts
since  Apr 30, 2008 
from 

Re: Serialization, Deserialization Exception
  Posted on: 01 May 2008      0 0    
Anyone ????
Brandon Lewis
posted  234 posts
since  Oct 31, 2006 
from  Illinois

Re: Serialization, Deserialization Exception
  Posted on: 02 May 2008      0 0    
Lots of stuff wrong :( But its ok, it happens. The object you are serializing to the membership.dat file is not an array. Ive gone ahead and fixed up alot of the stuff that you were having issues with and Ill explain it with comments.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

namespace HomeWork_2
{
    //Mark these classes as
    //serializable so they can
    //be serialized to the file.

    [Serializable]
    public abstract class Person
    {
        public abstract string Name { get; set; }
        public abstract string PhoneNumber { get; set; }
        public virtual void PrintInfo() { }
    }

    //You could also have used an
    //interface for this
    //not sure why an empty abstract
    //class was used.

    public interface IPerson
    {
        string Name
        {
            get;
            set;
        }

        string PhoneNumber
        {
            get;
            set;
        }

        void PrintInfo();
    }

    [Serializable]
    public class PersonInfo : Person
    {
        //Always try to initialize variables
        //with something to avoid null values.
        private string name = String.Empty;
        private string phoneNumber = String.Empty;

        public PersonInfo()
        {

        }

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

        public override string PhoneNumber
        {
            get { return this.phoneNumber; }
            set { this.phoneNumber = value; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Create the list to store
            //person info in and the
            //binary formatter to serialize
            //and deserialize it to the file.

            List<PersonInfo> personInfoList = new
              
List<PersonInfo>(10);

            //You may want to read up on
            //generics a bit

            BinaryFormatter binaryFormatter = new BinaryFormatter();

            try
            {
                //Create a filestream object
                //to check the length of the
                //file before attempting to
                //deserialize.

                using (FileStream fileStream = new FileStream("membership.dat", FileMode.OpenOrCreate, FileAccess.Read))
                {
                    if (fileStream.Length > 0)
                    {
                        //If there is data to
                        //deserialize, then
                        //deserialize it and cast
                        //it to the personInfoList
                        //object

                        personInfoList = (List<PersonInfo>)binaryFormatter.Deserialize(fileStream);
                    }
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine("Unable to access membership.dat file. {0}.", ex.Message);
            }
            catch (Exception ex)
            {
                //This generally isnt a good
                //idea, but its a catch all for now

                Console.WriteLine(ex.Message);
            }

            //Prime the while loop
            bool quit = false;

            while (!quit)
            {
                //Display the menu
                Console.Write("   Main Menu\n\t(a) Add \n\t(b) Search \n\t(c) Print All \n\t(d) Exit\n\t-> ");

                //Create a char variable to
                //contain the entered character
                //from the command prompt.

                char selectionChar;

                //Attempt to parse the input.
                //If it succeeds, continue with processing.

                if (Char.TryParse(Console.ReadLine(),
                       out selectionChar))
                {
                    switch (selectionChar)
                    {
                        case 'a':

                            //Create a new person info object.
                            PersonInfo personInfo = new PersonInfo();

                            //Request the employees name
                            Console.Write("\nEnter Employee name: ");
                            personInfo.Name = Console.ReadLine();

                            //Request the employees phone number
                            Console.Write("\nEnter the employee's phone #: ");
                            personInfo.PhoneNumber = Console.ReadLine();

                            //Add a new employee to the list here
                            personInfoList.Add(personInfo);
                            break;

                        case 'b':

                            //Get the name to search for
                            Console.WriteLine("Enter the name of the employee whose record you want to find\n-> ");
                            string queryEmpName = Console.ReadLine();

                            //Set a variable for checking later
                            bool foundPerson = false;

                            //Iterate through the list of persons and look for the person with the supplied name.
                            for (int i = 0; i < personInfoList.Count; i++)
                            {
                                //If the person is found...
                                if (personInfoList[i].Name == queryEmpName)
                                {
                                    //Let the user know and break from the loop.
                                    Console.WriteLine("Found! Name: {0} with phone number {1}", personInfoList[i].Name, personInfoList[i].PhoneNumber);
                                    foundPerson = true;
                                    break;
                                }

                                //If the person is not found, the loop continues until all of the persons have been checked.

                            }

                            //If the person was not found, display a message letting the user know.
                            if (!foundPerson)
                            {
                                //Let the user know that the person was not found.
                                Console.WriteLine("The employee with name {0} was not found.", queryEmpName);
                            }
                            break;

                        case 'c':

                            //Iterate through the list of persons and display their information.
                            for (int i = 0; i < personInfoList.Count; i++)
                            {
                                //Display each persons information.
                                Console.WriteLine("{0} - Name: {1} Phone Number: {2}", /*Up i by one because arrays are zero indexed.*/ (i + 1).ToString(), personInfoList[i].Name, personInfoList[i].PhoneNumber);
                            }

                            break;
                        case 'd':
                            try
                            {
                                //Create a file stream object to serialize the data to.
                                using (FileStream fileStream = new FileStream("membership.dat", FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    binaryFormatter.Serialize(fileStream, personInfoList);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);

                                //Pause the console so the message can be read.
                                Console.ReadLine();
                            }
                            finally
                            {
                                //Set the quit variable so the loop will exit.
                                quit = true;
                            }
                            break;
                        default:
                            Console.WriteLine("Invalid selection entered.");
                            break;
                    }
                }
                else   //If the input couldnt be parsed, display an error.
                {
                    Console.WriteLine("Invalid selection entered");
                }
            }
        }
    }
}
//--------------
//-NO MORE CODE-
//--------------

So basically, when you load it, it will display a menu asking you for a choice. If you enter a lowercase letter a - d it will continue processing but anything else and it will prompt for and let you know you input something invalid. It will then let you make another choice.

Generic collections, as I have used in the collection of PersonInfo objects, are really a nice thing. Theyre easier to work with than raw arrays and they dynamically resize themselves rather than having a set size all the time much like an array. Generics are much more useful than just using in collection classes too.

As well as being easier to work with, the generic List class (denotated as List<Type>) where Type is the type of object you wish to store in the strongly typed collection. This works much better than the ArrayList class (which I havent used for quite some time due to me liking type safety) but when you create a generic List collection, you can only store objects of the type you have specified in it. In later learning, you will probably come across interfaces and base classes where you will be able to store any object that implements an particular interface or base class and such... But that might be awhile, lol.

Some examples...
List<string> //A generic collection of strings
List<int> //A generic collection of integer values
List<MyClass> //A generic collection of class objects
List<IMyInterface> //A generic collection of interface objects


I commented alot of the code to help you figure out what was going on instead of just giving you the code, so if you wanna learn, check my comments and go through the code and try to figure it out for yourself.

The whole issue with your serialization/deserialization was that you were serializing objects of type PersonInfo to the file, but you were attempting to deserialize objects of type PersonInfo[] which was giving you an exception. Just check it out, and be sure to go through it because thats how you learn and if you have any questions at all, feel free to ask. I tend to talk about, but I always figure I can never do enough explaining of a concept :) More always helps.
Making it work is easy.
Making it work well is the tough part.

I saw Billy Maise on the TV the other day. He was all "Dude! When I first saw this product I nearly peed my pants! BUY IT NOW!!!"  -Me
Jessica Green
posted  5 posts
since  Apr 30, 2008 
from 

Re: Serialization, Deserialization Exception
  Posted on: 02 May 2008      0 0    

Thank you very much 4 helping me out on this I really appreciate the time you put into explaining it as well it really helped me out a lot. A simple thanks cannot explain my gratitude but that's all i can offer so thanks again...

Jessica

       
Sponsored by
Become a Sponsor
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Unlimited Access to 10,000 Tech Books & Videos, 15 Days, $0
Unlimited Access to 10,000 Tech Books & Videos, 15 Days, $0
Top Microsoft Certification Books & Videos, 15 Days, $0
Top Microsoft Certification Books & Videos, 15 Days, $0

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Advertise with us
Current Version: 3.2009.8.27
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved