Monday, October 13, 2014

Object Containing objects


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



namespace ObjectsContainment
{
     [Serializable]
    public class Course
    {
    //Define a class Course. This class should have the following fields:
//_courseID  (string) example CSI-155
//_startDate (DateTime) the first day the course started
//_testList (List<Test>)

        private string _courseID;
        private DateTime _startDate;
        private List<Test> _testList;

        public Course(string courseID, DateTime startDate)
        {
            _courseID = courseID;
            _startDate = startDate;
            _testList = new List<Test>();
        }

        public string CourseID
        { get { return _courseID; } }

        public DateTime StartDate
        { get { return _startDate; } }

        //Define method:  AddTest, to add a Test object to the testList
        public void AddTest(Test test)
        {
            _testList.Add(test);
        }

        public Test[] testList
        { get { return _testList.ToArray(); } }

        //Define method:  GetLabGrades, that returns an array of all the lab grades
        public float[] GetLabGrades()
        {
            List<float> lgrades = new List<float>();
            for (int i = 0; i < _testList.Count; i++)
{
                if (_testList[i].TypeOfTest == TestType.Lab)
                {
                    lgrades.Add(_testList[i].Grade);
                }  
}
            lgrades.TrimExcess();
            return lgrades.ToArray();
        }

        //GetQuizGrades, that returns an array of all the quiz grades
        public float[] GetQuizGrades()
        {
            List<float> qgrades = new List<float>();
            for (int i = 0; i < _testList.Count; i++)
            {
                if (_testList[i].TypeOfTest == TestType.Quiz)
                {
                    qgrades.Add(_testList[i].Grade);
                }
            }
            qgrades.TrimExcess();
            return qgrades.ToArray();
        }

        public float [] GetMidExamGrade()
        {
            List<float> mgrades = new List<float>();
            for (int i = 0; i < _testList.Count; i++)
            {
                if (_testList[i].TypeOfTest == TestType.Midterm)
                {
                    mgrades.Add(_testList[i].Grade);
                }
            }
            mgrades.TrimExcess();
            return mgrades.ToArray();
        }

        public float [] GetFinalExamGrade()
        {
            List<float> fgrades = new List<float>();
            for (int i = 0; i < _testList.Count; i++)
            {
                if (_testList[i].TypeOfTest == TestType.Final)
                {
                    fgrades.Add(_testList[i].Grade);
                }
            }
            fgrades.TrimExcess();
            return fgrades.ToArray();
        }

        public float GetOverallAverageGrade()
        {
            float avg = 0;
            if (_testList.Count > 0)
            {
                for (int i = 0; i < _testList.Count; i++)
                {
                    avg += _testList[i].Grade;
                }
            }
            return avg / _testList.Count;
        }
    }
}
//Define method:  AddTest, to add a Test object to the testList
//Define method:  GetLabGrades, that returns an array of all the lab grades
//Define method: GetQuizGrades, that returns an array of all the quiz grades
//Define methods: GetFinalExamGrade and GetMidtermExamGrade to return the final grade
//and the midterm grade respectivel
//Define method : GetOverallAverageGrade, that returns the overall average grade of this course.
//=====================================================================
namespace ObjectsContainment
{
     [Serializable]
    public class Test
    {
        private DateTime _date;
        private float _grade;
        private TestType _testType;

        ////Constructor
        public Test(DateTime date, float grade, TestType testType)
        {
            this._date = date;
            this._grade = grade;
            this._testType = testType;
        }

        ////Properties
        public DateTime Date
        { get { return this._date; } }

        public float Grade
        { get { return this._grade; } }

        public TestType TypeOfTest
        { get { return this._testType; } }
    }
}

//Define a class Test. This class should have the following fields: 
//_date the test was administrated (DateTime)
//_value, the grade value obtained
//_category,  type of test taken (should be an enum with values: Quiz, Lab, Final, Midterm
//Add all necessary constructor(s) and properties */
///=====================================================================
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; //added to serializtion exception
using System.Runtime.Serialization.Formatters.Binary; //added to serialize data

namespace ObjectsContainment
{
    public enum TestType
    {
        Quiz, Lab, Final, Midterm
    };

    public partial class Form1 : Form
    {
        List<Course> courseList = new List<Course>();
        string coursesFile = "coursesFile.txt";
        string coursefilepath = "coursefile.dat";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] tType =
                Enum.GetNames(typeof(TestType));
           
            cboTestType.Items.AddRange(tType);
            cboTestType.SelectedIndex = 0;

            //===============================
            if (File.Exists(coursesFile))
            {
                using (StreamReader sr = new StreamReader(
                    new FileStream(coursesFile, FileMode.Open, FileAccess.Read)))
                {
                    while (!sr.EndOfStream)
                    {
                        string courseID = sr.ReadLine();
                        DateTime startDate = Convert.ToDateTime(sr.ReadLine());
                        courseList.Add(new Course(courseID, startDate));
                    }
                }
            }

            //------------------------------------
            //deserialize courseList
            FileStream fs = null;
            try
            {
                //1. Create a Formatter
                BinaryFormatter formatter = new BinaryFormatter();
                //2. Create file stream
                fs = new FileStream(coursefilepath,
                                           FileMode.Open,
                                           FileAccess.Read);
                //3.Deserialize (reconstruct the list of people
                courseList = (List<Course>)formatter.Deserialize(fs);

                MessageBox.Show("Course 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 btnCreateCourse_Click(object sender, EventArgs e)
        {
            string courseId = txtCourseID.Text;
            DateTime startdt = dt1.Value;
            //save to a file
            StreamWriter sw = null;
            try
            {
                using (sw = new StreamWriter(
                    new FileStream(coursesFile, FileMode.Append, FileAccess.Write)))
                {
                    sw.WriteLine(courseId);
                    sw.WriteLine(startdt.ToShortDateString());
                }
                Course c = new Course(courseId, startdt);
                courseList.Add(c);

                MessageBox.Show("new course has been added");
                txtCourseID.Clear();
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message);
            }
        }

        private void btnDisplayCourse_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            foreach (Course c in courseList)
            {
                listView1.Items.Add(GetListViewItem(c));
            }
        }
        private  ListViewItem GetListViewItem(Course c)
        {
            ListViewItem lvi = new ListViewItem(c.CourseID);
            lvi.SubItems.Add(c.StartDate.ToShortDateString());
            return lvi;
        }

        private void btnAddTestToSelectedCourse_Click(object sender, EventArgs e)
        {
            ListView.SelectedIndexCollection sindices = listView1.SelectedIndices;
            float gradevalue;
            if (sindices.Count > 0)
            {
                int sindex = sindices[0];

                Course c = courseList[sindex];
                //create new test

                //ExpenseCategory ec = (ExpenseCategory)Enum.Parse(typeof(ExpenseCategory), br.ReadString());
                TestType testT = (TestType)Enum.Parse(typeof(TestType), cboTestType.Text);

                //float gradevalue = float.Parse(txtGrade.Text);
                float.TryParse(txtGrade.Text, out gradevalue);
                DateTime testDateTime = testdt.Value;

                //Test test = new Test(testDateTime, gradevalue, testT);
                Test test = new Test(testDateTime, gradevalue, testT);

                c.AddTest(test);
                MessageBox.Show("Test has been added to the selected person");
            }
            else
                MessageBox.Show("you must first select a course");
        }

        private void btnDisplayInfoOfSelectedCourse_Click(object sender, EventArgs e)
        {
            //get all the test info of the selected course
            //get the selected course
            ListView.SelectedIndexCollection sindices =
                                           listView1.SelectedIndices;
            if (sindices.Count > 0)
            {
                int sindex = sindices[0];
                Course c = courseList[sindex];
                //get its test info
                Test[] tests = c.testList;

                //display all the tests
                listView2.Items.Clear();
                foreach (Test t in tests)
                {
                    ListViewItem lvi2 = new ListViewItem(t.TypeOfTest.ToString());
                    lvi2.SubItems.Add(t.Grade.ToString());
                    lvi2.SubItems.Add(t.Date.ToShortDateString());
                    listView2.Items.Add(lvi2);
                }
            }
        }

        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(coursefilepath,
                                            FileMode.Create,
                                            FileAccess.Write);
                //3.Serialize the list (break dow into bits)
                formatter.Serialize(fs, courseList);

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

        private void btnDisplayEndQtrResult_Click(object sender, EventArgs e)
        {
            listView3.Items.Clear();

            foreach (Course c in courseList)
            {
                ListViewItem lvi = new ListViewItem(c.CourseID);
                lvi.SubItems.Add(GetAvgGrade(c.GetLabGrades()).ToString("n"));
                lvi.SubItems.Add(GetAvgGrade(c.GetQuizGrades()).ToString("n"));
                lvi.SubItems.Add(GetAvgGrade(c.GetMidExamGrade()).ToString("n"));
                lvi.SubItems.Add(GetAvgGrade(c.GetFinalExamGrade()).ToString("n"));
                lvi.SubItems.Add(c.GetOverallAverageGrade().ToString("n"));
                lvi.SubItems.Add(GetGPA(c).ToString());
                listView3.Items.Add(lvi);
            }

        }
        //Get average Lab grade
        private float GetAvgGrade(float [] gradesArr)
        {
            float sum = 0;
            for (int i = 0; i < gradesArr.Length; i++)
            {
                sum += gradesArr[i];

            }
            if (gradesArr.Length == 0)
                return 0;
            return sum / gradesArr.Length;
        }

        private decimal GetGPA(Course c)
        {
            float avggrade = c.GetOverallAverageGrade();
            if (avggrade >= 96)
            {
                return 4.0m;
            }
            else if (avggrade >= 90 && avggrade < 96)
            {
                return 3.8m;
            }
            else if (avggrade >= 85 && avggrade < 90)
            {
                return 3.6m;
            }
            else if (avggrade >= 80 && avggrade < 85)
            {
                return 3.4m;
            }
            else if (avggrade >= 75 && avggrade < 80)
            {
                return 3.2m;
            }
            else if (avggrade >= 70 && avggrade < 75)
            {
                return 3.0m;
            }
            else if (avggrade >= 65 && avggrade < 70)
            {
                return 2.8m;
            }
            else if (avggrade >= 60 && avggrade < 65)
            {
                return 2.6m;
            }
            else if (avggrade >= 55 && avggrade < 60)
            {
                return 2.4m;
            }
            else if (avggrade > 50 && avggrade < 55)
            {
                return 2.0m;
            }
            return 0m;
        }
    }
}


No comments:

Post a Comment