13 Replies - 1414 Views - Last Post: 17 December 2012 - 10:18 AM Rate Topic: -----

#1 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Working with Serialization

Posted 15 December 2012 - 04:03 PM

Well I was working on a project for my class that was a simple Banking Application, but (long story short) I am having to start over due to the flash drive the project was on being destroyed. I've decided to do something really basic, since we only have a fairly small and simple list of requirements to meet. But I'm stuck on the issue of saving everything. Right now, I'm just using an abstract class called Vehicle as the base for everything, followed by an Automobile Class from which most of the other Classes inherit from (Sports Car inherits from Car however). It's a simple project with each form for making a new car of the selected type having text boxes to collect the input, passed through constructors, and creating an object that is added to the Listbox on the main form. I'm guessing that logically, when it's tested for grading, several objects will be made. I've been reading on my options as far as saving these go, and without knowing how many of which objects will be created, it sounds like I should just make it so anything that is created and added to the listbox is also added to a list to keep track of everything I want to save. The problem is I've read a few tutorials on it, and I can't seem to get it nailed down. We have covered nothing on this subject, and frankly, if anyone knows of a better/easier way to be able to save all the objects to a file and load them back that doesn't involve serialization, I'd much rather do that. The tutorials I found were for the most part very good, but lacking in how they describe the layout of the code. (what code belongs where type of thing)

the following is my entire VehicleClass.cs file that I'm using.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AlfordScottFinalProgrammingProject
{
    public class VehicleClass
    {
        // Abstract Class
        public abstract class Vehicle
        {
            // Abstract Property
            public int Year
            {
                get;
                set;
            }

            // Abstract Method
            public virtual void StartVehicle()
            {
                
            }
        }

        // Base Class
        public class Automobile : Vehicle
        {
            // Fields
            public int _year;
            public string _make;
            public string _model;
            public string _color;

            // Default Constructor
            public Automobile()
            {

            }

            // Constructor
            public Automobile(int year, string make, string model, string color)
            {
                _year = year;
                _make = make;
                _model = model;
                _color = color;
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Override StartVehicle Method
            public override void StartVehicle()
            {
                MessageBox.Show("Automobile Started.");
            }

            // Drive Method
            public void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Automobile.");
            }

            // Park Method
            public void Park()
            {
                MessageBox.Show("Parked the Automobile in the driveway");
            }

            // Wash Method
            public void Wash()
            {
                MessageBox.Show("Washed the Automobile. Looks Great!");
            }
        }

        public class Car : Automobile
        {
            // Fields
            private int _doors;
            
            // Default Constructor
            public Car()
            {

            }

            // Constructor
            public Car(int year, string make, string model, string color, int doors) : base (year, make, model, color) 
            {
                _doors = 2;
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }

            // Override StartVehicle Method
            public override void StartVehicle()
            {
                MessageBox.Show("Car Started. It's Quiet!");
            }

            // Drive Car Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Car.");
            }

            // Park Car Method
            public new void Park()
            {
                MessageBox.Show("Parked the Car in the driveway");
            }

            // Wash Car Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Car. Looks Great!");
            }
        }

        public class SportsCar : Car
        {
            // Fields
            private int _doors;
            
            // Constructor
            public SportsCar(int year, string make, string model, string color, int doors) : base (year, make, model, color, doors)
            {
                _doors = 2;
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public new int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }

            // Override StartVehicle Method
            public override void StartVehicle()
            {
                MessageBox.Show("Sports Car Started. It's Loud!");
            }

            // Drive Sports Car Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Sports Car.");
            }

            // Park Sports Car Method
            public new void Park()
            {
                MessageBox.Show("Parked the Sports Car in the driveway");
            }

            // Wash Sports Car Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Sports Car. Looks Great!");
            }
        }

        public class Truck : Automobile
        {
            // Field
            private int _doors;
            private string _driveType;
            

            // Constructor
            public Truck(int year, string make, string model, string color, int doors, string driveType)
                : base(year, make, model, color)
            {
                _driveType = "";
                _doors = 2;
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }

            // Drive Type Property
            public string Type
            {
                get { return _driveType; }
                set { _driveType = value; }
            }

            // Override StartVehicle Method
            public override void StartVehicle()
            {
                MessageBox.Show("Truck Started. It's Loud!");
            }

            // Drive Truck Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Truck.");
            }

            // Park Truck Method
            public new void Park()
            {
                MessageBox.Show("Parked the Truck in the driveway");
            }

            // Wash Truck Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Truck. Looks Great!");
            }
        }

        public class MiniVan : Automobile
        {
            // Fields
            public int _doors;
            public int _passengers;

            // Constructor
            public MiniVan(int year, string make, string model, string color, int passengers)
                : base(year, make, model, color)
            {
                _doors = 3;
                _passengers = 7;
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }
            // Passengers Property
            public int Passengers
            {
                get { return _passengers; }
                set { _passengers = value; }
            }

            // Override StartVehicle Method
            public override void StartVehicle()
            {
                MessageBox.Show("Minivan Started. It's Quiet!");
            }

            // Drive Minivan Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Minivan.");
            }

            // Park Minivan Method
            public new void Park()
            {
                MessageBox.Show("Parked the Minivan in the driveway");
            }

            // Wash Minivan Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Minivan. Looks Great!");
            }
        }
    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: Working with Serialization

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Working with Serialization

