Employee Database

EmployeeDatabaseV4

EmployeeDatabaseV4_1

This is a simple application I came up with to keep track of people, employees, etc… This another multi-class program. It was also my first attempt at using data serialization for saving the program data. I have to say it works really good and different from using string builder to save data. Yes it’s not a fully secure way to store data, for example encryption. However I’m pretty happy to have figured it out. This was also my first attempt at overloading a class. I used it if the user wanted to edit an exiting employees data. Well onto the source code. Enjoy.

Employee Form Class:


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 EmployeeDatabase
{
    public partial class EmployeeForm : Form
    {   
        private Employee _employeeInfo;

        internal Employee EmployeeInfo
        {
            get { return _employeeInfo; }
        }

        private int id = 0;

        public EmployeeForm()
        {
            InitializeComponent();
        }

        private void employeeFormOkButton_Click(object sender, EventArgs e)
        {
            //Setting all of the label colors to black.
            lastNameLabel.ForeColor = Color.Black;
            firstNameLabel.ForeColor = Color.Black;
            dateOfBirthLabel.ForeColor = Color.Black;
            addressOneLabel.ForeColor = Color.Black;
            cityLabel.ForeColor = Color.Black;
            stateLabel.ForeColor = Color.Black;
            zipcodeLabel.ForeColor = Color.Black;

            //Checking to make sure entries are made in all of the required boxes.
            if (lastNameTextBox.Text.Length < 1)
                lastNameLabel.ForeColor = Color.Red;
            if (firstNameTextBox.Text.Length < 1)
                firstNameLabel.ForeColor = Color.Red;
            if (dateOfBirthTextBox.Text.Length < 1)
                dateOfBirthLabel.ForeColor = Color.Red;
            if (addressOneTextBox.Text.Length < 1)
                addressOneLabel.ForeColor = Color.Red;
            if (cityTextBox.Text.Length < 1)
                cityLabel.ForeColor = Color.Red;
            if (stateTextBox.Text.Length < 1)
                stateLabel.ForeColor = Color.Red;
            if (zipCodeTextBox.Text.Length < 1)
                zipcodeLabel.ForeColor = Color.Red;

            //Checking for errors.
            bool isError = false;
            isError = (lastNameLabel.ForeColor == Color.Red || firstNameLabel.ForeColor == Color.Red ||
                dateOfBirthLabel.ForeColor == Color.Red || addressOneLabel.ForeColor == Color.Red ||
                cityLabel.ForeColor == Color.Red || stateLabel.ForeColor == Color.Red || zipcodeLabel.ForeColor == Color.Red);

            //If there are no errors then proceed with processing the employee information.
            if (!isError)
            {
                //Setting the dialog result for this button.
                this.DialogResult = DialogResult.OK;

                Random random = new Random();
                int randomID = 0;

                if (id == 0)
                    //Generating and employee ID.
                    randomID = random.Next(1, 100000);
                else
                    randomID = id;

                //Validate the date of birth.
                DateTime dateOfBirth;
                if (!DateTime.TryParse(dateOfBirthTextBox.Text, out dateOfBirth))
                    dateOfBirth = DateTime.MinValue;

                //Getting the data from the form entries. Using the initilizers thru the default constructor.
                _employeeInfo = new Employee()
                {
                    Id = randomID,
                    LastName = lastNameTextBox.Text,
                    FirstName = firstNameTextBox.Text,
                    DateOfBirth = dateOfBirth,
                    AddressOne = addressOneTextBox.Text,
                    AddressTwo = addressTwoTextBox.Text,
                    City = cityTextBox.Text,
                    State = stateTextBox.Text,
                    ZipCode = zipCodeTextBox.Text,
                    PhoneNumber = phoneNumberTextBox.Text
                };
            }
            else
            {
                MessageBox.Show("Please fill in all the red fields.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public EmployeeForm(int employeeId, string employeeLastName, string employeeFirstName, DateTime employeeDateOfBirth, string employeeAddressOne,
            string employeeAddressTwo, string employeeCity, string employeeState, string employeeZipCode, string employeePhoneNumber)
        {
            id = employeeId;
            Console.WriteLine(id);

            //Loading the form with all the fields.
            InitializeComponent();

            //Creating a new Employee object so I can use the variables in the class thru get/set.
            _employeeInfo = new Employee();

            //Loading all the selected employee data into the form.
            _employeeInfo.Id = employeeId;
            employeeIdLabel.Text = "Employee ID: " + _employeeInfo.Id;
            _employeeInfo.LastName = employeeLastName;
            lastNameTextBox.Text = _employeeInfo.LastName;
            _employeeInfo.FirstName = employeeFirstName;
            firstNameTextBox.Text = _employeeInfo.FirstName;
            _employeeInfo.DateOfBirth = employeeDateOfBirth;
            dateOfBirthTextBox.Text = _employeeInfo.DateOfBirth.ToString();
            _employeeInfo.AddressOne = employeeAddressOne;
            addressOneTextBox.Text = _employeeInfo.AddressOne;
            _employeeInfo.AddressTwo = employeeAddressTwo;
            addressTwoTextBox.Text = _employeeInfo.AddressTwo;
            _employeeInfo.City = employeeCity;
            cityTextBox.Text = _employeeInfo.City;
            _employeeInfo.State = employeeState;
            stateTextBox.Text = _employeeInfo.State;
            _employeeInfo.ZipCode = employeeZipCode;
            zipCodeTextBox.Text = _employeeInfo.ZipCode;
            _employeeInfo.PhoneNumber = employeePhoneNumber;
            phoneNumberTextBox.Text = _employeeInfo.PhoneNumber;
        }

        private void employeeFormCancelButton_Click(object sender, EventArgs e)
        {
            //Setting the dialog result for this button.
            this.DialogResult = DialogResult.Cancel;
        }
    }
}

EmployeeDatabaseForm Class

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace EmployeeDatabase
{
    [Serializable()]
    public partial class EmployeeDatabaseForm : Form
    {
        private List _employees = new List();

        public EmployeeDatabaseForm()
        {
            InitializeComponent();

            //Calling the method to load the employee data from the saved file.
            loadData();
        }

        private void addEmployeeButton_Click(object sender, EventArgs e)
        {   
            //Showing the employee form dialog box. 
            EmployeeForm employeeForm = new EmployeeForm();
            employeeForm.ShowDialog();

            if (employeeForm.DialogResult == DialogResult.OK)
            {
                //Clearing the list box.
                employeeListBox.Items.Clear();

                //Adding the items to the list.
                _employees.Add(employeeForm.EmployeeInfo);

                //Displaying the employees is the list box.
                displayEmployees();

                //Update the employee count label.
                employeeCountValueLabel.Text = employeeListBox.Items.Count.ToString();

                //Calling the method to save the data. This saves after the user has entered info into the form.
                saveData();
            }
        }

        private void displayEmployees()
        {
            //Iterating thru the Employee List and displaying the information.
            for (int i = 0; i < _employees.Count; i++)
            {
                employeeListBox.Items.Add("Name: " + _employees[i].FirstName + " " + _employees[i].LastName + " ID: " + _employees[i].Id);
            }

            //Update the employee count label.
            employeeCountValueLabel.Text = employeeListBox.Items.Count.ToString();
        }

        //Method used to serialize and save the employee data.
        private void saveData()
        {
            //Path of the file containing the data.
            string dataPath = Application.StartupPath + @"\data\Employee Info.data";

            //Creating and opening a file stream to the file I want to save the data to.
            FileStream stream = File.Open(dataPath, FileMode.Create, FileAccess.ReadWrite);

            //Creating a new binary formatter object to format the data stream.
            BinaryFormatter bin = new BinaryFormatter();

            //Serializing the data from the list.
            bin.Serialize(stream, _employees);

            //Closing the stream.
            stream.Close();
        }

        //Method used to de-serialize and load the employee data.
        private void loadData()
        {
            try
            {
                //Path of the file containing 
                string dataPath = Application.StartupPath + @"\data\Employee Info.data";

                //Creating a file stream to open the file.
                FileStream stream = File.Open(dataPath, FileMode.Open);

                //Creating a binary formatter to put the data back into the list.
                BinaryFormatter bin = new BinaryFormatter();
                _employees = (List)bin.Deserialize(stream);

                //Closing the stream.
                stream.Close();

                //Clearing the list box.
                employeeListBox.Items.Clear();

                //Running the method to display the employees.
                displayEmployees();
            }
            catch
            {
            }
        }

        private void employeeListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Enabling or disabling the Remove button if there are selectable items in the list box.
            if (employeeListBox.SelectedIndex >= 0)
            {
                removeButton.Enabled = true;
                viewButton.Enabled = true;
                editInfoButton.Enabled = true;
            }
            else
            {
                removeButton.Enabled = false;
                viewButton.Enabled = false;
                editInfoButton.Enabled = false;
            }
        }

        //Making it so the user can view the rest of the employee information with the view button.
        private void viewButton_Click(object sender, EventArgs e)
        {
            //By using the listbox selected index id along with the index in the List this
            //will display the rest of employee information if need be. You can either 
            //click on the view button or double-click on the entry you want to view.

            //Checking to make sure the index is correct in the listbox.
            //Console.WriteLine(employeeListBox.SelectedIndex);

            //Checking to see if the listbox index matches the List index and Employee ID.
            //Console.WriteLine(_employees[employeeListBox.SelectedIndex].Id);

            //Displaying a messagebox with the information.
            MessageBox.Show("ID: " + _employees[employeeListBox.SelectedIndex].Id + "\n" +
            "First Name: " + _employees[employeeListBox.SelectedIndex].FirstName + "\n" +
            "Last Name: " + _employees[employeeListBox.SelectedIndex].LastName + "\n" +
            "Date Of Birth: " + _employees[employeeListBox.SelectedIndex].DateOfBirth + "\n" +
            "Address 1: " + _employees[employeeListBox.SelectedIndex].AddressOne + "\n" +
            "Address 2: " + _employees[employeeListBox.SelectedIndex].AddressTwo + "\n" +
            "City: " + _employees[employeeListBox.SelectedIndex].City + "\n" + 
            "State: " + _employees[employeeListBox.SelectedIndex].State + "\n" +
            "Zip Code: " + _employees[employeeListBox.SelectedIndex].ZipCode + "\n" +
            "Phone Number: " + _employees[employeeListBox.SelectedIndex].PhoneNumber, 
            "Employee Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void editInfoButton_Click(object sender, EventArgs e)
        {
            //Call the overloaded method passing all of the employee information.
            EmployeeForm employeeForm = new EmployeeForm(_employees[employeeListBox.SelectedIndex].Id, _employees[employeeListBox.SelectedIndex].LastName,
                _employees[employeeListBox.SelectedIndex].FirstName, _employees[employeeListBox.SelectedIndex].DateOfBirth,
                _employees[employeeListBox.SelectedIndex].AddressOne, _employees[employeeListBox.SelectedIndex].AddressTwo,
                _employees[employeeListBox.SelectedIndex].City, _employees[employeeListBox.SelectedIndex].State,
                _employees[employeeListBox.SelectedIndex].ZipCode, _employees[employeeListBox.SelectedIndex].PhoneNumber);
            employeeForm.ShowDialog();

            if (employeeForm.DialogResult == DialogResult.OK)
            {
                //Remove the previous entry from the list.
                _employees.RemoveAt(employeeListBox.SelectedIndex);

                //Clearing the list box.
                employeeListBox.Items.Clear();

                //Adding the edited items to the list.
                _employees.Add(employeeForm.EmployeeInfo);

                //Refresh the employees is the list box.
                displayEmployees();

                //Update the employee count label.
                employeeCountValueLabel.Text = employeeListBox.Items.Count.ToString();

                //Calling the method to save the data. This saves after the user has entered info into the form.
                saveData();
            }
        }

        //Or the user can double-click on the listbox item to view detailed information.
        private void employeeListBox_DoubleClick(object sender, EventArgs e)
        {
            //Same as the viewButton_Click method. Only this will display the information
            //if the entry is double clicked on. The exception is taken care of an if/else
            //statement. This makes sure the user clicks on an item.

            //Checking to make sure the index is correct in the listbox.
            //Console.WriteLine(employeeListBox.SelectedIndex);

            //Checking to see if the listbox index matches the List index and Employee ID.
            //Console.WriteLine(_employees[employeeListBox.SelectedIndex].Id);

            if (employeeListBox.SelectedIndex < 0)
            {
                MessageBox.Show("No entries to view, please select or add one.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //Displaying a messagebox with the information.
                MessageBox.Show("ID: " + _employees[employeeListBox.SelectedIndex].Id + "\n" +
                "First Name: " + _employees[employeeListBox.SelectedIndex].FirstName + "\n" +
                "Last Name: " + _employees[employeeListBox.SelectedIndex].LastName + "\n" +
                "Date Of Birth: " + _employees[employeeListBox.SelectedIndex].DateOfBirth + "\n" +
                "Address 1: " + _employees[employeeListBox.SelectedIndex].AddressOne + "\n" +
                "Address 2: " + _employees[employeeListBox.SelectedIndex].AddressTwo + "\n" +
                "City: " + _employees[employeeListBox.SelectedIndex].City + "\n" +
                "State: " + _employees[employeeListBox.SelectedIndex].State + "\n" +
                "Zip Code: " + _employees[employeeListBox.SelectedIndex].ZipCode + "\n" +
                "Phone Number: " + _employees[employeeListBox.SelectedIndex].PhoneNumber,
                "Employee Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to remove this entry? ", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //Note: I chose to use the selectedIndex property of the listBox to get the ID of the item to remove in the list. Made sense since they match.

                //Removing the items from the List object.
                _employees.RemoveAt(employeeListBox.SelectedIndex);

                //Clearing the list box.
                employeeListBox.Items.Clear();

                //Refreshing the employee list display
                displayEmployees();

                //Update the employee count label.
                employeeCountValueLabel.Text = employeeListBox.Items.Count.ToString();

                //Calling the method to save the data. This saves after the user has clicked the remove button.
                saveData();
            }
        }

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

Employee Class:


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

namespace EmployeeDatabase
{
    [Serializable()]
    class Employee
    {
        private int _id = 0;
        private string _lastName;
        private string _firstName;
        private DateTime _dateOfBirth;
        private string _addressOne;
        private string _addressTwo;
        private string _city;
        private string _state;
        private string _zipCode;
        private string _phoneNumber;

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }

        public DateTime DateOfBirth
        {
            get { return _dateOfBirth; }
            set { _dateOfBirth = value; }
        }

        public string AddressOne
        {
            get { return _addressOne; }
            set { _addressOne = value; }
        }

        public string AddressTwo
        {
            get { return _addressTwo; }
            set { _addressTwo = value; }
        }

        public string City
        {
            get { return _city; }
            set { _city = value; }
        }

        public string State
        {
            get { return _state; }
            set { _state = value; }
        }

        public string ZipCode
        {
            get { return _zipCode; }
            set { _zipCode = value; }
        }

        public string PhoneNumber
        {
            get { return _phoneNumber; }
            set { _phoneNumber = value; }
        }

        public Employee()
        {
            //Default Constructor
        }
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s