Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

August 27, 2009

Building an Alarm Class

Filed under: C#,OOP,VB.NET @ 12:21 pm

The specifics of this class demonstrate how to build an alarm. You can use this class to build an alarm clock application, or to add an alarm feature into your application, similar to the Reminder feature in Outlook.

OR you can just use this class as an example of raising events from a business object or displaying sounds asynchronously.

Build the Alarm class as follows.

In C#:

// Declare a delegate
public delegate void AlarmWentOffHandler(object sender, EventArgs e);

public class Alarm
{
    // Declare an event
    public event AlarmWentOffHandler AlarmWentOff;

    public DateTime? AlarmTime { get; set; }
    private Timer AlarmTimer { get; set; }
    public int SnoozeInterval { get; set; }

    public Alarm() : this(null, 5)
    {  }

    public Alarm(DateTime? timeForAlarm): this(timeForAlarm, 5)
    {  }

    public Alarm(DateTime? timeForAlarm, int minutesToSnooze)
    {
        // Set the properties
        AlarmTime = timeForAlarm;
        SnoozeInterval = minutesToSnooze;

        // Start the timer
        AlarmTimer = new Timer() {Interval = 10000,
                                  Enabled = true};
        AlarmTimer.Tick += CheckAlarm;
    }

    public void Snooze()
    {
        // Reset the alarm by the snooze interval
        AlarmTime = DateTime.Now.AddMinutes(SnoozeInterval);

        // Reset the timer
        AlarmTimer.Enabled = true;
    }

    protected virtual void OnAlarmWentOff(EventArgs e)
    {
        if (AlarmWentOff != null)
            AlarmWentOff(this, e);
    }

    private void CheckAlarm(object sender,
                            EventArgs e)
    {
        // Check whether alarm time has been reached
        if (AlarmTime <= DateTime.Now)
        {
            // Disable the timer
            AlarmTimer.Enabled = false;

            // Raise the event
            OnAlarmWentOff(new EventArgs());
        }
    }
}

In VB:

Public Class Alarm
    Event AlarmWentOff(ByVal sender As Object, ByVal e As EventArgs)

    Private _AlarmTime As DateTime?
    Public Property AlarmTime() As DateTime?
        Get
            Return _AlarmTime
        End Get
        Set(ByVal value As DateTime?)
            _AlarmTime = value
        End Set
    End Property

    Private _AlarmTimer As Timer
    Private Property AlarmTimer() As Timer
        Get
            Return _AlarmTimer
        End Get
        Set(ByVal value As Timer)
            _AlarmTimer = value
        End Set
    End Property

    Private _SnoozeInterval As Integer
    Public Property SnoozeInterval() As Integer
        Get
            Return _SnoozeInterval
        End Get
        Set(ByVal value As Integer)
            _SnoozeInterval = value
        End Set
    End Property

    Public Sub New()
        ‘ Set Defaults
        Me.New(Nothing, 5)
    End Sub

    Public Sub New(ByVal timeForAlarm As DateTime?)
        ‘ Set Defaults
        Me.New(timeForAlarm, 5)
    End Sub

    Public Sub New(ByVal timeForAlarm As DateTime?, _
                   ByVal minutesToSnooze As Integer)
        ‘ Set the properties
        AlarmTime = timeForAlarm
        SnoozeInterval = minutesToSnooze

        ‘ Start the timer
        AlarmTimer = New Timer With {.Interval = 10000, _
                                     .Enabled = True}
        AddHandler AlarmTimer.Tick, AddressOf CheckAlarm
    End Sub

    Public Sub Snooze()
        ‘ Reset the alarm by the snooze interval
        AlarmTime = Now.AddMinutes(SnoozeInterval)

        ‘ Reset the timer
        AlarmTimer.Enabled = True
    End Sub

    Private Sub CheckAlarm(ByVal sender As Object, _
                           ByVal e As EventArgs)
        ‘ Check whether alarm time has been reached
        If AlarmTime <= Now Then
            ‘ Disable the timer
            AlarmTimer.Enabled = False

            ‘ Raise the event
            RaiseEvent AlarmWentOff(Me, New EventArgs())
        End If

    End Sub
End Class

The C# code begins by declaring a delegate for its event. This is not required in the VB code since the delegate is handled for you.

Within the class, the C# and VB code declare an event called AlarmWentOff. This is the event that is generated when the alarm goes off.