Posted 15 December 2012 - 06:48 PM

I'd go with the serialization.

Separating data from GUI - PLUS - serializing the data to XML
Was This Post Helpful? 1
  • +
  • -

#3 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 15 December 2012 - 07:31 PM

View PosttlhIn`toq, on 16 December 2012 - 01:48 AM, said:




So if I'm understanding correctly, I don't have to do anything special to my existing class file? Simply create a new class file to hold the serialization code, and then pass my list of cars to it? Do you happen to have anything on the back end as well? (deserializing to "load" from the file you save to?)
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Working with Serialization

Posted 16 December 2012 - 08:04 AM

See response #20 (on page 2) - it was pointed out earlier that there was no deserialize code but it was too late to alter the article so I put it in a post.
Was This Post Helpful? 1
  • +
  • -

#5 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 16 December 2012 - 09:50 AM

View PosttlhIn`toq, on 16 December 2012 - 03:04 PM, said:

See response #20 (on page 2) - it was pointed out earlier that there was no deserialize code but it was too late to alter the article so I put it in a post.


Thanks
Was This Post Helpful? 0
  • +
  • -

#6 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 16 December 2012 - 11:46 AM

Okay so I thought I adapted it correctly, but I'm getting an exception on x.Serialize. The exception is InvalidOperationException. The XML file does get created, but it's empty. And I'm using a list of cars called MyCars to store everything inside the main form by the way.

          string SavePath = @"C:\CarFile\";
          System.IO.Directory.CreateDirectory(SavePath);
          if (!System.IO.Directory.Exists(SavePath))
          {
              MessageBox.Show("Please check permissions");
          }
          else
          {
              SavePath += ("My_Car_File");
              SavePath = System.IO.Path.ChangeExtension(SavePath, ".xml");
              System.IO.File.Delete(SavePath);
              object carFile = MyCars;
              var x = new System.Xml.Serialization.XmlSerializer(carFile.GetType());
              using (var sw = new StreamWriter(SavePath, false))
              {
                 x.Serialize(sw, carFile);
              }
          }


Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Working with Serialization

Posted 16 December 2012 - 12:37 PM

Quote

The exception is InvalidOperationException.

Where? What line?

Quote

11
    System.IO.File.Delete(SavePath);


You might like to make this
if (System.IO.File.Exists(SavePath) System.IO.File.Delete(SavePath);

So you don't try to delete a file that doesn't yet exist.

Did you tag your Car class with the [SERIALIZABLE] attribute? If that's not it, let's see your current code.
Was This Post Helpful? 2
  • +
  • -

#8 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 16 December 2012 - 01:03 PM

Yes, I made sure the Car class has the serial tag, and I took a screen shot of the Exception. Below is all the code needed I believe

//Main.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AlfordScottFinalProgrammingProject
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        //Fields
        public int numOfvehicles = 0;
        public string[] vehicle = new string[8];
        public List<VehicleClass.Vehicle> MyCars = new List<VehicleClass.Vehicle>();
        public VehicleClass.Car car = new VehicleClass.Car();
        public VehicleClass.SportsCar sportscar = new VehicleClass.SportsCar();
        public VehicleClass.Truck truck = new VehicleClass.Truck();
        public VehicleClass.MiniVan minivan = new VehicleClass.MiniVan();
        public bool isCar = false;
        public bool isSportsCar = false;
        public bool isTruck = false;
        public bool isMiniVan = false;

        // Save File Element
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string SavePath = @"C:\CarFile\";
	        System.IO.Directory.CreateDirectory(SavePath);
	        if (!System.IO.Directory.Exists(SavePath))
	        {
                MessageBox.Show("Please check permissions");
	        }
            else
	        {
                SavePath += ("My_Car_File");
                SavePath = System.IO.Path.ChangeExtension(SavePath, ".xml");
	            if (System.IO.File.Exists(SavePath))
                System.IO.File.Delete(SavePath);
                object carFile = MyCars;
	            var x = new System.Xml.Serialization.XmlSerializer(carFile.GetType());
	            using (var sw = new StreamWriter(SavePath, false))
	            {
                    x.Serialize(sw, carFile);
	            }
            }
        }

        // Load File Element
        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            DialogResult dr = ofd.ShowDialog();
            if (dr != DialogResult.OK) return;
            var x = new System.Xml.Serialization.XmlSerializer(typeof(VehicleClass));
            using (var sw = new StreamReader(ofd.FileName))
            {
                object o = x.Deserialize(sw);
                //Main newMain  = new Main { lsbCars = (MyCars)o };
                //newMain.Show();
            }
        }

        // Exit Program Element
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // Create New Car Button
        public void btnNewCar_Click(object sender, EventArgs e)
        {           
            CarForm NewCar = new CarForm();
            {
                NewCar.ShowDialog();
                vehicle[numOfvehicles] = "Car";
                VehicleClass.Car myCar = new VehicleClass.Car("Car",Convert.ToInt16(NewCar.txtYear.Text), NewCar.txtMake.Text, NewCar.txtModel.Text, NewCar.txtColor.Text, Convert.ToInt16(NewCar.txtDoors.Text));
                MyCars.Add(myCar);
                lsbCars.Items.Add(myCar._year + " " + myCar._make + " " + myCar._model + " " + myCar._color + " - " + myCar._doors + " Door");
                numOfvehicles++;
            }
        }

        // Create New Sports Car Button
        private void btnNewSportsCar_Click(object sender, EventArgs e)
        {
            
            SportsCarForm NewSportsCar = new SportsCarForm();
            {
                NewSportsCar.ShowDialog();
                vehicle[numOfvehicles] = "Sports Car";
                VehicleClass.SportsCar mySportsCar = new VehicleClass.SportsCar("Sports Car", Convert.ToInt16(NewSportsCar.txtYear.Text), NewSportsCar.txtMake.Text, NewSportsCar.txtModel.Text, NewSportsCar.txtColor.Text, Convert.ToInt16(NewSportsCar.txtDoors.Text));
                MyCars.Add(mySportsCar);
                lsbCars.Items.Add(mySportsCar._year + " " + mySportsCar._make + " " + mySportsCar._model + " " + mySportsCar._color + " - " + mySportsCar._doors + " Door");
                numOfvehicles++;
            }
        }

        private void btnNewTruck_Click(object sender, EventArgs e)
        {
            numOfvehicles++;
            TruckForm NewTruck = new TruckForm();
            {
                NewTruck.ShowDialog();
                vehicle[numOfvehicles] = "Truck";
                VehicleClass.Truck myTruck = new VehicleClass.Truck("Truck", (Convert.ToInt16(NewTruck.txtYear.Text)), NewTruck.txtMake.Text, NewTruck.txtModel.Text, NewTruck.txtColor.Text, Convert.ToInt16(NewTruck.txtDoors.Text), Convert.ToInt16(NewTruck.txtDriveType.Text));
                MyCars.Add(myTruck);
                lsbCars.Items.Add(myTruck._year + " " + myTruck._make + " " + myTruck._model + " " + myTruck._color + " - " + myTruck._doors + " Door - " + myTruck._driveType + "WD");
                numOfvehicles++;
            }
        }

        private void btnNewMinivan_Click(object sender, EventArgs e)
        {
            numOfvehicles++;
            MinivanForm NewMinivan = new MinivanForm();
            {
                NewMinivan.ShowDialog();
                vehicle[numOfvehicles] = "MiniVan";
                VehicleClass.MiniVan myMiniVan = new VehicleClass.MiniVan("MiniVan", (Convert.ToInt16(NewMinivan.txtYear.Text)), NewMinivan.txtMake.Text, NewMinivan.txtModel.Text, NewMinivan.txtColor.Text, Convert.ToInt16(NewMinivan.txtDoors.Text), Convert.ToInt16(NewMinivan.txtPassengers.Text));
                MyCars.Add(myMiniVan);
                lsbCars.Items.Add(myMiniVan._year + " " + myMiniVan._make + " " + myMiniVan._model + " " + myMiniVan._color + " - " + myMiniVan._doors + " Door - " + myMiniVan._passengers + " Passenger");
                numOfvehicles++;
            }
        }


---------------------------------------------------------------------------------------------------------------------
//VehicleClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AlfordScottFinalProgrammingProject
{
    public class VehicleClass
    {
        // Abstract Class
        public abstract class Vehicle
        {
            // Abstract Property
            public int Year
            {
                get;
                set;
            }

            // Abstract Method
            public virtual void StartVehicle()
            {
                
            }
        }

        // Base Class
        public class Automobile : Vehicle
        {
            // Fields
            public string _type;
            public int _year;
            public string _make;
            public string _model;
            public string _color;

            // Default Constructor
            public Automobile()
            {

            }

            // Constructor
            public Automobile(string type, int year, string make, string model, string color)
            {
                _type = type;
                _year = year;
                _make = make;
                _model = model;
                _color = color;
            }

            // Type Property
            public new string Type
            {
                get { return _type; }
                set { _type = value; }
            }

            // Year Property
            public int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Override StartVehicle Method
            public override void StartVehicle()
            {
                MessageBox.Show("Automobile Started.");
            }

            // Drive Method
            public virtual void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Automobile.");
            }

            // Park Method
            public virtual void Park()
            {
                MessageBox.Show("Parked the Automobile in the driveway");
            }

            // Wash Method
            public virtual void Wash()
            {
                MessageBox.Show("Washed the Automobile. Looks Great!");
            }
        }

        [Serializable]
        public class Car : Automobile
        {
            // Fields
            public string _type;
            public int _doors;
            
            // Default Constructor
            public Car()
            {

            }

            // Constructor
            public Car(string type, int year, string make, string model, string color, int doors) : base (type, year, make, model, color) 
            {
                _type = "Car";
                _doors = doors;
            }

            // Type Property
            public new string Type
            {
                get { return _type; }
                set { _type = value; }
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public new int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }

            // Override StartVehicle Method
            public new void StartVehicle()
            {
                MessageBox.Show("Car Started. It's Quiet!");
            }

            // Drive Car Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Car.");
            }

            // Park Car Method
            public new void Park()
            {
                MessageBox.Show("Parked the Car in the driveway");
            }

            // Wash Car Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Car. Looks Great!");
            }
        }

Attached image(s)

  • Attached Image

Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Working with Serialization

Posted 16 December 2012 - 01:15 PM

See that link in the message that says "View Detail".... Click it. See how much more you can learn of the error.

YOu could also wrap that line in a try/catch block so you can grab the exception and examine it more closely
Was This Post Helpful? 2
  • +
  • -

#10 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 16 December 2012 - 01:23 PM

Still new to the whole trouble shooting thing, I really appreciate your help and patience with this.

The detail view gave me the inner exception {"The type AlfordScottFinalProgrammingProject.VehicleClass+Car was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."}

I also included a screen shot of the entire pane, as I have little to no idea what I'm looking at lol.

Attached image(s)

  • Attached Image

Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Working with Serialization

Posted 16 December 2012 - 01:37 PM

Quote

025        public VehicleClass.Car car = new VehicleClass.Car();
026        public VehicleClass.SportsCar sportscar = new VehicleClass.SportsCar();
027        public VehicleClass.Truck truck = new VehicleClass.Truck();
028        public VehicleClass.MiniVan minivan = new VehicleClass.MiniVan();


What is the point of making these new objects and doing nothing with them?

Quote

lsbCars.Items.Add(myCar._year + " " + myCar._make + " " + myCar._model + " " + myCar._color + " - " + myCar._doors + " Door");

It would be a lot easier to add the actual car object.
lsb.Cars.Items.Add(myCar);

That way when one is selected you can use the actual object out of hte list and not have to find it. Just override .ToString() in the car class to provide a string you like for display
override string ToString()
{
   return _year + " " + _make + " " + _model + " " + ._color + " - " + _doors + " Door;
}


Quote

