Simple Alarm Clock Program

Alarms

AlarmsNew

AlarmsEdit

AlarmsCd

This was a simple desktop alarm program I did as a final to my C# class at Oreilly School Of Technology. This program has multiple classes as you can see from the class designer picture. One for the MainForm where you could Add, Edit, and Delete alarms from a ListBox. The program took care of binary serialization for saving the data. Any time an alarm was entered, edited, or deleted the data was saved automatically via the methods as you will see later in this post. A display alert shows up when an alarm comes due. Click on more to see the code. Also remember that the source code for all these programs is available via the C# Downloads & Files link.


MainForm 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 Alarms
{
    [Serializable()]
    public partial class MainForm : Form
    {
        private Alarms _alarms = new Alarms();
        string dataPath = Application.StartupPath + @"\data\Alarm Data.data";    //Setting the data file path.

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            //Enabling the timer for the current time.
            alarmTimer.Enabled = true;

            //Loading any data that might be saved.
            _alarms.LoadAlarmsFromFile(dataPath);
            refreshAlarmsList();
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            //Showing the AlarmForm dialog box.
            AlarmForm alarmForm = new AlarmForm();
            alarmForm.ShowDialog();

            if (alarmForm.DialogResult == DialogResult.OK)
            {
                bool alarmExists = _alarms.Search(alarmForm.Alarm.AlarmTime);
                //Checking to see if the alarm exists. If not it will be added to the form.
                if (alarmExists)
                {
                    MessageBox.Show("Sorry cannot add a duplicate alarm time.", this.Text, MessageBoxButtons.OK);

                    //Refreshing the alarms listbox.
                    refreshAlarmsList();
                }
                else
                {
                    //Adding the alarm object to the list.
                    _alarms.Add(alarmForm.Alarm);

                    //Saving the data.
                    _alarms.SaveAlarmsToFile(dataPath);

                    //Refreshing the alarms listbox.
                    refreshAlarmsList();
                }
            }
        }

        private void editButton_Click(object sender, EventArgs e)
        {
            //Making sure there is an alarm in the form to edit.
            if (alarmsListBox.SelectedIndex > -1)
            {
                //Getting the alarm time.
                string alarmTime = _alarms.GetAlarm(alarmsListBox.SelectedIndex);
                DateTime time = DateTime.Parse(alarmTime);
                int hour = int.Parse(time.ToString("hh"));
                int minutes = int.Parse(time.ToString("mm"));

                //Getting the alarm category.
                string category = _alarms.GetAlarmCategory(alarmsListBox.SelectedIndex);

                //Getting the alarm enabled status.
                bool enabled = _alarms.GetEnabledStatus(alarmsListBox.SelectedIndex);

                AlarmForm editAlarmForm = new AlarmForm(hour, minutes, category, enabled);
                editAlarmForm.ShowDialog();

                //Removing the alarm to be edited. This is so it won't think the edited alarm is a duplicate.
                _alarms.DeleteAlarmFromList(alarmsListBox.SelectedIndex);

                if (editAlarmForm.DialogResult == DialogResult.OK)
                {
                    bool alarmExists = _alarms.Search(editAlarmForm.Alarm.AlarmTime);
                    //Checking to see if the edited alarm already exists. If so removing it and the user will have to re-add the alarm.
                    if (alarmExists)
                    {
                        MessageBox.Show("Sorry, cannot edit an alarm to an already existing time. Please re-add your alarm.", this.Text, MessageBoxButtons.OK);

                        //Refreshing the alarms listbox.
                        refreshAlarmsList();
                    }
                    else
                    {
                        //Removing an re-adding the edited alarm to the _alarms list and the mainform listbox.
                        _alarms.Add(editAlarmForm.Alarm);
                        refreshAlarmsList();
                        _alarms.GetAlarmsList();    //Test method call to verify the edited alarms was added to the list. Can remove later.
                    }
                }
            }
            else
            {
                MessageBox.Show("No alarms selected for editing.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            //Checking to make sure an alarm has been selected or the listbox is populated.
            if (alarmsListBox.SelectedIndex > -1)
            {
                if (MessageBox.Show("Delete " + _alarms.GetAlarm(alarmsListBox.SelectedIndex) + " alarm?", "Delete Alarm",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    _alarms.DeleteAlarmFromList(alarmsListBox.SelectedIndex);    //Deleting the alarm from the list in Alarms.cs.
                    refreshAlarmsList();
                    _alarms.GetAlarmsList();    //Test method call to verify the alarm was removed from the list. Can remove later.
                }
            }
            else
            {
                MessageBox.Show("No alarms selected to delete.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private void alarmsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Saving the alarm list data.
            _alarms.SaveAlarmsToFile(dataPath);
        }

        private void alarmTimer_Tick(object sender, EventArgs e)
        {
            //Getting the time and changing the text on the MainForm to reflect the current time.
            DateTime timeNow = DateTime.Now;
            timeLabel.Text = timeNow.ToLongTimeString();

            //Calling the method to check the alarms list times.
            DateTime alarms = _alarms.GetNextDue(timeNow);

            //Checking to see if an alarm should be displaying.
            if (timeNow > alarms)
            {
                alarmTimer.Enabled = false;
                MessageBox.Show(alarms.ToString() + "\n" + _alarms.GetAlarmCategory(alarms), "Alarm", MessageBoxButtons.OK);
            }        
        }

        private void refreshAlarmsList()
        {
            //Un-binding and re-binding the listbox datasource. This is so the listbox can refresh itself while referencing the _alarms list.
            alarmsListBox.DataSource = null;
            alarmsListBox.DataSource = _alarms.GetAlarms();
            alarmsListBox.Refresh();
        }
    }
}

AlarmForm 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 Alarms
{
    [Serializable()]
    public partial class AlarmForm : Form
    {
        private Alarm _alarm;
        private Alarms _alarms;

        public Alarm Alarm
        {
            get { return _alarm; }
            set { _alarm = value; }
        }

        public Alarms Alarms
        {
            get { return _alarms; }
            set { _alarms = value; }
        }

        public AlarmForm()
        {
            InitializeComponent();
        }

        private void AlarmForm_Shown(object sender, EventArgs e)
        {
            //Setting the minimum and maximum values for the hour and minute boxes.
            hourNumericUpDown.Minimum = 1;
            hourNumericUpDown.Maximum = 24;
            minuteNumericUpDown.Maximum = 60;
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;

            //Getting the hour and minute values from the up/down boxes.
            DateTime rightNow = DateTime.Now;
            int hour = Convert.ToInt32(hourNumericUpDown.Value);
            int minutes = Convert.ToInt32(minuteNumericUpDown.Value);

            //Using the hour and minute values for DateTime.
            DateTime value = new DateTime(rightNow.Year, rightNow.Month, rightNow.Day, hour, minutes, 0);

            //Getting the alarm category if selected.
            string category = "";
            if (categoryComboBox.SelectedIndex > -1)
            {
                category = categoryComboBox.SelectedItem.ToString();
            }
            else
                categoryComboBox.Text = "Personal";

            //Checking to see if the alarm is enabled.
            bool isEnabled = false;
            if (enabledCheckBox.Checked)
                isEnabled = true;

            //Creating the alarm object to be added to the list.
            _alarm = new Alarm()
            {
                AlarmCategory = category,
                AlarmTime = value,
                Enabled = isEnabled
            };
        }

        //This is used to populate the form if the user is editing an existing alarm.
        public AlarmForm(int hour, int minutes, string category, bool isEnabled)
        {
            //Loading the form with all the fields.
            InitializeComponent();

            //Setting the label showing that this an existing alarm to be edited.
            errorLabel.ForeColor = Color.Red;
            errorLabel.Text = "Existing Alarm";

            //Loading all of the data into the form.
            hourNumericUpDown.Value = hour;
            minuteNumericUpDown.Value = minutes;
            categoryComboBox.Text = category;
            if (isEnabled == true)
            {
                enabledCheckBox.Checked = true;
            }
            else
                enabledCheckBox.Checked = false;
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
    }
}

Alarm 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 Alarms
{
    [Serializable()]
    public class Alarm
    {
        //Fields
        private string _alarmCategory;
        private DateTime _alarmTime;
        private bool _due;
        private bool _enabled;
        public string[] AlarmCategories = { "Personal", "Business" };

        //Properties
        public string AlarmCategory
        {
            get { return _alarmCategory; }
            set { _alarmCategory = value; }
        }

        public DateTime AlarmTime
        {
            get { return _alarmTime; }
            set { _alarmTime = value; }
        }

        public bool Due
        {
            get { return _due; }
            set { _due = value; }
        }

        public bool Enabled
        {
            get { return _enabled; }
            set { _enabled = value; }
        }

        //Methods
        public override string ToString()
        {
            return this._alarmTime.ToLongTimeString() + " - " + (this._enabled ? "Enabled" : "Disabled");
        }
    }
}

Alarms 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 Alarms
{
    [Serializable()]
    public class Alarms
    {
        //Fields
        private List _alarms = new List();

        public List GetAlarms()
        {
            return _alarms;
        }

        //Method to add the alarm to the _alarms list.
        public void Add(Alarm alarm)
        {
            _alarms.Add(alarm);
        }

        //Method to delete the selected alarm from the list.
        public void DeleteAlarmFromList(int i)
        {
            _alarms.RemoveAt(i);
        }

        //Method to count the number of items in the _alarms list.
        public int Count()
        {
            int numberOfItems = 0;
            for (int i = 0; i < _alarms.Count; i++)
            {
                numberOfItems++;
            }
            return numberOfItems;
        }

        //Method to get an alarm from the _alarms list.
        public string GetAlarm(int index)
        {
            string item = "";
            for (int i = 0; i < _alarms.Count; i++)
            {
                item = _alarms[index].AlarmTime.ToLongTimeString();
            }
            return item;
        }

        //Method to get the alarm category.
        public string GetAlarmCategory(int index)
        {
            string category = "";
            for (int i = 0; i < _alarms.Count; i++)
            {
                category = _alarms[index].AlarmCategory;
            }
            return category;
        }

        //Overload method to get the alarm category by providing the alarm time.
        public string GetAlarmCategory(DateTime alarmTime)
        {
            string category = "";
            for (int i = 0; i < _alarms.Count; i++)
            {
                if (_alarms[i].AlarmTime == alarmTime)
                {
                    category = _alarms[i].AlarmCategory;
                }
            }
            return category;
        }

        //Method to get the alarm enabled status.
        public bool GetEnabledStatus(int index)
        {
            bool isEnabled = false;
            for (int i = 0; i < _alarms.Count; i++)             {                 isEnabled = _alarms[index].Enabled;             }             return isEnabled;         }         //Method to get the alarm that's due.         public DateTime GetNextDue(DateTime time)         {             DateTime alarmDue = DateTime.Now;             //Foreach loop to search the _alarmsList times.             foreach (Alarm items in _alarms)             {                 if (time > items.AlarmTime && items.Enabled == true)
                {
                    alarmDue = items.AlarmTime;
                }
            }
            return alarmDue;
        }

        //Method for searching the alarm list for a duplicate alarm.
        public bool Search(DateTime targetAlarm)
        {
            bool alarmExists = false;
            for (int i = 0; i < _alarms.Count; i++)
            {
                if (_alarms[i].AlarmTime == targetAlarm)
                {
                    alarmExists = true;
                }
            }
            return alarmExists;
        }

        public void SnoozeAlarm(int index)
        {
        }

        //Method to load the alarms from the file data.
        public void LoadAlarmsFromFile(string fileName)
        {
            FileStream stream = File.Open(fileName, FileMode.Open);
            BinaryFormatter bin = new BinaryFormatter();
            _alarms = (List)bin.Deserialize(stream);
            stream.Close();
        }

        //Method to save the file data.
        public void SaveAlarmsToFile(string fileName)
        {
            FileStream stream = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite);
            BinaryFormatter bin = new BinaryFormatter();
            bin.Serialize(stream, _alarms);
            stream.Close();
        }

        //Test method used to see all the alarms in the list.
        public void GetAlarmsList()
        {
            foreach (Alarm items in _alarms)
            {
                Console.WriteLine(items.AlarmTime.ToLongTimeString() + " - " + (items.Enabled ? "Enabled" : "Disabled"));
            }
        }
    }
}
Advertisements

2 thoughts on “Simple Alarm Clock Program

    • Hello, no nothing is missing. It was coded this way to take care of some assignment objectives. This simple workflow is something that’s on my fix-it todo list now that I’ve finished this course. So for now the simple way is to disable the alarm then close and re-open the program.

      Also if you have an idea please feel free to modify the source code as you need.. 🙂

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