Capstone A: the form
The first capstone ends with the application itself. It is four files, and for the first time in this course a lesson shows a project rather than one listing: the entry point, the document, the presenter, and the form. The files on this page were assembled into a project and built in the container, and the command and its output are below.
Four files
Notes/
app.csproj
nuget.config
Program.cs the entry point and the composition
NoteDocument.cs the document, the store and recent files
NotesPresenter.cs the IView interface and the presenter
NotesForm.cs the form, the menus, the dialogs
The project file and the nuget.config are the ones of lesson 002 and lesson 007; the four .cs files are the blocks below. Each block is a whole file, and the captions are the file names, so the page can be assembled into a folder without a guess.
Program.cs
The composition root of lesson 057, for this application: it creates the store, the document and the recent list, and gives them to the form. Nothing else constructs them, and the form never reads a static.
The file is Program.cs:
using System;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
var store = new FileNotesStore();
var document = new NoteDocument(store);
var recent = new RecentFiles();
Application.Run(new NotesForm(document, recent));
}
}
NoteDocument.cs
The document of lesson 071, with the file store added. FileNotesStore is the two methods the interface needs, and the only file in the project that names File.
The file is NoteDocument.cs:
using System;
using System.Collections.Generic;
using System.IO;
internal interface INotesStore
{
string Load(string path);
void Save(string path, string text);
}
internal sealed class FileNotesStore : INotesStore
{
public string Load(string path) => File.ReadAllText(path);
public void Save(string path, string text) => File.WriteAllText(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);
}
public int ReplaceAll(string needle, string replacement)
{
if (needle.Length == 0)
{
return 0;
}
var count = 0;
var index = 0;
var result = new System.Text.StringBuilder();
while (true)
{
var hit = Text.IndexOf(needle, index, StringComparison.OrdinalIgnoreCase);
if (hit < 0)
{
result.Append(Text, index, Text.Length - index);
break;
}
result.Append(Text, index, hit - index);
result.Append(replacement);
index = hit + needle.Length;
count++;
}
if (count > 0)
{
Text = result.ToString();
IsDirty = true;
}
return count;
}
}
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);
}
}
}
NotesPresenter.cs
The presenter of lesson 072, unchanged. It subscribes to the four events of the view, and every dialog it needs is a method of the interface.
The file is NotesPresenter.cs:
using System;
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 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;
}
NotesForm.cs
The form that implements the interface. A menu with File and Edit, a tool strip with the find box, a multiline text box and a status strip. The explicit interface implementations keep the form's own Text property, which is the window title, separate from the document text.
The file is NotesForm.cs:
using System;
using System.Drawing;
using System.Windows.Forms;
internal sealed class NotesForm : Form, INotesView
{
private readonly TextBox _box = new()
{
Dock = DockStyle.Fill,
Multiline = true,
ScrollBars = ScrollBars.Both,
WordWrap = false,
AcceptsTab = true,
};
private readonly ToolStripTextBox _find = new() { Width = 160 };
private readonly ToolStripStatusLabel _status = new("Ready.");
private readonly NotesPresenter _presenter;
public NotesForm(NoteDocument document, RecentFiles recent)
{
Text = "Notes";
ClientSize = new Size(600, 420);
var menu = new MenuStrip();
var file = new ToolStripMenuItem("&File");
file.DropDownItems.Add("&New", null, (sender, e) => NewRequested?.Invoke(this, EventArgs.Empty));
file.DropDownItems.Add("&Open...", null, (sender, e) => OpenRequested?.Invoke(this, EventArgs.Empty));
file.DropDownItems.Add("&Save", null, (sender, e) => SaveRequested?.Invoke(this, EventArgs.Empty));
var edit = new ToolStripMenuItem("&Edit");
edit.DropDownItems.Add("&Find", null, (sender, e) => FindRequested?.Invoke(this, EventArgs.Empty));
menu.Items.Add(file);
menu.Items.Add(edit);
MainMenuStrip = menu;
var tools = new ToolStrip();
tools.Items.Add(new ToolStripLabel("Find:"));
tools.Items.Add(_find);
var findButton = new ToolStripButton("Find");
findButton.Click += (sender, e) => FindRequested?.Invoke(this, EventArgs.Empty);
tools.Items.Add(findButton);
var status = new StatusStrip();
status.Items.Add(_status);
_presenter = new NotesPresenter(this, document, recent);
_box.TextChanged += (sender, e) => _presenter.TextChanged();
Controls.Add(_box);
Controls.Add(status);
Controls.Add(tools);
Controls.Add(menu);
}
string INotesView.Text
{
get => _box.Text;
set => _box.Text = value;
}
string INotesView.Title
{
set => Text = value;
}
string INotesView.Status
{
set => _status.Text = value;
}
bool INotesView.ConfirmDiscard() =>
MessageBox.Show(
this,
"Discard the changes to this note?",
"Notes",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes;
string? INotesView.AskOpenPath()
{
using var dialog = new OpenFileDialog
{
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
Title = "Open a note",
};
return dialog.ShowDialog(this) == DialogResult.OK ? dialog.FileName : null;
}
string? INotesView.AskSavePath()
{
using var dialog = new SaveFileDialog
{
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
Title = "Save the note",
DefaultExt = "txt",
AddExtension = true,
};
return dialog.ShowDialog(this) == DialogResult.OK ? dialog.FileName : null;
}
string? INotesView.AskFindText() => _find.Text;
void INotesView.Select(int start, int length)
{
_box.Select(start, length);
_box.ScrollToCaret();
_box.Focus();
}
public event EventHandler? NewRequested;
public event EventHandler? OpenRequested;
public event EventHandler? SaveRequested;
public event EventHandler? FindRequested;
}
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 with the same command the other lessons use. That is the check a multi-file page needs: the compiler sees the files together, not one block at a time.
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The build is real, and it is the whole application: four files, no stub and no missing method. The checker of the course builds one block at a time and reports Program.cs as skipped, because the form and the presenter are in other files; this assembled build is what proves the four fit together, and it is the reason the capstone page is written as files.
The form is built and not run: it draws a window, and WinForms needs Windows. What the run of lesson 072 proved is the part a window would drive: the same presenter, the same document and the same commands, against a fake view. The form adds the three dialogs, the text box and the menus, and each of them is a call the presenter already knows how to ask for.
Exercises
- Add a Recent menu that lists recent.Paths, and say where the list should be loaded at startup.
- Override OnFormClosing and cancel the close when the document is dirty and the user refuses to discard.
- Add a Word wrap menu item that switches WordWrap and explain why it needs no presenter.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How many files does the application have?
Answer
Four C# files, plus the project file and the feed config
Program, document, presenter and form.
-
What does Program.cs construct?
Answer
The store, the document, the recent list and the form
It is the composition root of the application.
-
Which file names File?
Answer
NoteDocument.cs, in the store implementation
The document and the presenter stay free of the file system.
-
Why are the interface members of the form explicit?
Answer
To keep the form's own Text property, the window title, separate
An implicit Text would collide with Form.Text.
-
Which control holds the document text?
Answer
A multiline TextBox docked to fill
The text box is the editing surface.
-
Which control shows the find box?
Answer
A ToolStripTextBox on the tool strip
AskFindText returns its text.
-
What did the assembled build report?
Answer
Build succeeded, 0 warnings and 0 errors
The four files compile together.
-
Why is the Program.cs block skipped by the course checker?
Answer
It references the form and the presenter, which are other files
The checker builds one block at a time; the page assembles them.
-
What does the form add to the run of lesson 072?
Answer
The dialogs, the text box and the menus
The decisions were already in the presenter.
-
Where should the recent list be loaded at startup?
Answer
In Main, next to the other constructed objects
The composition root is where state outside the process enters.
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. The four files of the application were assembled from this page and built together, as the build section says.
Article author: Arthur Isaev