Capstone C: the form, and what we could not run

The third capstone ends with its form, and the course ends with this page. The form is four files and is built here as the other two capstones were. The audit that follows is the honest summary of the course: which of its programs were compiled only, which were also run, and what no page of it could check. The last section is what to build next.

Four files

Todo/ app.csproj nuget.config Program.cs the entry point and the load TodoModel.cs the task, the list and the repository TodoPresenter.cs the IView, the commands and the presenter TodoForm.cs the list box, the menus and the title dialog

The presenter is the one of lesson 078 with a Changed event added, so the form can save after every command without the presenter knowing what a file is. The model is lesson 077 plus the repository of lesson 079.

Program.cs

Main chooses the file, loads it when it exists, and gives the list and the repository to the form. This is the composition root again: the only place that knows the path and the concrete types.

The file is Program.cs:

using System; using System.IO; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); var path = Path.Combine(AppContext.BaseDirectory, "todo.json"); var repository = new TodoRepository(path); var list = File.Exists(path) ? repository.Load() : new TaskList(); Application.Run(new TodoForm(list, repository)); } }

TodoModel.cs

The state machine, the list, the DTOs and the repository. The JSON options are the ones of lesson 079, passed to both directions, and the restore moves the id counter past the highest saved id.

The file is TodoModel.cs:

