Thursday, October 2, 2014

Object Containing Other Objects


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace ObjectContainingOtherObjects
{
    [Serializable]
    public class Car
    {
        private string _make;
        private string _model;
        private int _year;
        private int _mileage;
        private decimal _price;

        public Car(string make, string model, int year, int mileage, decimal price)
        {
            _make = make;
            _model = model;
            _year = year;
            _mileage = mileage;
            _price = price;
        }

        public string Make
        { get { return _make; } }

        public string Model
        { get { return _model; } }

        public int Year
        { get { return _year; } }

        public int Mileage
        { get { return _mileage; } }

        public decimal Price
        { get { return _price; } }

    }
}
//==================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObjectContainingOtherObjects
{
    [Serializable]
    public class Person
    {
        private string _firstname;
        private string _lastname;
        private List<string> _phoneList;
        private List<Car> _carList;

        public Person(string firstname, string lastname)
        {
            _firstname = firstname;
            _lastname = lastname;
            //create both lists
            _phoneList = new List<string>();
            _carList = new List<Car>();
        }

        public string Firstname
        { get { return _firstname; } }

        public string Lastname
        { get { return _lastname; } }

        //add methods to add new car to the carlist and a new phone
        //to the phonelist
        public void AddCar(Car car)
        {
            _carList.Add(car);
        }

        public void AddPhone(string phone)
        {
            _phoneList.Add(phone);
        }
        //return the list of cars using a property that returns
        //the list as an array of cars (a copy of the _carList)

        public Car[] CarList
        { get { return _carList.ToArray(); } }

        //return the list of phones using a property that returns
        //the list as an array of strings (a copy of the original _phoneList)
        public string[] PhoneList
        { get { return _phoneList.ToArray(); } }

        //provide methods to remove items from the lists
        public bool RemoveCar(Car car)
        {
            return _carList.Remove(car);
        }
        public bool RemovePhone(string phone)
        {
            return _phoneList.Remove(phone);
        }
    }
}
//===================================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


namespace ObjectContainingOtherObjects
{
    public partial class Form1 : Form
    {
        string peoplesfile = "peoplesfile.txt";
        //file to use for serializing/deserializing peopleList
        string peopleListfile = "peopleListdata.dat";

        List<Person> peopleList = new List<Person>();

        public Form1()
        {
            InitializeComponent();
        }

        private void btnAddNewPerson_Click(object sender, EventArgs e)
        {
            string firstname = txtFirstname.Text;
            string lastname = txtLastname.Text;
            //save to a file
            StreamWriter sw = null;
            try
            {
                using (sw = new StreamWriter(
                    new FileStream(peoplesfile, FileMode.Append, FileAccess.Write)))
                {
                    sw.WriteLine(firstname);
                    sw.WriteLine(lastname);
                }
                Person p = new Person(firstname, lastname);
                peopleList.Add(p);

                MessageBox.Show("new person has been added");
                txtLastname.Clear();
                txtFirstname.SelectAll();
                txtFirstname.Focus();
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            foreach (Person p in peopleList)
            {
                listView1.Items.Add(GetListViewItem(p));
            }
        }
        private  ListViewItem GetListViewItem(Person p)
        {
            ListViewItem lvi = new ListViewItem(p.Lastname);
            lvi.SubItems.Add(p.Firstname);
            return lvi;
        }

        private void btnAddCarToSelectedPerson_Click(object sender, EventArgs e)
        {
           ListView.SelectedIndexCollection sindices = 
                                            listView1.SelectedIndices;
           if (sindices.Count > 0)
           {
               int sindex = sindices[0];
               //Assuming that the index in listview matches the index
               //in peopleList
               //the the person object corresponding to the firstname,
               //lastname selected in the listview
               Person p = peopleList[sindex];
               //create new car
               string make = txtMake.Text;
               string model = txtModel.Text;
               int year = int.Parse(txtYear.Text);
               int mileage = int.Parse(txtMileage.Text);
               decimal price = decimal.Parse(txtPrice.Text);
               Car car = new Car(make, model, year, mileage, price);
               //add car to the person
               p.AddCar(car);
               MessageBox.Show("Car has been added to the selected person");
           }
           else
               MessageBox.Show("you must first select a person");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(peoplesfile))
            {
                using (StreamReader sr = new StreamReader(
                    new FileStream(peoplesfile, FileMode.Open, FileAccess.Read)))
                {
                    while (!sr.EndOfStream)
                    {
                        string firstname = sr.ReadLine();
                        string lastname = sr.ReadLine();
                        peopleList.Add(new Person(firstname, lastname));
                    }
                }
            }
            //------------------------------------
            //deserialize peopleList
            FileStream fs = null;
            try
            {
                //1. Create a Formatter
                BinaryFormatter formatter = new BinaryFormatter();
                //2. Create file stream
                fs = new FileStream(peopleListfile,
                                           FileMode.Open,
                                           FileAccess.Read);
                //3.Deserialize (reconstruct the list of people
                peopleList = (List<Person>)formatter.Deserialize(fs);

                MessageBox.Show("people list has been deserialized");
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message);
            }
            catch (SerializationException se)
            {
                MessageBox.Show(se.Message);
            }
            finally
            {
                if (fs != null) fs.Close();
            }

        }

        private void btnDisplayCarsOfSelectedPerson_Click(object sender, EventArgs e)
        {
            //get all the cars of the selected person
            //get the selected person
             ListView.SelectedIndexCollection sindices = 
                                            listView1.SelectedIndices;
             if (sindices.Count > 0)
             {
                 int sindex = sindices[0];
                 Person p = peopleList[sindex];
                 //get his/her cars
                 Car[] cars = p.CarList;
                 //display all the cars
                 listView2.Items.Clear();
                 foreach (Car c in cars)
                 {
                     ListViewItem lvitem = new ListViewItem(c.Make);
                     lvitem.SubItems.Add(c.Model);
                     lvitem.SubItems.Add(c.Year.ToString());
                     lvitem.SubItems.Add(c.Mileage.ToString("n0"));
                     lvitem.SubItems.Add(c.Price.ToString("c"));
                     //add lvitem to the listview
                     listView2.Items.Add(lvitem);
                 }
             }
        }

        private void btnAddPhoneToPerson_Click(object sender, EventArgs e)
        {
             ListView.SelectedIndexCollection sindices = 
                                            listView1.SelectedIndices;
             if (sindices.Count > 0)
             {
                 int sindex = sindices[0];
                 Person p = peopleList[sindex];
                 //get new phone from user
                 string phone = txtPhoneNumber.Text.Trim();
                 if (phone != String.Empty)
                 {
                     p.AddPhone(phone);
                     MessageBox.Show("phone, successfully added");
                 }
                 else
                     MessageBox.Show("Need to enter a phone number");
             }
        }

        private void btnDisplayAllPhones_Click(object sender, EventArgs e)
        {
             ListView.SelectedIndexCollection sindices = 
                                            listView1.SelectedIndices;
             if (sindices.Count > 0)
             {
                 //get the index of the selected person
                 int sindex = sindices[0];
                 //use the index to extract the person object
                 Person p = peopleList[sindex];
                 //display the list of phones of the given person p
                 phoneListbox.Items.Clear();
                 foreach (string phone in p.PhoneList)
                 {
                     phoneListbox.Items.Add(phone);
                 }
             }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this code runs right before the application closes
            //save the entire list of people
            //use Serialization. Serialize the list using the BinaryFormat
            FileStream fs = null;
            try
            {
                //1. Create a Formatter
                BinaryFormatter formatter = new BinaryFormatter();
                //2. Create file stream
                fs = new FileStream(peopleListfile,
                                            FileMode.Create,
                                            FileAccess.Write);
                //3.Serialize the list (break dow into bits)
                formatter.Serialize(fs, peopleList);

                MessageBox.Show("people list has been serialized");
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message);
            }
            catch (SerializationException se)
            {
                MessageBox.Show(se.Message);
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }
    }
}
///Build a GUI to allow user to:
/// Enter a person (firstname and lastname) then add the 
/// person to a list of people, defined in Form1. At the same
/// time save the person first and last names to a text file.

///provide gui to read the text file and populate the listview
///with first and last names
///
/// 
///Lab Assignment:
///Add gui to enter a phone number and add it to the selected person
///then add gui to display all the phone numbers of the selected person

No comments:

Post a Comment