101                VehicleClass.SportsCar mySportsCar = new VehicleClass.SportsCar("Sports Car", Convert.ToInt16(NewSportsCar.txtYear.Text), NewSportsCar.txtMake.Text, NewSportsCar.txtModel.Text, NewSportsCar.txtColor.Text, 

NO. EVIL. One form should never reach into another and directly access the GUI controls like that. Just have the new form make an actual SportCar object then you can get that. Doing what you're doing tightly binds the two forms. As soon as you make the smallest change for form2 you break form1. But if you only have to get a car object back from form2 you can do anything you like to the forms and even redesign the car objects and nothing breaks.

NewSportsCarDLG.ShowDialog();
SportsCar myNewCar = NewSportsCarDLG.NewlyMintedCarObject;


Take an hour or two to clean up the project. Then return to the serialization stuff. Address the items I mentioned. Fix some names. NewSportsCar is not the name of a form to get the info, its the name of an object. NewSportsCarDLG is the name of a dialog window. Generally make it all a lot cleaner and less confusing before moving forward. Don't build on top of confusion or you have an unsteady foundation.

This post has been edited by tlhIn`toq: 16 December 2012 - 02:05 PM

Was This Post Helpful? 2
  • +
  • -

#12 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 16 December 2012 - 03:09 PM

The First objects were left over from planning, just place holders for me to type the code before I had actually done any work on the vehicle class (Proof of concept) I tried adding the object, but a meaningless string was added, so I didn't know about the toString() method. Also, I tried creating the object on another form, and was unable to return the object to the main form. When I tried creating the form, creating the object and hiding the form, I figured out I could access it, and I contemplated using those temporary holders from #1 to just copy the car from the new form because I was having an issue passing the object from Car form to Main form, but just used the evil method you pointed out as #3. I'm on borrowed time is the ultimate reason why, and this is just going to be tested for functionality, not professional coding standards. I know better, but it's just the rush. I'm re-coding the portions you mentioned, Implementing the override of toString(), and doing some cleanup. Can you explain on the last code you posted? The NewlyMintedCarObject part, I mean.
Was This Post Helpful? 0
  • +
  • -

#13 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 16 December 2012 - 03:49 PM

Okay... Cleaned up the main and changed what you pointed out. Also did the same for Vehicle Class, and I undid the evil on the Car Form. I'm still a little confused with the NewlyMintedObject aspect, but at the moment that is the only erros I'm getting. Code is as follows


//Main.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AlfordScottFinalProgrammingProject
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        //Fields
        public int numOfvehicles = 0;
        public List<VehicleClass.Vehicle> MyCars = new List<VehicleClass.Vehicle>();
        public bool isCar = false;
        public bool isSportsCar = false;
        public bool isTruck = false;
        public bool isMiniVan = false;

        // Save File Element
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string SavePath = @"C:\CarFile\";
	        System.IO.Directory.CreateDirectory(SavePath);
	        if (!System.IO.Directory.Exists(SavePath))
	        {
                MessageBox.Show("Please check permissions");
	        }
            else
	        {
                SavePath += ("My_Car_File");
                SavePath = System.IO.Path.ChangeExtension(SavePath, ".xml");
	            if (System.IO.File.Exists(SavePath))
                System.IO.File.Delete(SavePath);
                object carFile = MyCars;
	            var x = new System.Xml.Serialization.XmlSerializer(carFile.GetType());
	            using (var sw = new StreamWriter(SavePath, false))
	            {
                    x.Serialize(sw, carFile);
	            }
            }
        }

        // Load File Element
        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            DialogResult dr = ofd.ShowDialog();
            if (dr != DialogResult.OK) return;
            var x = new System.Xml.Serialization.XmlSerializer(typeof(VehicleClass));
            using (var sw = new StreamReader(ofd.FileName))
            {
                object o = x.Deserialize(sw);
                //Main newMain  = new Main { lsbCars = (MyCars)o };
                //newMain.Show();
            }
        }

        // Exit Program Element
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // Create New Car Button
        public void btnNewCar_Click(object sender, EventArgs e)
        {           
            CarForm NewCarDLG = new CarForm();
            {
                NewCarDLG.ShowDialog();
                VehicleClass.Car myCar = new NewCarDLG.NewlyMintedCarObject();
                MyCars.Add(myCar);
                lsbCars.Items.Add(myCar.ToString());
                numOfvehicles++;
            }
        }

        // Create New Sports Car Button
        private void btnNewSportsCar_Click(object sender, EventArgs e)
        {
            
            SportsCarForm NewSportsCarDLG = new SportsCarForm();
            {
                NewSportsCarDLG.ShowDialog();
                VehicleClass.SportsCar mySportsCar = new NewSportsCarDLG.NewlyMintedObject();
                MyCars.Add(mySportsCar);
                lsbCars.Items.Add(mySportsCar.ToString());
                numOfvehicles++;
            }
        }

        private void btnNewTruck_Click(object sender, EventArgs e)
        {
            TruckForm NewTruckDLG = new TruckForm();
            {
                NewTruckDLG.ShowDialog();
                VehicleClass.Truck myTruck = new NewTruckDLG.NewlyMintedObject();
                MyCars.Add(myTruck);
                lsbCars.Items.Add(myTruck.ToString());
                numOfvehicles++;
            }
        }

        private void btnNewMinivan_Click(object sender, EventArgs e)
        {
            MinivanForm NewMinivanDLG = new MinivanForm();
            {
                NewMinivanDLG.ShowDialog();
                VehicleClass.MiniVan myMiniVan = new NewMinivanDLG.NewlyMintedObject();
                MyCars.Add(myMiniVan);
                lsbCars.Items.Add(myMiniVan.ToString());
                numOfvehicles++;
            }
        }

        private void lsbCars_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void btnStartVehicle_Click(object sender, EventArgs e)
        {

        }

        private void btnDriveVehicle_Click(object sender, EventArgs e)
        {

        }

        private void btnParkVehicle_Click(object sender, EventArgs e)
        {

        }

        private void btnWashVehicle_Click(object sender, EventArgs e)
        {

        }
    }
}

//VehicleClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AlfordScottFinalProgrammingProject
{
    public class VehicleClass
    {
        // Abstract Class
        public abstract class Vehicle
        {
            // Abstract Property
            public int Year
            {
                get;
                set;
            }

            // Abstract Method
            public virtual void StartVehicle()
            {
                
            }
        }

        // Base Class
        public class Automobile : Vehicle
        {
            // Fields
            public string _type;
            public int _year;
            public string _make;
            public string _model;
            public string _color;

            // Default Constructor
            public Automobile()
            {

            }

            // Constructor
            public Automobile(string type, int year, string make, string model, string color)
            {
                _type = type;
                _year = year;
                _make = make;
                _model = model;
                _color = color;
            }

            // Type Property
            public string Type
            {
                get { return _type; }
                set { _type = value; }
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Override StartVehicle Method
            public override void StartVehicle()
            {
                MessageBox.Show("Automobile Started.");
            }

            // Drive Method
            public virtual void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Automobile.");
            }

            // Park Method
            public virtual void Park()
            {
                MessageBox.Show("Parked the Automobile in the driveway");
            }

            // Wash Method
            public virtual void Wash()
            {
                MessageBox.Show("Washed the Automobile. Looks Great!");
            }
        }

        [Serializable]
        public class Car : Automobile
        {
            // Fields
            public new string _type;
            public int _doors;
            
            // Default Constructor
            public Car()
            {

            }

            // Constructor
            public Car(string type, int year, string make, string model, string color, int doors) : base (type, year, make, model, color) 
            {
                _type = "Car";
                _doors = doors;
            }

            // Type Property
            public new string Type
            {
                get { return _type; }
                set { _type = value; }
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }

            // Override StartVehicle Method
            public new void StartVehicle()
            {
                MessageBox.Show("Car Started. It's Quiet!");
            }

            // Drive Car Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Car.");
            }

            // Park Car Method
            public new void Park()
            {
                MessageBox.Show("Parked the Car in the driveway");
            }

            // Wash Car Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Car. Looks Great!");
            }

            public override string ToString()
            {
                return _year + " " + _make + " " + _model + " " + _color + " - " + _doors + " Door";
            }
        }

        public class SportsCar : Car
        {
            // Fields
            public new int _doors;
            
            // Default Constructor
            public SportsCar()
            {

            }

            // Constructor
            public SportsCar(string type, int year, string make, string model, string color, int doors) : base (type, year, make, model, color, doors)
            {
                _type = "Sports Car";
                _doors = doors;
            }

            // Type Property
            public new string Type
            {
                get { return _type; }
                set { _type = value; }
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public new int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }

            // Override StartVehicle Method
            public new void StartVehicle()
            {
                MessageBox.Show("Sports Car Started. It's Loud!");
            }

            // Drive Sports Car Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Sports Car.");
            }

            // Park Sports Car Method
            public new void Park()
            {
                MessageBox.Show("Parked the Sports Car in the driveway");
            }

            // Wash Sports Car Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Sports Car. Looks Great!");
            }

            public override string ToString()
            {
                return _year + " " + _make + " " + _model + " " + _color + " - " + _doors + " Door";
            }
        }

        public class Truck : Automobile
        {
            // Field
            public int _doors;
            public int _driveType;
            
            // Default Constructor
            public Truck()
            {
                
            }

            // Constructor
            public Truck(string type, int year, string make, string model, string color, int doors, int driveType)
                : base(type, year, make, model, color)
            {
                _type = "Truck";
                _doors = doors;
                _driveType = driveType;
            }

            // Type Property
            public new string Type
            {
                get { return _type; }
                set { _type = value; }
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }

            // Drive Type Property
            public int DriveType
            {
                get { return _driveType; }
                set { _driveType = value; }
            }

            // Override StartVehicle Method
            public new void StartVehicle()
            {
                MessageBox.Show("Truck Started. It's Loud!");
            }

            // Drive Truck Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Truck.");
            }

            // Park Truck Method
            public new void Park()
            {
                MessageBox.Show("Parked the Truck in the driveway");
            }

            // Wash Truck Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Truck. Looks Great!");
            }

            public override string ToString()
            {
                return _year + " " + _make + " " + _model + " " + _color + " - " + _doors + " Door - " + _driveType + "WD";
            }
        }

        public class MiniVan : Automobile
        {
            // Fields
            public int _doors;
            public int _passengers;

            // Default Constructor
            public MiniVan()
            {

            }

            // Constructor
            public MiniVan(string type, int year, string make, string model, string color, int doors, int passengers)
                : base(type, year, make, model, color)
            {
                _type = "MiniVan";
                _doors = doors;
                _passengers = passengers;
            }

            // Type Property
            public new string Type
            {
                get { return _type; }
                set { _type = value; }
            }

            // Year Property
            public new int Year
            {
                get { return _year; }
                set { _year = value; }
            }

            // Make Property
            public new string Make
            {
                get { return _make; }
                set { _make = value; }
            }

            // Model Property
            public new string Model
            {
                get { return _model; }
                set { _model = value; }
            }

            // Color Property
            public new string Color
            {
                get { return _color; }
                set { _color = value; }
            }

            // Doors Property
            public int Doors
            {
                get { return _doors; }
                set { _doors = value; }
            }
            // Passengers Property
            public int Passengers
            {
                get { return _passengers; }
                set { _passengers = value; }
            }

            // Override StartVehicle Method
            public new void StartVehicle()
            {
                MessageBox.Show("Minivan Started. It's Quiet!");
            }

            // Drive Minivan Method
            public new void Drive()
            {
                MessageBox.Show("Went for a nice drive in the Minivan.");
            }

            // Park Minivan Method
            public new void Park()
            {
                MessageBox.Show("Parked the Minivan in the driveway");
            }

            // Wash Minivan Method
            public new void Wash()
            {
                MessageBox.Show("Washed the Minivan. Looks Great!");
            }

            public override string ToString()
            {
                return _year + " " + _make + " " + _model + " " + _color + " - " + _doors + " Door - " + _passengers + " Passengers";
            }
        }
    }
}

//CarForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AlfordScottFinalProgrammingProject
{
    public partial class CarForm : Form
    {
        public CarForm()
        {
            InitializeComponent();
        }

        private void btnNewCar_Click(object sender, EventArgs e)
        {
            VehicleClass.Car NewCar = new VehicleClass.Car("Car", Convert.ToInt16(txtYear.Text), txtMake.Text, txtModel.Text, txtColor.Text, Convert.ToInt16(txtDoors.Text));
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#14 SAlford6129  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 03-September 12

Re: Working with Serialization

Posted 17 December 2012 - 10:18 AM

Never mind. Had a really helpful person on another Forum take the time to walk me through how to Serialize the objects so that when I load the file their states are returned as well. I do appreciate your help, you pointed out some really good things about the code and conventions. I'm done with about 24 hours to spare on my deadline.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1