The class has three properties:

  • AlarmTime: Time that the alarm should go off.
  • AlarmTimer: A private property that manages the timer for checking the alarm time.
  • SnoozeInterval: The alarm can optionally be set to snooze. This is the amount of snooze time in minutes.

The C# code uses auto-implemented properties and the VB code uses the expanded property syntax. (VB is getting auto-implemented properties in VB 10.)

The constructors for the class optionally define the alarm time and minutes to snooze. The constructor then starts the timer that goes off every 10 seconds. (This can be adjusted as desired. Or the timer interval could be defined as a property of this Alarm class.)

The class has one public method: Snooze. The Snooze method adds the snooze interval amount to the AlarmTime to reset the alarm. It also ensures that the timer in enabled.

Each time the timer goes off, the code checks the current time against the alarm time. If the alarm time has been reached, the code disables the timer and raises the AlarmWentOff event.

This class can be used whenever you need to add an alarm, notification, or reminder to your application. Here is an example of how this class is accessed.

NOTE: It uses a .wav file for the alarm and plays it using the built-in SoundPlayer.

Start by adding this to the top of your code file.

In C#:

using System.Media;

In VB:

Imports System.Media

Then add the following code somewhere in your user interface.

In C#:

Alarm myAlarm;
private void SetTheAlarm()
{
    // Create an alarm object
    myAlarm = new Alarm(DateTime.Now.AddMinutes(1), 1);
    myAlarm.AlarmWentOff +=  AlarmWentOff;
}

private void AlarmWentOff(object sender, EventArgs e)
{
    var player = new SoundPlayer("myFile.wav");
    player.PlayLooping();
    DialogResult replay =
        MessageBox.Show("Wake up" +
                             Environment.NewLine +
                             "Yes to wake up." +
                             Environment.NewLine +
                             "No to snooze.",
                        "Alarm Clock",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Exclamation);
    player.Stop();
    if (replay != DialogResult.Yes)
        myAlarm.Snooze();
}

In VB:

Dim myAlarm As Alarm
Private Sub SetTheAlarm()
    ‘ Create an alarm object
    myAlarm = New Alarm(Now.AddMinutes(1), 1)
    AddHandler myAlarm.AlarmWentOff, AddressOf AlarmWentOff
End Sub

Private Sub AlarmWentOff(ByVal sender As Object, ByVal e As EventArgs)
    Dim player As New SoundPlayer("myFile.wav")
    player.PlayLooping()
    Dim replay As DialogResult = _
        MessageBox.Show("Wake up" & _
                             Environment.NewLine & _
                             "Yes to wake up." & _
                             Environment.NewLine & _
                             "No to snooze.", _
                        "Alarm Clock", _
                        MessageBoxButtons.YesNo, _
                        MessageBoxIcon.Exclamation)
    player.Stop()
    If replay <> DialogResult.Yes Then
        myAlarm.Snooze()
    End If
End Sub

This code defines a variable that references the Alarm class. In a SetTheAlarm method, the class creates an instance of the class, passing in an alarm time and snooze interval.

For testing, this is set to 1 minute from the current time and the snooze is set to one minute. In most cases, you would want to get the alarm time from the user.

When the alarm goes off, this code plays a .wav file using the SoundPlayer provided in .NET. Be sure to change the .wav file name to the directory and file name of a .wav file on your system.

The PlayLooping method of the SoundPlayer is used to play the sound continuously. This method is asynchronous, so the code will continue to the next line.

The example displays a message box, allowing the user to cancel the alarm or snooze the alarm. In either cause, the code calls the Stop method of the SoundPlayer to stop the .wav file. If the user requested to snooze, it calls the alarm’s Snooze method.

Enjoy!

4 Comments

  1.   es — September 3, 2009 @ 1:28 pm    Reply

    what timers ?? what class ? there are three timers class !!!

  2.   DeborahK — September 3, 2009 @ 2:11 pm    Reply

    Hi es –

    Thank you for visiting my blog.

    It does not really matter to the code which timer you use. Rather, it will depend on your application.

    I used the System.Windows.Forms.Timer because my example was executed from a WinForm. You may want to pick one of the others, depending on how you use this class.

  3.   Shriti — November 12, 2009 @ 1:20 am    Reply

    This is what i was looking for :D,
    Thankyou!!

  4.   megha — March 29, 2011 @ 12:55 am    Reply

    will umake this application in objective c?

RSS feed for comments on this post. TrackBack URI

Leave a comment

*

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs