Universal Windows Platform – Pomodoro App

Pomodoro App shows how to create a simple application that can help with time management using a timer to help break down tasks with a 25 Minute Task Timer and then have a Short 5 Minute or Long 15 Minute Break inbetween.

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in the Name as PomodoroApp and select a Location and then select Ok to create the Project
vs2017-new-project-pomodoro-app

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10, version 1803 (10.0; Build 17134) which is the April 2018 Update and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-pomodoro-app

Step 7

Once in the Code View for Library.cs the following should be entered:

using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Popups;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Reflection;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using System.Text.RegularExpressions;
using Windows.UI.Xaml;
using Windows.UI;
using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;
using System.Linq;

namespace PomodoroApp
{
    public enum PomodoroType
    {
        [Description("\U0001F345")]
        TaskTimer = 25,
        [Description("\U00002615")]
        ShortBreak = 1,
        [Description("\U0001F34F")]
        LongBreak = 15
    }

    public class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected bool SetProperty<T>(ref T field, T value,
        [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        public void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }

    public class PomodoroItem : BindableBase
    {
        private PomodoroType _type;
        private Color _light;
        private Color _dark;

        private string GetGlyph(PomodoroType type)
        {
            FieldInfo info = type.GetType().GetField(type.ToString());
            DescriptionAttribute[] attr =
            (DescriptionAttribute[])info.GetCustomAttributes
            (typeof(DescriptionAttribute), false);
            return attr[0].Description;
        }

        private string GetId(PomodoroType type)
        {
            return Enum.GetName(typeof(PomodoroType), type);
        }

        private IEnumerable<string> GetName(PomodoroType type)
        {
            string text = GetId(type);
            Regex regex = new Regex(@"\p{Lu}\p{Ll}*");
            foreach (Match match in regex.Matches(text))
            {
                yield return match.Value;
            }
        }

        public PomodoroType Type
        {
            get { return _type; }
            set { SetProperty(ref _type, value); }
        }

        public Color Dark
        {
            get { return _dark; }
            set { SetProperty(ref _dark, value); }
        }

        public Color Light
        {
            get { return _light; }
            set { SetProperty(ref _light, value); }
        }

        public string Id => GetId(_type);

        public string Glyph => GetGlyph(_type);

        public string Name => string.Join(" ", GetName(_type));

        public TimeSpan TimeSpan => TimeSpan.FromMinutes((double)_type);

        public PomodoroItem(PomodoroType type, Color dark, Color light)
        {
            Type = type;
            Dark = dark;
            Light = light;
        }
    }

    public class PomodoroSetup : BindableBase
    {
        private bool _started;
        private string _display;
        private DateTime _start;
        private DateTime _finish;
        private TimeSpan _current;
        private PomodoroItem _item;
        private List<PomodoroItem> _items;
        private DispatcherTimer _timer;
        private ToastNotifier _notifier = ToastNotificationManager.CreateToastNotifier();

        private ScheduledToastNotification GetToast()
        {
            return _notifier.GetScheduledToastNotifications().FirstOrDefault();
        }

        private void ClearToast()
        {
            foreach (ScheduledToastNotification toast in _notifier.GetScheduledToastNotifications())
            {
                _notifier.RemoveFromSchedule(toast);
            }
        }

        private void AddToast(string id, string name, string glyph, DateTime start, DateTime finish)
        {
            XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            xml.GetElementsByTagName("text")[0].InnerText = $"{glyph} {name}";
            xml.GetElementsByTagName("text")[1].InnerText = $"Start {start:HH:mm} Finish {finish:HH:mm}";
            ScheduledToastNotification toast = new ScheduledToastNotification(xml, finish) { Id = id };
            _notifier.AddToSchedule(toast);
        }

        private string GetDisplay(TimeSpan timeSpan) => timeSpan.ToString(@"mm\:ss");

        private void Start()
        {
            _started = true;
            if (_timer == null)
            {
                _timer = new DispatcherTimer()
                {
                    Interval = TimeSpan.FromMilliseconds(250)
                };
                _timer.Tick += (object s, object args) =>
                {
                    TimeSpan difference = _start - DateTime.UtcNow;
                    string display = GetDisplay(_current + difference);
                    if (_started && display != GetDisplay(TimeSpan.Zero))
                    {
                        Display = display;
                    }
                    else
                    {
                        _current = TimeSpan.Zero;
                        Display = GetDisplay(_current);
                        _timer.Stop();
                        _started = false;
                    }
                };
            }
            _timer.Start();
        }

        private void Stop()
        {
            if (_timer != null) _timer.Stop();
           _started = false;
            Select(_item);
        }

        public PomodoroItem Item
        {
            get { return _item; }
            set { SetProperty(ref _item, value); }
        }

        public List<PomodoroItem> Items
        {
            get { return _items; }
            set { SetProperty(ref _items, value); }
        }

        public string Display
        {
            get { return _display; }
            set { SetProperty(ref _display, value); }
        }

        public bool Started
        {
            get { return _started; }
            set { SetProperty(ref _started, value); }
        }

        public void Select(PomodoroItem item)
        {
            Item = item;
            _current = Item.TimeSpan;
            Display = GetDisplay(_current);
        }

        public void Init()
        {
            if (Items == null)
            {
                Items = new List<PomodoroItem>
                {
                    new PomodoroItem(PomodoroType.TaskTimer, 
                    Color.FromArgb(255, 240, 58, 23), 
                    Color.FromArgb(255, 239, 105, 80)),
                    new PomodoroItem(PomodoroType.ShortBreak,
                    Color.FromArgb(255, 131, 190, 236), 
                    Color.FromArgb(255, 179, 219, 212)),
                    new PomodoroItem(PomodoroType.LongBreak,
                    Color.FromArgb(255, 186, 216, 10), 
                    Color.FromArgb(255, 228, 245, 119)),
                };
            }
            ScheduledToastNotification toast = GetToast();
            PomodoroItem item = Items[0];
            if (toast != null)
            {
                item = Items.FirstOrDefault(f => f.Id == toast.Id);
                _start = toast.DeliveryTime.UtcDateTime - item.TimeSpan;
                _finish = toast.DeliveryTime.UtcDateTime;
                Start();
            }
            Select(item);
        }

        public void Toggle()
        {
            _start = DateTime.UtcNow;
            _finish = _start.Add(TimeSpan.FromMinutes((double)Item.Type));
            if(_started)
            {
                ClearToast();
                Stop();
            }
            else
            {
                AddToast(_item.Id, _item.Name, _item.Glyph, _start, _finish);
                _current = Item.TimeSpan;
                Start();
            }
        }
    }

    public class Library
    {
        private const string app_title = "Pomodoro App";

        private IAsyncOperation<IUICommand> _dialogCommand;
        private PomodoroSetup _setup = new PomodoroSetup();

        private async Task<bool> ShowDialogAsync(string content, string title = app_title)
        {
            try
            {
                if (_dialogCommand != null)
                {
                    _dialogCommand.Cancel();
                    _dialogCommand = null;
                }
                _dialogCommand = new MessageDialog(content, title).ShowAsync();
                await _dialogCommand;
                return true;
            }
            catch (TaskCanceledException)
            {
                return false;
            }
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            AppBarButton button = (AppBarButton)sender;
            if(_setup.Started)
            {
                await ShowDialogAsync($"You will need to Stop {_setup.Item.Name} Timer to Switch");
            }
            else
            {
                _setup.Select((PomodoroItem)button.Tag);
            }
        }

        public void Init(ref CommandBar command, ref Grid display)
        {
            _setup.Init();
            if (command.PrimaryCommands.Count == 1)
            {
                foreach (PomodoroItem item in _setup.Items)
                {
                    AppBarButton button = new AppBarButton()
                    {
                        Tag = item,
                        Content = item.Name,
                        Icon = new FontIcon()
                        {
                            Glyph = item.Glyph,
                            Margin = new Thickness(0, -5, 0, 0),
                            FontFamily = new FontFamily("Segoe UI Emoji")
                        }
                    };
                    button.Click += Button_Click;
                    command.PrimaryCommands.Add(button);
                }
            }
            display.DataContext = _setup;
        }

        public void Toggle()
        {
            _setup.Toggle();
        }
    }      
}

In the Code File for Library there are using statements to include the necessary functionality. There is an enum for PomodoroApp which has values for use within the Application and also includes a Description Attribute. There is a BindableBase Class which implements INotifyPropertyChanged there are SetProperty and OnPropertyChanged Methods.

The PomodoroItem Class Inherits from BindableBase and has members for PomodoroType and Color. The GetGlyph Method is used to read the DescriptionAttribute value, GetId Method is used to get the Name of the PomodoroType Value the and GetName Method is used to return a friendly Name for the PomodoroType. There are Properties for the PomodoroType, for Color, and some string Properties and for TimeSpan.

The PomodoroSetup Class

also Inherits from BindableBase and has various Members including ones for DateTime, PomodoroItem, DispatcherTimer and ToastNotifier. There is a GetToast Method which will return the first ScheduledToastNotification or default, as null. The ClearToast Method is used to remove all ScheduledToastNotification from the ToastNotificationManager. The AddToast Method is used to create a ScheduledToastNotification with a given ToastTemplateType. The GetDisplay Method uses a Lambda to return a Formatted TimeSpan.

Also in the PomodoroSetup Class there is a Start Method which will create a DispatcherTimer which will be used to Display a Current value which involves Calculating a time difference to use as a Countdown. The Stop Method will Stop the DispatcherTimer and call a Select Method. The Select Method is used to set the PomodoroItem to use and get the Current TimeSpan for this. The Init Method is used to help create the look-and-feel of the Application and will Populate the List of PomodoroItem with the different PomodoroType Values, it will get any existing ScheduledToastNotification to retrieve an already running Timer or call the Select Method. The Toggle Method is used to either Start or Stop a Timer.

The Library Class has Members for IAsyncOperation of IUICommand for use with the ShowDialogAsync Method which will display a MessageDialog and for PomodoroSetup. There is a Button_Click Event Handler which will call the Select Method to pick a Timer or if one is Started it will display a message with ShowDialogAsync. The Init Method is used to create the Layout of the Application and add additional AppBarButton for each PomodoroItem and there is a Toggle Method which will call the Toggle Method in the PomodoroSetup Class.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-pomodoro-app

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in in this between the Grid and /Grid elements, enter the following XAML:

<Grid Name="Display" Margin="50" HorizontalAlignment="Center">
	<Grid.RowDefinitions>
		<RowDefinition Height="50*"/>
		<RowDefinition Height="50*"/>
	</Grid.RowDefinitions>
	<Grid Grid.Row="0">
		<Grid.Background>
			<SolidColorBrush Color="{Binding Path=Item.Light, Mode=OneWay}"/>
		</Grid.Background>
		<Viewbox>
			<TextBlock Text="{Binding Path=Item.Glyph, Mode=OneWay}" FontFamily="Segoe UI Emoji"/>
		</Viewbox>
	</Grid>
	<Grid Grid.Row="1">
		<Grid.Background>
			<SolidColorBrush Color="{Binding Path=Item.Dark, Mode=OneWay}"/>
		</Grid.Background>
		<Viewbox>
			<TextBlock Margin="5" Text="{Binding Path=Display, Mode=OneWay}" Foreground="WhiteSmoke"/>
		</Viewbox>
	</Grid>
</Grid>
<CommandBar Name="Command" VerticalAlignment="Bottom">
	<AppBarButton Name="Timer" Icon="Clock" Label="Timer" Click="Timer_Click"/>
</CommandBar>

Within the main Grid Element, the first block of XAML is a Grid Control which has two Rows, in the first Row is a TextBlock which will display the Glyph for a PomodoroItem and is within a Grid which has a Background set to the Light Property and in the second Row is another Grid with another TextBlock set to the Display Property and is within a Grid with its Background set to the Dark Property. The second block of XAML is a CommandBar with AppBarButton for Time which calls Timer_Click.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

protected override void OnNavigatedTo(NavigationEventArgs e)
{
	library.Init(ref Command, ref Display);
}

private void Timer_Click(object sender, RoutedEventArgs e)
{
	library.Toggle();
}

There is an OnNavigatedTo Event Handler which calls the Init Method in the Library Class and Timer_Click which calls the Toggle Method of the Library Class.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

Once the Application has started running you can select the Timer Button to Start or Stop the Task Timer and then do some work or select the Short Break or Long Break to rest – at the end of the time a Toast Notification will appear

uwp-ran-pomodoro-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

This example shows how to implement the Pomodoro Technique created by Francesco Cirillo which involves deciding on a Task to perform then setting a Timer to 25 Minutes, then once done have a Short Break of 5 Minutes, then every Four Tasks performed then take a Long Break of 15 Minutes and then repeat the process again. This is a useful working technique and also is a great way on how to use ScheduledToastNotification and other features to create an application like this.

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

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