using System; using System.Collections.Generic; using System.IO; using System.Text.Json; internal enum TaskState { New, Active, Done, } internal sealed class TodoItem { internal TodoItem(string id, string title, TaskState state) { Id = id; Title = title; State = state; } public string Id { get; } public string Title { get; } public TaskState State { get; private set; } public void Start() { if (State != TaskState.New) { throw new InvalidOperationException($"Cannot start a task in state {State}."); } State = TaskState.Active; } public void Complete() { if (State == TaskState.New) { Start(); } if (State != TaskState.Active) { throw new InvalidOperationException($"Cannot complete a task in state {State}."); } State = TaskState.Done; } internal void Restore(TaskState state) => State = state; } internal sealed class TaskList { private readonly List<TodoItem> _items = new(); private int _next = 1; public IReadOnlyList<TodoItem> Items => _items; public int Count => _items.Count; public int ActiveCount => _items.FindAll(item => item.State == TaskState.Active).Count; public int DoneCount => _items.FindAll(item => item.State == TaskState.Done).Count; public TodoItem Add(string title) { var trimmed = title.Trim(); if (trimmed.Length == 0) { throw new ArgumentException("A title must not be empty.", nameof(title)); } foreach (var item in _items) { if (string.Equals(item.Title, trimmed, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException($"Cannot add '{trimmed}': the title is already used."); } } var added = new TodoItem($"T-{_next++}", trimmed, TaskState.New); _items.Add(added); return added; } public TodoItem? Find(string id) => _items.Find(item => item.Id == id); public bool Remove(string id) { var item = Find(id); return item is not null && _items.Remove(item); } public int IndexOf(string id) => _items.FindIndex(item => item.Id == id); public void Insert(int index, TodoItem item) => _items.Insert(Math.Clamp(index, 0, _items.Count), item); public void RemoveAt(int index) => _items.RemoveAt(index); public void Restore(string id, string title, TaskState state) { _items.Add(new TodoItem(id, title, state)); if (int.TryParse(id.AsSpan(2), out var number)) { _next = Math.Max(_next, number + 1); } } } internal sealed record TaskDto(string Id, string Title, string State); internal sealed record Envelope(int Version, List<TaskDto> Tasks); internal sealed class TodoRepository { public const int CurrentVersion = 1; private static readonly JsonSerializerOptions Options = new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; private readonly string _path; public TodoRepository(string path) => _path = path; public void Save(TaskList list) { var tasks = new List<TaskDto>(); foreach (var item in list.Items) { tasks.Add(new TaskDto(item.Id, item.Title, item.State.ToString())); } File.WriteAllText(_path, JsonSerializer.Serialize(new Envelope(CurrentVersion, tasks), Options)); } public TaskList Load() { var envelope = JsonSerializer.Deserialize<Envelope>(File.ReadAllText(_path), Options)!; if (envelope.Version != CurrentVersion) { throw new InvalidDataException($"Unsupported version {envelope.Version}."); } var list = new TaskList(); foreach (var task in envelope.Tasks) { list.Restore(task.Id, task.Title, Enum.Parse<TaskState>(task.State)); } return list; } }

TodoPresenter.cs

The presenter and its three commands. Changed is raised after every successful command and after undo and redo, and the form saves the list in its handler. The presenter never names File.

The file is TodoPresenter.cs:

using System; using System.Collections.Generic; internal interface ITodoView { void ShowItems(IReadOnlyList<string> items); int SelectedIndex { get; } string Status { set; } bool CanUndo { set; } bool CanRedo { set; } void ClearSelection(); string? AskTitle(); bool ConfirmRemove(); event EventHandler? AddRequested; event EventHandler? CompleteRequested; event EventHandler? RemoveRequested; event EventHandler? UndoRequested; event EventHandler? RedoRequested; } internal interface IUndoable { void Do(); void Undo(); } internal sealed class TodoPresenter { private readonly TaskList _list; private readonly ITodoView _view; private readonly Stack<IUndoable> _undo = new(); private readonly Stack<IUndoable> _redo = new(); public TodoPresenter(TaskList list, ITodoView view) { _list = list; _view = view; view.AddRequested += OnAdd; view.CompleteRequested += OnComplete; view.RemoveRequested += OnRemove; view.UndoRequested += (sender, e) => Undo(); view.RedoRequested += (sender, e) => Redo(); Refresh(); } public event EventHandler? Changed; public TaskList List => _list; private void OnAdd(object? sender, EventArgs e) { var title = _view.AskTitle(); if (string.IsNullOrWhiteSpace(title)) { _view.Status = "A title is required."; return; } if (Run(new AddTask(_list, title))) { _view.Status = $"Added '{title.Trim()}'."; } } private void OnComplete(object? sender, EventArgs e) { var item = Selected(); if (item is null) { return; } if (Run(new CompleteTask(item))) { _view.Status = $"Completed '{item.Title}'."; } } private void OnRemove(object? sender, EventArgs e) { var item = Selected(); if (item is null) { return; } if (!_view.ConfirmRemove()) { _view.Status = "Remove cancelled."; return; } if (Run(new RemoveTask(_list, item))) { _view.Status = $"Removed '{item.Title}'."; } } private TodoItem? Selected() { var index = _view.SelectedIndex; if (index < 0 || index >= _list.Count) { _view.Status = "Select a task first."; return null; } return _list.Items[index]; } private bool Run(IUndoable command) { try { command.Do(); _undo.Push(command); _redo.Clear(); Refresh(); Changed?.Invoke(this, EventArgs.Empty); return true; } catch (Exception error) when (error is InvalidOperationException or ArgumentException) { _view.Status = error.Message; return false; } } private void Undo() { if (_undo.Count == 0) { return; } var command = _undo.Pop(); command.Undo(); _redo.Push(command); Refresh(); _view.Status = "Undo."; Changed?.Invoke(this, EventArgs.Empty); } private void Redo() { if (_redo.Count == 0) { return; } var command = _redo.Pop(); command.Do(); _undo.Push(command); Refresh(); _view.Status = "Redo."; Changed?.Invoke(this, EventArgs.Empty); } private void Refresh() { var items = new List<string>(); foreach (var item in _list.Items) { items.Add($"{item.Title} [{item.State}]"); } _view.ShowItems(items); _view.CanUndo = _undo.Count > 0; _view.CanRedo = _redo.Count > 0; if (_view.SelectedIndex >= _list.Count) { _view.ClearSelection(); } } } internal sealed class AddTask : IUndoable { private readonly TaskList _list; private readonly string _title; private TodoItem? _item; public AddTask(TaskList list, string title) { _list = list; _title = title; } public void Do() { _item ??= _list.Add(_title); if (_list.Find(_item.Id) is null) { _list.Insert(_list.Count, _item); } } public void Undo() { if (_item is not null) { _list.Remove(_item.Id); } } } internal sealed class CompleteTask : IUndoable { private readonly TodoItem _item; private TaskState _before; public CompleteTask(TodoItem item) => _item = item; public void Do() { _before = _item.State; _item.Complete(); } public void Undo() => _item.Restore(_before); } internal sealed class RemoveTask : IUndoable { private readonly TaskList _list; private readonly TodoItem _item; private readonly int _index; public RemoveTask(TaskList list, TodoItem item) { _list = list; _item = item; _index = list.IndexOf(item.Id); } public void Do() => _list.RemoveAt(_index); public void Undo() => _list.Insert(_index, _item); }

TodoForm.cs

A list box, a File menu with Add, an Edit menu with Complete, Remove, Undo and Redo, a status strip, and a small dialog for the title. The buttons follow the selection: Complete and Remove are enabled only when something is selected. A double click on a task completes it, which is the shortcut a user tries first.

The file is TodoForm.cs:

using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; internal sealed class TodoForm : Form, ITodoView { private readonly ListBox _items = new() { Dock = DockStyle.Fill, IntegralHeight = false }; private readonly ToolStripStatusLabel _status = new("Ready."); private readonly ToolStripMenuItem _undo = new("&Undo"); private readonly ToolStripMenuItem _redo = new("&Redo"); private readonly ToolStripMenuItem _complete = new("&Complete"); private readonly ToolStripMenuItem _remove = new("&Remove"); private readonly TodoPresenter _presenter; public TodoForm(TaskList list, TodoRepository repository) { Text = "To-do"; ClientSize = new Size(420, 420); _undo.Click += (sender, e) => UndoRequested?.Invoke(this, EventArgs.Empty); _redo.Click += (sender, e) => RedoRequested?.Invoke(this, EventArgs.Empty); _complete.Click += (sender, e) => CompleteRequested?.Invoke(this, EventArgs.Empty); _remove.Click += (sender, e) => RemoveRequested?.Invoke(this, EventArgs.Empty); var menu = new MenuStrip(); var file = new ToolStripMenuItem("&File"); file.DropDownItems.Add("&Add...", null, (sender, e) => AddRequested?.Invoke(this, EventArgs.Empty)); file.DropDownItems.Add(new ToolStripSeparator()); file.DropDownItems.Add("E&xit", null, (sender, e) => Close()); var edit = new ToolStripMenuItem("&Edit"); edit.DropDownItems.Add(_complete); edit.DropDownItems.Add(_remove); edit.DropDownItems.Add(new ToolStripSeparator()); edit.DropDownItems.Add(_undo); edit.DropDownItems.Add(_redo); menu.Items.Add(file); menu.Items.Add(edit); MainMenuStrip = menu; var status = new StatusStrip(); status.Items.Add(_status); _items.SelectedIndexChanged += (sender, e) => UpdateButtons(); _items.DoubleClick += (sender, e) => CompleteRequested?.Invoke(this, EventArgs.Empty); Controls.Add(_items); Controls.Add(status); Controls.Add(menu); _presenter = new TodoPresenter(list, this); _presenter.Changed += (sender, e) => Save(repository); UpdateButtons(); } void ITodoView.ShowItems(IReadOnlyList<string> items) { _items.BeginUpdate(); _items.Items.Clear(); foreach (var item in items) { _items.Items.Add(item); } _items.EndUpdate(); if (_items.Items.Count > 0 && _items.SelectedIndex < 0) { _items.SelectedIndex = 0; } } int ITodoView.SelectedIndex => _items.SelectedIndex; string ITodoView.Status { set => _status.Text = value; } bool ITodoView.CanUndo { set => _undo.Enabled = value; } bool ITodoView.CanRedo { set => _redo.Enabled = value; } void ITodoView.ClearSelection() => _items.ClearSelected(); string? ITodoView.AskTitle() { using var dialog = new TitleDialog(); return dialog.ShowDialog(this) == DialogResult.OK ? dialog.Title : null; } bool ITodoView.ConfirmRemove() => MessageBox.Show( this, "Remove the selected task?", "To-do", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; public event EventHandler? AddRequested; public event EventHandler? CompleteRequested; public event EventHandler? RemoveRequested; public event EventHandler? UndoRequested; public event EventHandler? RedoRequested; private void UpdateButtons() { var has = _items.SelectedIndex >= 0; _complete.Enabled = has; _remove.Enabled = has; } private void Save(TodoRepository repository) { try { repository.Save(_presenter.List); } catch (System.IO.IOException error) { _status.Text = error.Message; } } private sealed class TitleDialog : Form { private readonly TextBox _title = new() { Location = new Point(16, 16), Width = 280 }; private readonly Button _ok = new() { Text = "OK", DialogResult = DialogResult.OK, Location = new Point(120, 52) }; private readonly Button _cancel = new() { Text = "Cancel", DialogResult = DialogResult.Cancel, Location = new Point(208, 52) }; public TitleDialog() { Text = "Add a task"; ClientSize = new Size(312, 92); FormBorderStyle = FormBorderStyle.FixedDialog; MaximizeBox = false; MinimizeBox = false; StartPosition = FormStartPosition.CenterParent; AcceptButton = _ok; CancelButton = _cancel; Controls.Add(new Label { Text = "&Title:", AutoSize = true, Location = new Point(16, 20) }); Controls.Add(_title); Controls.Add(_ok); Controls.Add(_cancel); } public string Title => _title.Text; } }

The build

The four blocks above were extracted from this page as rendered, written into a folder with the project file and the feed, and built together:

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The build is real and it is the whole application. Like the other two capstones, the per-block checker reports Program.cs as skipped because the form and the presenter are other files; the assembled build is what proves the four fit.

The form is not run, and that is the boundary of the course: it draws a window, and WinForms needs Windows. The presenter and the model it drives were run in the two lessons before, against a fake view, and that is the part a window would drive.

The audit of the course

The course has eighty lessons. Of them, 71 show at least one program that was built for net10.0-windows and never started, and 63 show logic that was also run on this machine. Across the course the checker counted 225 code blocks, built the 90 that are whole programs (85 cleanly, 2 that teach a compiler error and 3 capstone entry points assembled with their files), and the pages hold 69 console programs whose output is a real run.

What was built only is what draws: every form, every control on it, the designer files read as code, the dialogs, the paint handlers, the custom controls, the interop signatures that call a Windows DLL, and the three capstone applications. What was run is what has no window: the validators, the presenters against fake views, the view models, the undo stacks, the cancellation loops, the CSV and JSON code, the hit-test arithmetic, the publish commands, dotnet format, and the metadata of a P/Invoke signature.

Three things were never checked, and no page of the course pretends otherwise:

That is not a weakness of the course; it is its subject. A WinForms application that keeps its logic in presenters and view models is exactly the application that can be checked on a machine with no Windows, and the course made that point in every part.

What to build next

Three places continue from here, and each has a hub that says what it will cover:

A last suggestion for practice: take one capstone and make it yours. Add recent files that survive a restart to the notes app, an editable grid to the CSV viewer, or a due date and a filter to the to-do list. Each one is a small feature that touches the model, the presenter, the view and the tests, which is the whole shape of the work this course taught.

Exercises

  1. Add a filter box to the to-do form that hides the done tasks, and say which layer owns the filter.
  2. Save the list to %LOCALAPPDATA% instead of the application folder and explain which Windows API gives the path.
  3. Write, from memory, the list of every part of this course and one thing you can now do that you could not at the start.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many files does the to-do application have?

    Answer

    Four C# files, plus the project file and the feed config

    Program, model, presenter and form.

  2. What does the presenter raise so the form can save?

    Answer

    A Changed event after every command and undo

    The presenter stays free of the file system.

  3. When are Complete and Remove enabled?

    Answer

    When a task is selected

    The presenter needs a selection to act on.

  4. How was the four-file application checked?

    Answer

    The files were assembled from this page and built together

    The multi-file build is the check for a capstone.

  5. Which listings were built only?

    Answer

    The ones that draw a window

    No window can be drawn in the container.

  6. Which part of the course was also run?

    Answer

    The presenters, view models and other logic with no window

    That is the part the fake view and the console drive.

  7. Why was no installer made?

    Answer

    ClickOnce, MSIX and signing need Windows, the SDK and packs

    Lesson 067 shows the real errors of what can be attempted.

  8. What does the course say about screenshots?

    Answer

    There is none, and none is faked

    The behaviour is documented behaviour, never an observation.

  9. Which hub continues with the retained-mode stack?

    Answer

    WPF

    WPF is the other Windows desktop stack.

  10. What is the suggested practice after the course?

    Answer

    Take one capstone and add a feature that touches model, presenter, view and tests

    The shape of the work is the point of the capstones.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The four files of the application were assembled from this page and built together, as the build section says.

Article author: Arthur Isaev