Capstone A: the presenter
The presenter of the notes application is the part that decides what New, Open, Save and Find mean. It reads the document, asks the view for a path or a confirmation, and writes back a title and a status line. In this lesson it is driven by a fake view and a store in memory, so every branch runs on this machine.
The view interface
The interface is written from the presenter's side. It has the text it reads and writes, a title and a status to show, four questions it may ask the user, a selection it may set, and four events for the commands:
internal interface INotesView
{
string Text { get; set; }
string Title { set; }
string Status { set; }
bool ConfirmDiscard();
string? AskOpenPath();
string? AskSavePath();
string? AskFindText();
void Select(int start, int length);
event EventHandler? NewRequested;
event EventHandler? OpenRequested;
event EventHandler? SaveRequested;
event EventHandler? FindRequested;
}
The three Ask methods return null when the user cancels, which is the value the presenter tests. They are methods rather than properties because each one can open a dialog and wait, and because a property that blocks is a trap for the next reader. ConfirmDiscard returns a bool instead: the answer is yes or no, never a value.
The alternative design puts the dialogs in the presenter with OpenFileDialog directly. It is shorter and it is untestable: the fake view could not answer, and every test would need a desktop session. The interface is the seam that makes this page possible.
The presenter
One event handler per command, a Sync that copies the document into the view, and one guard that both New and Open use:
internal sealed class NotesPresenter
{
private readonly INotesView _view;
private readonly NoteDocument _document;
private readonly RecentFiles _recent;
public NotesPresenter(INotesView view, NoteDocument document, RecentFiles recent)
{
_view = view;
_document = document;
_recent = recent;
view.NewRequested += OnNew;
view.OpenRequested += OnOpen;
view.SaveRequested += OnSave;
view.FindRequested += OnFind;
}
private void OnNew(object? sender, EventArgs e)
{
if (!LeaveCurrent())
{
return;
}
_document.New();
Sync();
_view.Status = "New document.";
}
private void OnOpen(object? sender, EventArgs e)
{
if (!LeaveCurrent())
{
return;
}
var path = _view.AskOpenPath();
if (path is null)
{
return;
}
try
{
_document.Open(path);
_recent.Add(path);
Sync();
_view.Status = $"Opened {path}.";
}
catch (Exception error) when (error is System.IO.IOException or UnauthorizedAccessException)
{
_view.Status = error.Message;
}
}
private void OnSave(object? sender, EventArgs e)
{
var path = _document.FilePath ?? _view.AskSavePath();
if (path is null)
{
_view.Status = "Save cancelled.";
return;
}
try
{
_document.Save(path);
_recent.Add(path);
Sync();
_view.Status = $"Saved {path}.";
}
catch (Exception error) when (error is System.IO.IOException or UnauthorizedAccessException)
{
_view.Status = error.Message;
}
}
private void OnFind(object? sender, EventArgs e)
{
var needle = _view.AskFindText();
if (string.IsNullOrEmpty(needle))
{
return;
}
var index = _document.Find(needle, 0);
if (index < 0)
{
_view.Status = $"'{needle}' was not found.";
return;
}
_view.Select(index, needle.Length);
_view.Status = $"Found '{needle}' at {index}.";
}
public void TextChanged()
{
_document.SetText(_view.Text);
UpdateTitle();
}
private bool LeaveCurrent()
{
if (!_document.IsDirty)
{
return true;
}
return _view.ConfirmDiscard();
}
private void Sync()
{
_view.Text = _document.Text;
UpdateTitle();
}
private void UpdateTitle() =>
_view.Title = _document.IsDirty ? $"{_document.Title} *" : _document.Title;
}
Three details are worth reading twice. TextChanged is public because the form calls it from its text box, and it updates the title without writing the text back, which would move the caret. LeaveCurrent is the one place that asks about unsaved changes, so New and Open cannot disagree about it. And the two catch filters name the exceptions a file operation raises; anything else is a bug and is allowed to reach the top, where the UnhandledException handler of the application can log it.
The dirty guard
The guard is one question with three outcomes: the document is clean, so continue; it is dirty and the user confirms, so continue; it is dirty and the user refuses, so stop. The presenter stops by returning from the handler, and the document is untouched, which is why the title still shows the asterisk.
A close button needs the same guard, and the form gets it from FormClosing: ask the presenter whether it is safe to close, set e.Cancel when it is not. That method is not in this lesson's interface because it is the form's own event, but the decision behind it is the same LeaveCurrent, which is why it is a method and not inline code in OnNew.
The presenter in a program that runs
The whole program: the document and the presenter at the bottom, the fake view in the middle, and a driver at the top that walks through nine steps. It was built and run in the container:
using System;
using System.Collections.Generic;
using System.IO;
Console.WriteLine("the notes presenter against a fake view");
var store = new MemoryStore();
store.Save("/notes/todo.txt", "Buy milk\nCall Ada");
var document = new NoteDocument(store);
var view = new FakeView();
var presenter = new NotesPresenter(view, document, new RecentFiles());
Console.WriteLine("-- a new document");
view.RaiseNew();
Console.WriteLine($"title: {view.Title}");
Console.WriteLine($"status: {view.Status}");
Console.WriteLine("-- typing marks the title");
view.Text = "Hello";
presenter.TextChanged();
Console.WriteLine($"title: {view.Title}");
Console.WriteLine("-- New with the discard refused");
view.DiscardAnswer = false;
view.RaiseNew();
Console.WriteLine($"title: {view.Title}");
Console.WriteLine($"text: '{view.Text}'");
Console.WriteLine("-- New with the discard accepted");
view.DiscardAnswer = true;
view.RaiseNew();
Console.WriteLine($"title: {view.Title}");
Console.WriteLine($"text: '{view.Text}'");
Console.WriteLine("-- Open todo.txt");
view.NextOpenPath = "/notes/todo.txt";
view.RaiseOpen();
Console.WriteLine($"title: {view.Title}");
Console.WriteLine($"status: {view.Status}");
Console.WriteLine($"text: {view.Text.Replace("\n", " | ")}");
Console.WriteLine("-- Find ada");
view.NextFindText = "ada";
view.RaiseFind();
Console.WriteLine($"status: {view.Status}");
Console.WriteLine($"selection: {view.Selection.Start}, {view.Selection.Length}");
Console.WriteLine("-- Find zzz");
view.NextFindText = "zzz";
view.RaiseFind();
Console.WriteLine($"status: {view.Status}");
Console.WriteLine("-- Type and Save to the same path");
view.Text = "Buy milk\nCall Ada!";
presenter.TextChanged();
Console.WriteLine($"title: {view.Title}");
view.NextSavePath = null;
view.RaiseSave();
Console.WriteLine($"status: {view.Status}");
Console.WriteLine($"title: {view.Title}");
Console.WriteLine($"store: {store.Load("/notes/todo.txt").Replace("\n", " | ")}");
internal interface INotesView
{
string Text { get; set; }
string Title { set; }
string Status { set; }
bool ConfirmDiscard();
string? AskOpenPath();
string? AskSavePath();
string? AskFindText();
void Select(int start, int length);
event EventHandler? NewRequested;
event EventHandler? OpenRequested;
event EventHandler? SaveRequested;
event EventHandler? FindRequested;
}
internal sealed class FakeView : INotesView
{
public string Text { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
public bool DiscardAnswer { get; set; }
public string? NextOpenPath { get; set; }
public string? NextSavePath { get; set; }
public string? NextFindText { get; set; }
public (int Start, int Length) Selection { get; private set; }
public bool ConfirmDiscard() => DiscardAnswer;
public string? AskOpenPath() => NextOpenPath;
public string? AskSavePath() => NextSavePath;
public string? AskFindText() => NextFindText;
public void Select(int start, int length) => Selection = (start, length);
public void RaiseNew() => NewRequested?.Invoke(this, EventArgs.Empty);
public void RaiseOpen() => OpenRequested?.Invoke(this, EventArgs.Empty);
public void RaiseSave() => SaveRequested?.Invoke(this, EventArgs.Empty);
public void RaiseFind() => FindRequested?.Invoke(this, EventArgs.Empty);
public event EventHandler? NewRequested;
public event EventHandler? OpenRequested;
public event EventHandler? SaveRequested;
public event EventHandler? FindRequested;
}
internal sealed class NotesPresenter
{
private readonly INotesView _view;
private readonly NoteDocument _document;
private readonly RecentFiles _recent;
public NotesPresenter(INotesView view, NoteDocument document, RecentFiles recent)
{
_view = view;
_document = document;
_recent = recent;
view.NewRequested += OnNew;
view.OpenRequested += OnOpen;
view.SaveRequested += OnSave;
view.FindRequested += OnFind;
}
private void OnNew(object? sender, EventArgs e)
{
if (!LeaveCurrent())
{
return;
}
_document.New();
Sync();
_view.Status = "New document.";
}
private void OnOpen(object? sender, EventArgs e)
{
if (!LeaveCurrent())
{
return;
}
var path = _view.AskOpenPath();
if (path is null)
{
return;
}
try
{
_document.Open(path);
_recent.Add(path);
Sync();
_view.Status = $"Opened {path}.";
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{
_view.Status = error.Message;
}
}
private void OnSave(object? sender, EventArgs e)
{
var path = _document.FilePath ?? _view.AskSavePath();
if (path is null)
{
_view.Status = "Save cancelled.";
return;
}
try
{
_document.Save(path);
_recent.Add(path);
Sync();
_view.Status = $"Saved {path}.";
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{
_view.Status = error.Message;
}
}
private void OnFind(object? sender, EventArgs e)
{
var needle = _view.AskFindText();
if (string.IsNullOrEmpty(needle))
{
return;
}
var index = _document.Find(needle, 0);
if (index < 0)
{
_view.Status = $"'{needle}' was not found.";
return;
}
_view.Select(index, needle.Length);
_view.Status = $"Found '{needle}' at {index}.";
}
public void TextChanged()
{
_document.SetText(_view.Text);
UpdateTitle();
}
private bool LeaveCurrent()
{
if (!_document.IsDirty)
{
return true;
}
return _view.ConfirmDiscard();
}
private void Sync()
{
_view.Text = _document.Text;
UpdateTitle();
}
private void UpdateTitle() =>
_view.Title = _document.IsDirty ? $"{_document.Title} *" : _document.Title;
}
internal interface INotesStore
{
string Load(string path);
void Save(string path, string text);
}
internal sealed class MemoryStore : INotesStore
{
private readonly Dictionary<string, string> _files = new();
public string Load(string path) => _files[path];
public void Save(string path, string text) => _files[path] = text;
}
internal sealed class NoteDocument
{
private readonly INotesStore _store;
public NoteDocument(INotesStore store) => _store = store;
public string Text { get; private set; } = string.Empty;
public string? FilePath { get; private set; }
public bool IsDirty { get; private set; }
public string Title => FilePath is null ? "Untitled" : Path.GetFileName(FilePath);
public void New()
{
Text = string.Empty;
FilePath = null;
IsDirty = false;
}
public void SetText(string text)
{
if (text == Text)
{
return;
}
Text = text;
IsDirty = true;
}
public void Open(string path)
{
Text = _store.Load(path);
FilePath = path;
IsDirty = false;
}
public void Save(string? path = null)
{
var target = path ?? FilePath
?? throw new InvalidOperationException("The document has no path yet.");
_store.Save(target, Text);
FilePath = target;
IsDirty = false;
}
public int Find(string needle, int start)
{
if (needle.Length == 0)
{
return -1;
}
var from = Math.Clamp(start, 0, Text.Length);
return Text.IndexOf(needle, from, StringComparison.OrdinalIgnoreCase);
}
}
internal sealed class RecentFiles
{
private readonly List<string> _paths = new();
public IReadOnlyList<string> Paths => _paths;
public int Capacity { get; } = 5;
public void Add(string path)
{
_paths.RemoveAll(existing => string.Equals(existing, path, StringComparison.OrdinalIgnoreCase));
_paths.Insert(0, path);
if (_paths.Count > Capacity)
{
_paths.RemoveAt(_paths.Count - 1);
}
}
}
dotnet run
the notes presenter against a fake view
-- a new document
title: Untitled
status: New document.
-- typing marks the title
title: Untitled *
-- New with the discard refused
title: Untitled *
text: 'Hello'
-- New with the discard accepted
title: Untitled
text: ''
-- Open todo.txt
title: todo.txt
status: Opened /notes/todo.txt.
text: Buy milk | Call Ada
-- Find ada
status: Found 'ada' at 14.
selection: 14, 3
-- Find zzz
status: 'zzz' was not found.
-- Type and Save to the same path
title: todo.txt *
status: Saved /notes/todo.txt.
title: todo.txt
store: Buy milk | Call Ada!
The output is the real run, and it is the behaviour the form will show. The refused discard left the dirty title and the typed text in place; the accepted one emptied both; Open replaced the text and cleared the asterisk; Find selected three characters at index 14; the missing word produced a status instead of a selection; and Save with an existing path asked for nothing, wrote the store and cleared the title.
Exercises
- Add a SaveAsRequested command that always asks for a path, and extend the driver with one step.
- Make ConfirmDiscard return null for cancel and add a third outcome to the guard.
- Add a CloseRequested command and a CanClose method, and explain what the form's FormClosing handler would do.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What do the Ask methods return when the user cancels?
Answer
Null
The presenter tests for null and returns without a change.
-
Where does the unsaved-changes question live?
Answer
In LeaveCurrent, used by New and Open
One guard keeps the two commands consistent.
-
What happened when the discard was refused?
Answer
The title kept its asterisk and the text stayed Hello
The run prints Untitled * and Hello.
-
Why is TextChanged public on the presenter?
Answer
The form calls it from its text box and it must not write the text back
Writing the text back would move the caret.
-
Where does Save get its path?
Answer
From the document, or from AskSavePath when the document has none
The run saves to the open path without a dialog.
-
What did Find select for ada?
Answer
14, 3
Buy milk and a newline come before Call Ada.
-
What status did the missing word produce?
Answer
'zzz' was not found.
A miss is a status line, not a selection.
-
Which exceptions do the file handlers catch?
Answer
IOException and UnauthorizedAccessException
A bug is allowed to reach the top and be logged.
-
Why is the fake view a better test double than a real form?
Answer
It answers the dialogs and records selections with no window
The presenter cannot tell it from the form.
-
What does Sync copy into the view?
Answer
The document text and the title with its dirty marker
Status is written by each command, Sync is the text and title.
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 logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev