0% нашли этот документ полезным (0 голосов)
26 просмотров85 страниц

Microsoft Blazor: Building Web Applications in .NET - Second Edition Peter Himschoot Instant Download

Документ представляет собой описание книги 'Microsoft Blazor: Building Web Applications in .NET' второго издания Питера Химшота, включая информацию о содержании, авторе и издателе. Книга охватывает создание веб-приложений с использованием технологии Blazor и включает главы о проектировании, связывании данных, компонентах и внедрении зависимостей. Также предоставлены ссылки на другие книги и ресурсы по теме.

Загружено:

olgindiogohg
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
0% нашли этот документ полезным (0 голосов)
26 просмотров85 страниц

Microsoft Blazor: Building Web Applications in .NET - Second Edition Peter Himschoot Instant Download

Документ представляет собой описание книги 'Microsoft Blazor: Building Web Applications in .NET' второго издания Питера Химшота, включая информацию о содержании, авторе и издателе. Книга охватывает создание веб-приложений с использованием технологии Blazor и включает главы о проектировании, связывании данных, компонентах и внедрении зависимостей. Также предоставлены ссылки на другие книги и ресурсы по теме.

Загружено:

olgindiogohg
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 85

Microsoft Blazor: Building Web Applications in

.NET - Second Edition Peter Himschoot install


download

https://ebookmeta.com/product/microsoft-blazor-building-web-
applications-in-net-second-edition-peter-himschoot/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Microsoft Blazor: Building Web Applications in .NET 6


and Beyond - Third Edition Peter Himschoot

https://ebookmeta.com/product/microsoft-blazor-building-web-
applications-in-net-6-and-beyond-third-edition-peter-himschoot/

Microsoft Blazor Building Web Applications in NET 6 and


Beyond 3rd Edition Peter Himschoot

https://ebookmeta.com/product/microsoft-blazor-building-web-
applications-in-net-6-and-beyond-3rd-edition-peter-himschoot/

Microsoft Blazor, 2nd Edition Peter Himschoot

https://ebookmeta.com/product/microsoft-blazor-2nd-edition-peter-
himschoot/

Bluetooth 5 0 Modem Design for IoT Devices Khaled Salah


Mohamed

https://ebookmeta.com/product/bluetooth-5-0-modem-design-for-iot-
devices-khaled-salah-mohamed/
Borrowed from Your Grandchildren : The Evolution of
100-Year Family Enterprises 1st Edition Dennis T. Jaffe

https://ebookmeta.com/product/borrowed-from-your-grandchildren-
the-evolution-of-100-year-family-enterprises-1st-edition-dennis-
t-jaffe/

Programming Fundamentals Using JAVA A Game Application


Approach 2nd Edition William Mcallister

https://ebookmeta.com/product/programming-fundamentals-using-
java-a-game-application-approach-2nd-edition-william-mcallister/

Business in Ethical Focus An Anthology 2nd Edition


Fritz Allho

https://ebookmeta.com/product/business-in-ethical-focus-an-
anthology-2nd-edition-fritz-allho/

Anatomy & Physiology: The Unity of Form and Function


Kenneth S. Saladin

https://ebookmeta.com/product/anatomy-physiology-the-unity-of-
form-and-function-kenneth-s-saladin/

Edexcel AS and A level Mathematics Pure Mathematics


Year 1 AS Textbook e book A level Maths and Further
Maths 2017 1st Edition Greg Attwood

https://ebookmeta.com/product/edexcel-as-and-a-level-mathematics-
pure-mathematics-year-1-as-textbook-e-book-a-level-maths-and-
further-maths-2017-1st-edition-greg-attwood/
RedPillDad Blog Writings 1st Edition Redpilldad

https://ebookmeta.com/product/redpilldad-blog-writings-1st-
edition-redpilldad/
Microsof t
Blazor
Building Web Applications in .NET

Second Edition

Peter Himschoot
Microsoft Blazor
Building Web Applications in .NET
Second Edition

Peter Himschoot
Microsoft Blazor: Building Web Applications in .NET

Peter Himschoot
Melle, Belgium

ISBN-13 (pbk): 978-1-4842-5927-6    ISBN-13 (electronic): 978-1-4842-5928-3


https://doi.org/10.1007/978-1-4842-5928-3

Copyright © 2020 by Peter Himschoot


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Jonathan Gennick
Development Editor: Laura Berendson
Coordinating Editor: Jill Balzano
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail [email protected], or visit http://www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484259276. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� xi

About the Technical Reviewer������������������������������������������������������������������������������� xiii


Acknowledgments���������������������������������������������������������������������������������������������������xv

Introduction�����������������������������������������������������������������������������������������������������������xvii

Chapter 1: Your First Blazor Project������������������������������������������������������������������������� 1


Installing Blazor Prerequisites������������������������������������������������������������������������������������������������������ 1
.NET Core��������������������������������������������������������������������������������������������������������������������������������� 1
Visual Studio 2019������������������������������������������������������������������������������������������������������������������� 2
Visual Studio Code������������������������������������������������������������������������������������������������������������������� 4
Installing the Blazor Templates for VS/Code���������������������������������������������������������������������������� 5
Generating Your Project with Visual Studio����������������������������������������������������������������������������������� 6
Creating a Project with Visual Studio�������������������������������������������������������������������������������������� 7
Generating the Project with dotnet cli������������������������������������������������������������������������������������� 8
Running the Project����������������������������������������������������������������������������������������������������������������� 9
Examining the Project’s Parts����������������������������������������������������������������������������������������������������� 11
The Solution��������������������������������������������������������������������������������������������������������������������������� 11
The Server����������������������������������������������������������������������������������������������������������������������������� 11
The Shared Project���������������������������������������������������������������������������������������������������������������� 13
The Client Blazor Project������������������������������������������������������������������������������������������������������� 14
Debugging Client-Side Blazor����������������������������������������������������������������������������������������������������� 18
Debugging with Visual Studio������������������������������������������������������������������������������������������������ 18
Debugging in Chrome������������������������������������������������������������������������������������������������������������ 19

iii
Table of Contents

The Client-Side Blazor Bootstrap Process���������������������������������������������������������������������������������� 21


The Server-Side Blazor Bootstrap Process��������������������������������������������������������������������������������� 23
Summary������������������������������������������������������������������������������������������������������������������������������������ 24

Chapter 2: Data Binding������������������������������������������������������������������������������������������ 25


A Quick Look at Razor����������������������������������������������������������������������������������������������������������������� 25
One-Way Data Binding���������������������������������������������������������������������������������������������������������������� 27
One-Way Data Binding Syntax����������������������������������������������������������������������������������������������� 27
Attribute Binding������������������������������������������������������������������������������������������������������������������� 28
Conditional Attributes������������������������������������������������������������������������������������������������������������ 29
Event Handling and Data Binding������������������������������������������������������������������������������������������������ 30
Event Binding Syntax������������������������������������������������������������������������������������������������������������� 30
Event Arguments������������������������������������������������������������������������������������������������������������������� 31
Using C# Lambda Functions�������������������������������������������������������������������������������������������������� 31
Two-Way Data Binding���������������������������������������������������������������������������������������������������������������� 32
Two-Way Data Binding Syntax����������������������������������������������������������������������������������������������� 32
Binding to Other Events: @bind:{event}�������������������������������������������������������������������������������������� 34
Preventing Default Actions���������������������������������������������������������������������������������������������������� 34
Stopping Event Propagation�������������������������������������������������������������������������������������������������� 36
Formatting Dates������������������������������������������������������������������������������������������������������������������� 37
Reporting Changes���������������������������������������������������������������������������������������������������������������������� 38
The Pizza Place Single-Page Application������������������������������������������������������������������������������������ 41
Create the PizzaPlace Project������������������������������������������������������������������������������������������������ 41
Add Shared Classes to Represent the Data��������������������������������������������������������������������������� 42
Build the UI to Show the Menu���������������������������������������������������������������������������������������������� 46
Enter the Customer���������������������������������������������������������������������������������������������������������������� 55
Validate the Customer Information���������������������������������������������������������������������������������������� 57
Summary������������������������������������������������������������������������������������������������������������������������������������ 63

iv
Table of Contents

Chapter 3: Components and Structure for Blazor Applications������������������������������ 65


What Is a Blazor Component?����������������������������������������������������������������������������������������������������� 65
Examining the SurveyPrompt Component����������������������������������������������������������������������������� 66
Building a Simple Alert Component with Razor��������������������������������������������������������������������� 67
Separating View and View Model������������������������������������������������������������������������������������������ 71
Understanding Parent-Child Communication������������������������������������������������������������������������ 72
Referring to a Child Component�������������������������������������������������������������������������������������������� 82
Communicating with Cascading Parameters������������������������������������������������������������������������ 83
Using Templated Components����������������������������������������������������������������������������������������������������� 87
Create the Grid Templated Component���������������������������������������������������������������������������������� 87
Use the Grid Templated Component�������������������������������������������������������������������������������������� 89
Specify the Type Parameter’s Type Explicitly������������������������������������������������������������������������� 91
Razor Templates�������������������������������������������������������������������������������������������������������������������� 91
Building a Component Library����������������������������������������������������������������������������������������������������� 94
Create the Component Library Project���������������������������������������������������������������������������������� 94
Add Components to the Library��������������������������������������������������������������������������������������������� 96
Refer to the Library from Your Project����������������������������������������������������������������������������������� 96
Component Life Cycle Hooks������������������������������������������������������������������������������������������������������ 99
OnInitialized and OnInitializedAsync������������������������������������������������������������������������������������ 100
OnParametersSet and OnParametersSetAsync������������������������������������������������������������������� 100
SetParametersAsync����������������������������������������������������������������������������������������������������������� 101
OnAfterRender and OnAfterRenderAsync���������������������������������������������������������������������������� 102
ShouldRender���������������������������������������������������������������������������������������������������������������������� 103
IDisposable�������������������������������������������������������������������������������������������������������������������������� 103
Refactoring PizzaPlace into Components��������������������������������������������������������������������������������� 104
Create a Component to Display a List of Pizzas������������������������������������������������������������������ 104
Show the ShoppingBasket Component������������������������������������������������������������������������������� 107
Add the CustomerEntry Component������������������������������������������������������������������������������������ 109
Use Cascading Properties���������������������������������������������������������������������������������������������������� 112
The Blazor Compilation Model�������������������������������������������������������������������������������������������������� 116
Summary���������������������������������������������������������������������������������������������������������������������������������� 119

v
Table of Contents

Chapter 4: Services and Dependency Injection���������������������������������������������������� 121


What Is Dependency Inversion?������������������������������������������������������������������������������������������������ 121
Understanding Dependency Inversion��������������������������������������������������������������������������������� 121
Using the Dependency Inversion Principle�������������������������������������������������������������������������� 123
Adding Dependency Injection���������������������������������������������������������������������������������������������� 125
Applying an Inversion-of-Control Container������������������������������������������������������������������������ 126
Configuring Dependency Injection�������������������������������������������������������������������������������������������� 128
Singleton Dependencies������������������������������������������������������������������������������������������������������ 130
Transient Dependencies������������������������������������������������������������������������������������������������������ 131
Scoped Dependencies��������������������������������������������������������������������������������������������������������� 131
Disposing Dependencies����������������������������������������������������������������������������������������������������� 134
Understanding Blazor Dependency Lifetime����������������������������������������������������������������������������� 135
Client-Side Blazor Experiment��������������������������������������������������������������������������������������������� 136
Server-Side Blazor Experiment������������������������������������������������������������������������������������������� 139
The Result of the Experiment���������������������������������������������������������������������������������������������� 141
Building Pizza Services������������������������������������������������������������������������������������������������������������� 142
Adding the MenuService and IMenuService Abstraction����������������������������������������������������� 144
Ordering Pizzas with a Service�������������������������������������������������������������������������������������������� 146
Summary���������������������������������������������������������������������������������������������������������������������������������� 149

Chapter 5: Data Storage and Microservices��������������������������������������������������������� 151


What Is REST?��������������������������������������������������������������������������������������������������������������������������� 151
Understanding HTTP������������������������������������������������������������������������������������������������������������ 151
Universal Resource Identifiers and Methods����������������������������������������������������������������������� 152
HTTP Status Codes�������������������������������������������������������������������������������������������������������������� 153
Invoking Server Functionality Using REST�������������������������������������������������������������������������������� 153
HTTP Headers���������������������������������������������������������������������������������������������������������������������� 153
JavaScript Object Notation�������������������������������������������������������������������������������������������������� 154
Some Examples of REST Calls��������������������������������������������������������������������������������������������� 154
Building a Simple Microservice Using ASP.NET Core���������������������������������������������������������������� 156
Services and Single Responsibility������������������������������������������������������������������������������������� 156
The Pizza Service���������������������������������������������������������������������������������������������������������������� 157

vi
Table of Contents

What Is Entity Framework Core?����������������������������������������������������������������������������������������������� 161


Using the Code First Approach�������������������������������������������������������������������������������������������� 161
Preparing Your Project for Code First Migrations���������������������������������������������������������������� 165
Creating Your Code First Migration�������������������������������������������������������������������������������������� 170
Generating the Database����������������������������������������������������������������������������������������������������� 172
Enhancing the Pizza Microservice�������������������������������������������������������������������������������������������� 174
Testing Your Microservice Using Postman�������������������������������������������������������������������������������� 177
Installing Postman��������������������������������������������������������������������������������������������������������������� 177
Making REST Calls with Postman���������������������������������������������������������������������������������������� 178
Summary���������������������������������������������������������������������������������������������������������������������������������� 183

Chapter 6: Communication with Microservices��������������������������������������������������� 185


Using the HttpClient Class��������������������������������������������������������������������������������������������������������� 185
Examining the Server Project���������������������������������������������������������������������������������������������� 185
Why Use a Shared Project?������������������������������������������������������������������������������������������������� 187
Looking at the Client Project����������������������������������������������������������������������������������������������� 188
Understanding the HttpClient Class������������������������������������������������������������������������������������������ 192
The HttpClientJsonExtensions Methods������������������������������������������������������������������������������ 193
Retrieving Data from the Server����������������������������������������������������������������������������������������������� 196
Storing Changes������������������������������������������������������������������������������������������������������������������������ 201
Updating the Database with Orders������������������������������������������������������������������������������������� 201
Building the Order Microservice������������������������������������������������������������������������������������������ 205
Talking to the Order Microservice��������������������������������������������������������������������������������������� 207
Summary���������������������������������������������������������������������������������������������������������������������������������� 208

Chapter 7: Single-Page Applications and Routing������������������������������������������������ 209


What Is a Single-Page Application?������������������������������������������������������������������������������������������ 209
Using Layout Components�������������������������������������������������������������������������������������������������������� 210
Blazor Layout Components�������������������������������������������������������������������������������������������������� 210
Selecting a @layout Component����������������������������������������������������������������������������������������� 213
_Imports.razor��������������������������������������������������������������������������������������������������������������������� 214
Nested Layouts�������������������������������������������������������������������������������������������������������������������� 215

vii
Table of Contents

Understanding Routing������������������������������������������������������������������������������������������������������������� 216


Installing the Router������������������������������������������������������������������������������������������������������������ 216
The NavMenu Component��������������������������������������������������������������������������������������������������� 217
The NavLink Component������������������������������������������������������������������������������������������������������ 219
Setting the Route Template������������������������������������������������������������������������������������������������������� 220
Using Route Parameters������������������������������������������������������������������������������������������������������ 220
Filter URIs with Route Constraints��������������������������������������������������������������������������������������� 221
Redirecting to Other Pages������������������������������������������������������������������������������������������������������� 222
Navigating Using an Anchor������������������������������������������������������������������������������������������������ 223
Navigating Using the NavLink Component�������������������������������������������������������������������������� 223
Navigating with Code���������������������������������������������������������������������������������������������������������� 223
Understanding the Base Tag������������������������������������������������������������������������������������������������ 224
Sharing State Between Components���������������������������������������������������������������������������������������� 226
Summary���������������������������������������������������������������������������������������������������������������������������������� 235

Chapter 8: JavaScript Interoperability����������������������������������������������������������������� 237


Calling JavaScript from C#�������������������������������������������������������������������������������������������������������� 237
Providing a Glue Function���������������������������������������������������������������������������������������������������� 237
Using IJSRuntime to Call the Glue Function������������������������������������������������������������������������ 238
Storing Data in the Browser with Interop���������������������������������������������������������������������������� 238
Passing a Reference to JavaScript�������������������������������������������������������������������������������������� 242
Calling .NET Methods from JavaScript�������������������������������������������������������������������������������������� 244
Adding a Glue Function Taking a .NET Instance������������������������������������������������������������������ 244
Adding a JSInvokable Method to Invoke����������������������������������������������������������������������������� 245
Using Services for Interop��������������������������������������������������������������������������������������������������������� 246
Building the ILocalStorage Service�������������������������������������������������������������������������������������� 246
The Counter with the LocalStorage Service������������������������������������������������������������������������ 248
Building a Blazor Chart Component Library������������������������������������������������������������������������������ 250
Creating the Blazor Component Library������������������������������������������������������������������������������� 250
Adding the Component Library to Your Project�������������������������������������������������������������������� 251

viii
Table of Contents

Adding Chart.js to the Component Library�������������������������������������������������������������������������� 254


Adding Chart.js Data and Options Classes�������������������������������������������������������������������������� 258
Registering the JavaScript Glue Function��������������������������������������������������������������������������� 262
Providing the JavaScript Interoperability Service��������������������������������������������������������������� 263
Implementing the LineChart Component����������������������������������������������������������������������������� 266
Using the LineChart Component������������������������������������������������������������������������������������������ 267
Summary���������������������������������������������������������������������������������������������������������������������������������� 270

Index��������������������������������������������������������������������������������������������������������������������� 271

ix
About the Author
Peter Himschoot works as a lead trainer, architect, and
strategist at U2U Training. Peter has a wide interest in
software development, which includes applications for
the Web, Windows, and mobile devices. Peter has trained
thousands of developers, is a regular speaker at international
conferences, and has been involved in many web and
mobile development projects as a software architect.
Peter has been a Microsoft Regional Director from 2003 to
2019, a group of trusted advisors to the developer and
IT professional audiences, and to Microsoft. He can be
reached on Twitter @peterhimschoot.

xi
About the Technical Reviewer
Gerald Versluis (@jfversluis) is a software engineer at
Microsoft from the Netherlands. With years of experience
working with Xamarin, Azure, ASP.NET, and other .NET
technologies, he has been involved in a number of different
projects and has been building several real-world apps and
solutions.
Not only does he like to code, but he is also passionate
about spreading his knowledge, as well as gaining some in
the bargain. Gerald involves himself in speaking, providing
training sessions and writing blogs (https://blog.verslu.is)
or articles, live coding, and contributing to open source projects in his spare time. He can be
reached on Twitter @jfversluis and his website https://gerald.verslu.is.

xiii
Acknowledgments
When Jonathan Gennick from Apress asked me if I would be interested in writing a book
on Blazor, I felt honored and of course I agreed that Blazor deserves a book. Writing a
book is a group effort, so I thank Jonathan Gennick and Jill Balzano for giving me tips on
styling and writing this book, and I thank Gerald Versluis for doing the technical review
and pointing out sections that needed a bit more explaining. I also thank Magda Thielman
and Lieven Iliano from U2U, my employer, for encouraging me to write this book.
I thoroughly enjoyed writing this book, and I hope you will enjoy reading and
learning from it.

Second Edition
As the first edition of Blazor Revealed was published (using pre-release software), the
Blazor team had made a bunch of changes to the razor syntax, stopping my examples
in Blazor Revealed from working. Now that Blazor has been released and is completely
official (YEAH!!!!), the time has come to publish an updated version of Blazor Revealed.
Should you get stuck with an example, I invite you to consult the accompanying code
samples for comparison purposes.

xv
Introduction
Back in 2018, I was attending the Microsoft Most Valued Professional and Regional
Directors Summit where we were introduced to Blazor for the first time by Steve
Sanderson and Daniel Roth. And I must admit, I was super excited about Blazor! We
learned that Blazor is a framework that allows you to build single-page applications
using C# and allows you to run any standard .NET library in the browser. Before Blazor,
your options for building a SPA were Angular, React, Vue.js, and others using JavaScript
or one of the other higher-level languages like TypeScript (which get compiled into
JavaScript anyway). I was so excited then that I ended up writing the first edition of this
book, and now I have updated it for you.
In this introduction, I will show you how browsers are now capable of running .NET
assemblies in the browser using WebAssembly, Mono, and Blazor.

A Tale of Two Wars


Think about it. The browser is one of the primary applications on your computer. You use it
every day. Companies who build browsers know that very well and are bidding for you to
use their browser. At the beginning of mainstream Internet, everyone was using Netscape,
and Microsoft wanted a share of the market, so in 1995 they built Internet Explorer 1.0,
released as part of Windows 95 Plus! pack. Newer versions were released rapidly, and
browsers started to add new features such as <blink> and <marquee> elements. This was
the beginning of the first browser war, giving people (especially designers) headaches
because some developers were building pages with blinking marquee controls . But
developers were also getting sore heads because of incompatibilities between browsers.
The first browser war was about having more HTML capabilities than the competition.
But all of this is now behind us with the introduction of HTML5 and modern
browsers like Google Chrome, Microsoft Edge, Firefox, Safari, and Opera. HTML5 not
only defines a series of standard HTML elements but also rules on how these should
render, making it a lot easier to build a website that looks the same in all modern
browsers. Then, in 1995 Brendan Eich wrote a little programming language known
as JavaScript (initially called LiveScript) in 10 days (What!?). It was called JavaScript
because its syntax was very similar to Java.
xvii
Introduction

JavaScript and Java are not related. Java and JavaScript have as much in
common as ham and hamster (I don’t know who formulated this first, but I love
this phrasing).

Little did Mr. Eich know how this language would impact the modern web and
even desktop application development. In 1995 Jesse James Garett wrote a white paper
called Ajax (Asynchronous JavaScript and XML), describing a set of technologies where
JavaScript is used to load data from the server and that data is used to update the
browser’s HTML. This avoids full-page reloads and allows for client-side web applications,
which are written in JavaScript that runs completely in the browser. One of the first
companies to apply Ajax was Microsoft when they built Outlook Web Access (OWA). OWA
is a web application almost identical to the Outlook desktop application proving the
power of Ajax. Soon other Ajax applications started to appear, with Google Maps stuck
in my memory as one of the other keystone applications. Google Maps would download
maps asynchronously and with some simple mouse interactions allowed you to zoom and
pan the map. Before Google Maps, the server would do the map rendering and a browser
displayed the map like any other image by downloading a bitmap from a server.
Building an Ajax website was a major undertaking that only big companies like
Microsoft and Google could afford. This soon changed with the introduction of
JavaScript libraries like jQuery and knockout.js (Knockout was also written by Steve
Sanderson, the author of Blazor!). Today we build rich web apps with Angular, React, and
Vue.js. All of them are using JavaScript or higher-level languages like TypeScript which
get transpiled into JavaScript.

Transpiling will take one language and convert it into another language. This is very
popular with TypeScript which gives you a modern high-level language. You need
JavaScript to run it in a browser, so TypeScript gets “transpiled” into JavaScript.

This brings us back to JavaScript and the second browser war. JavaScript
performance is paramount in modern browsers. Chrome, Edge, Firefox, Safari, and
Opera are all competing with one another, trying to convince users that their browser
is the fastest with cool-sounding names for their JavaScript engine like V8 and Chakra.
These engines use the latest optimization tricks like JIT compilation where JavaScript
gets converted into native code as illustrated in Figure 1.

xviii
Introduction

Figure 1. The JavaScript execution process

This process takes a lot of effort because JavaScript needs to be downloaded into
the browser, where it gets parsed, then compiled into bytecode and then Just-In-Time
converted into native code. So how can we make this process even faster?
The second browser war is all about JavaScript performance.

Introducing WebAssembly
WebAssembly allows you to take the parsing and compiling to the server. With WebAssembly,
you compile your code in a format called WASM (an abbreviation of WebASseMbly),
which gets downloaded by the browser where it gets Just-In-Time compiled into native
code as in Figure 2. Open your browser and google “webassembly demo zen garden.” One
of the links should take you to https://s3.amazonaws.com/mozilla-games/ZenGarden/
EpicZenGarden.html where you can see an impressive ray-­trace demo of a Japanese Zen
garden with a screenshot in Figure 3.

xix
Introduction

Figure 2. The WebAssembly execution process

Figure 3. Japanese Zen garden

xx
Introduction

From the official site webassembly.org


WebAssembly (abbreviated Wasm) is a binary instruction format for a
stack-based virtual machine. Wasm is designed as a portable target for
compilation of high-level languages like C/C++/Rust, enabling deployment
on the web for client and server applications.
So WebAssembly as a new binary format optimized for browser execution, it is
NOT JavaScript. There are compilers for languages like C++ and Rust which compile to
WASM. Some people have compiled C++ applications to wasm, allowing to run them in
the browser. There is even a Windows 2000 operating system compiled to wasm!

Which Browsers Support WebAssembly?


WebAssembly is supported by all major browsers: Chrome, Edge, Safari, Opera, and
Firefox, including their mobile versions. As WebAssembly will become more and
more important, we will see other modern browsers follow suit, but don’t expect
Internet Explorer to support WASM. You can check for this on https://caniuse.
com/#search=wasm.

W
 ebAssembly and Mono
Mono is an open source implementation of the .NET CLI specification, meaning that
Mono is a platform for running .NET assemblies. Mono is used in Xamarin for building
mobile applications that run on Windows, Android, and iOS mobile operating systems.
You can also use it to build applications for macOS, Linux, Tizen, and others. Mono
also allows you to run .NET on Linux (its original purpose) and is written in C++. This
last part is important because we saw that you can compile C++ to WebAssembly. So,
what happened is that the Mono team decided to try to compile Mono to WebAssembly,
which they did successfully. There are two approaches. One is where you take your
.NET code and you compile it together with the Mono runtime into one big WASM
application. However, this approach takes a lot of time because you need to take several
steps to compile everything into WASM, not so practical for day-to-day development.
The other approach takes the Mono runtime and compiles it into WASM, and this runs
in the browser where it will execute .NET Intermediate Language just like normal .NET
does. The big advantage is that you can simply run .NET assemblies without having to
compile them first into WASM. This is the approach currently taken by Blazor. But Blazor

xxi
Introduction

is not the only one taking this approach. For example, there is the Ooui project which
allows you to run Xamarin.Forms applications in the browser. The disadvantage of this
is that it needs to download a lot of .NET assemblies. This can be solved by using Tree
Shaking algorithms which remove all unused code from assemblies.

Interacting with the Browser with Blazor


WebAssembly with Mono allows you to run .NET code in the browser. Steve Sanderson
used this to build Blazor. Blazor uses the popular ASP.NET MVC approach for building
applications that run in the browser. With Blazor, you build Razor files (Blazor = Browser
+ Razor) which execute inside to browser to dynamically build a web page. With Blazor,
you don’t need JavaScript to build a web app which is good news for thousands of .NET
developers who want to continue using C# (or F#).

How Does It Work?


Let’s start with a simple razor file in Listing 1 which you can find when you create a new
Blazor project (which we will do in the first chapter).

Listing 1. The Counter razor file

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
  private int currentCount = 0;

  private void IncrementCount()


  {
    currentCount++;
  }
}

xxii
Introduction

This file gets compiled into .NET code (you’ll find out how later in this book)
which is then executed by the Blazor engine. The result of this execution is a tree-
like structure called the render tree. The render tree is then sent to JavaScript which
updates the DOM to reflect the render tree (creating, updating, and removing HTML
elements and attributes). Listing 1 will result in h1, p (with the value of currentCount),
and button HTML elements. When you interact with the page, for example, when
you click the button, this will trigger the button’s click event which will invoke the
IncrementCount method from Listing 1. The render tree is then regenerated, and
any changes are sent again to JavaScript which will update the DOM. This process is
illustrated in Figure 4.

Figure 4. The Blazor WebAssembly DOM generation process

This model is very flexible. It allows you to build Progressive Web Apps and also
can be embedded in Electron desktop applications, of which Visual Studio Code is a
prime example.
In Chapter 1, section “The Client-Side Blazor Bootstrap Process,” we will look at
which files get downloaded. One of the drawbacks of Blazor WebAssembly is that this is
a substantial download on first use (after this, most files can be cached by the browser
or the Blazor runtime itself ), especially the Mono runtime itself. If you want to avoid this
big download, you can use Server-Side Blazor.

xxiii
Introduction

Server-Side Blazor
At the August 7, 2018, ASP.NET Community Standup, Daniel Roth introduced a new
execution model for Blazor called Server-Side Blazor. In this model, your Blazor site is
running on the server resulting in a way smaller download for the browser.

The Server-Side Model


We just saw that Client-Side Blazor (also known as Blazor WebAssembly) builds a render
tree using the Mono runtime which then gets sent to JavaScript to update the DOM. With
Server-Side Blazor, the render tree is built on the server and then gets serialized to the
browser using SignalR. JavaScript in the browser then deserializes the render tree to
update the DOM. Pretty similar to the client-side Blazor model. When you interact with
the site, events get serialized back to the server which then executes the .NET code,
updating the render tree which then gets serialized back to the browser. I’ve illustrated
this process in Figure 5. The big difference is that there is no need to send the Mono
runtime and your Blazor assemblies to the browser. And the programming model stays
the same! You can switch between server-side and client-side Blazor (also known as
Blazor WebAssembly) with just a couple of small changes to your code.

Figure 5. Blazor Server-Side


xxiv
Introduction

Pros and Cons of the Server-Side Model


The Server-Side model has a couple of benefits, but also some drawbacks. Let’s discuss
these here so you can decide which model fits your application’s needs.

Smaller Downloads
With server-side, your application does not need to download blazor.wasm (the Mono
runtime) nor all your .NET assemblies. The browser downloads a small JavaScript library
which sets up the SignalR connection to the server. This means that the application will
start a lot faster, especially on slower connections.

Development Process
Blazor client-side has limited debugging capabilities, resulting in added logging. Because
your .NET code is running on the server, you can use the regular .NET debugger. You
could start building your Blazor application using the server-side model, and when it’s
finished, switch to the client-side model by making a small change to your code.

.NET APIs
Because you are running your .NET code on the server, you can use all the .NET APIs
you would use with regular Asp.Net Core MVC applications, for example, accessing the
database directly. Do note that doing this will stop you from quickly converting it into a
client-side application.

Online Only
Running the Blazor application on the server does mean that your users will always need
access to the server. This will prevent the application from running in Electron, nor will
you be able to run it as a Progressive Web Application (PWA). And if the connection
drops between the browser and server, your user could lose some work because the
application will stop functioning. Blazor will try to reconnect to the server without losing
any data, so most of the time users will not lose any work done.

xxv
Introduction

Server Scalability
All your .NET code runs on the server, so if you have thousands of clients, your server(s)
will have to handle all the work. Not only that, Blazor uses a state-full model which will
require you to keep track of every user’s state on the server. So your server will need
more resources than with client-side Blazor.

Summary
In this introduction, we looked at the history of the browser wars and how this resulted
in the creation of WebAssembly. Mono allows you to run .NET assemblies, and because
Mono can run on WebAssembly, we can now run .NET assemblies in the browser! All of
this resulted in the creation of Blazor, where you build razor files containing .NET code
which updates the browser’s DOM, giving us the ability to build single-page applications
in .NET, instead of JavaScript.

xxvi
CHAPTER 1

Your First Blazor Project


Getting hands-on is the best way to learn. In this chapter, you’ll install the prerequisites
to developing with Blazor. These include Visual Studio along with some needed
extensions. Then you’ll create your first Blazor project in Visual Studio, run the project
to see it work, and finally inspect the different aspects of the project to get a “lay of the
land” view for how Blazor applications are developed.

I learned an important lesson from the first edition of this book: Never
underestimate the speed at which Microsoft innovates! All code samples in the
first edition of Blazor Revealed became invalid quite rapidly. I do not expect this
to happen again with this edition since it is based on the Release To Manufacture
(RTM) version of Blazor. If something does not work, simply consult the sources
that come with this book. I will keep these up to date.
The source code for this book is available on GitHub via the book’s product page,
located at www.apress.com/9781484259276.

Installing Blazor Prerequisites


Working with Blazor requires you to install some prerequisites so in this section, you will
install what is needed to get going.

. NET Core
Blazor runs on top of .NET Core, providing the web server for your project which will
serve the client files that run in the browser and run any server-side APIs that your Blazor
project needs. .NET Core is Microsoft’s cross-platform solution for working with .NET on
Windows, Linux, and OS X.

1
© Peter Himschoot 2020
P. Himschoot, Microsoft Blazor, https://doi.org/10.1007/978-1-4842-5928-3_1
Chapter 1 Your First Blazor Project

You can find the installation files at www.microsoft.com/net/download. Look for


the latest version of the .NET Core SDK (you’ll need at least version 3.1). Download the
installer, then simply run it and accept the defaults.
Verify the installation when the installer is done by opening a new command prompt
and typing the following command:

dotnet --version

Look for the following output to indicate that you installed the correct version. The
version number should be at least 3.1.201.
Should the command’s output show an older version (e.g., 2.1.200), you will need to
download and install a more recent version of .NET Core SDK.

Visual Studio 2019


Visual Studio 2019 (from now on I will refer to Visual Studio as VS) is one of the
integrated development environments (IDE) we will use throughout this book. The other
IDEs will be Visual Studio Code and Visual Studio for Mac. With either one, you can edit
your code, compile it, and run it all from the same application. The code samples are
also the same. However, VS only runs on Windows, so if you’re using another OS, please
continue to the section “Visual Studio Code.” All samples should also work fine with
Visual Studio for Mac.
Download the latest version of Visual Studio 2019 from www.visualstudio.com/
downloads/.
Run the installer and make sure that you install the ASP.NET and web development
role as shown in Figure 1-1.

2
Chapter 1 Your First Blazor Project

Figure 1-1. The Visual Studio Installer Workloads selection

After installation, run Visual Studio from the Start menu. Then open the Help menu
and select About Microsoft Visual Studio. The About Microsoft Visual Studio dialog
window should specify at least version 16.6.0 as illustrated in Figure 1-2. I am currently
using the latest preview version of Visual Studio 2019, but by the time you are reading
this, Visual Studio 16.6.0 should be out for general release.

3
Chapter 1 Your First Blazor Project

Figure 1-2. About Microsoft Visual Studio

Visual Studio Code


Visual Studio Code is a free, modern, cross-platform development environment with an
integrated editor, git source control, and debugger. The environment has a huge range
of extensions available allowing you to use all kinds of languages and tools directly from
Code. So, if you don’t have access to (because you’re running a non-Windows operating
system or you don’t want to use) Visual Studio, use Code.
Download the installer from www.visualstudio.com. Run it and simply choose the
defaults.
After installation, I do advise you to install a couple of extensions for Code, especially
the C# extension. Start Code, and at the left side, select the Extensions tab as shown in
Figure 1-3.

4
Chapter 1 Your First Blazor Project

Figure 1-3. Visual Studio Code Extensions tab

You can search for extensions, so start with C# which is the first extension from
Figure 1-4. This extension will give you IntelliSense for the C# programming language
and .NET assemblies. You will probably get a newer version listed so take the latest.
Click install.

Figure 1-4. C# for Visual Studio Code

Installing the Blazor Templates for VS/Code


Throughout this book, we will create several different Blazor projects. Not all of them
can be created from Visual Studio or Code, meaning you’ll need to install the templates
for Blazor projects. This section’s example shows how to install those templates from the
.NET Core command-line interface, also known as the .NET Core CLI. You should have
this command-line interface as part of your .NET Core installation.
Open a command line on your OS, and type the following to install the templates
from NuGet:

dotnet new -i Microsoft.AspNetCore.Components.WebAssembly.Templates

These templates will allow you to quickly generate projects and items. Verify the
installation by typing the following command:

dotnet new –-help

5
Chapter 1 Your First Blazor Project

This command will list all the templates that have been installed by the command-­
line interface. You will see four columns. The first shows the template’s description, the
second column displays the name, the third lists the languages for which the template
is available, and the last shows the tags, a kind of group name for the template. Among
those listed are the following:

Razor Component                           razorcomponent
Blazor Server App                         blazorserver
Blazor WebAssembly App                    blazorwasm
Razor Class Library                       razorclasslib

Generating Your Project with Visual Studio


With Blazor projects, you have a couple of choices. You can create a stand-alone Blazor
project (using the blazorwasm template) that does not need server-side code. This kind
of project known as Blazor WebAssembly has the advantage that you can simply deploy
it to any web server which will function as a file server, allowing browsers to download
your site just like any other site.
Or you can create a hosted project (adding the --hosted option) with client, server,
and shared code. This kind of Blazor WebAssembly project will require you to host it
where there is .NET Core 3.1 support because you will execute code on the server as well.
The third option is to run all Blazor code on the server (using the blazorserver
template). This is known as Blazor Server-Side (previously known as Blazor
components). In this case, the browser will use a SignalR connection to receive UI
updates from the server and to send user interaction back to the server for processing.
In this book, we will use the second option (Blazor WebAssembly hosted on ASP.
NET MVC Core), but the concepts you will learn in this book are the same for all three
options. You can even develop for Blazor WebAssembly and Blazor Server-Side at the
same time. Why? Because debugging support for Blazor WebAssembly is limited, so
you develop with Blazor Server-Side using all debugger features you know and love. But
you can test everything with Blazor WebAssembly ensuring you can run everything in
the browser later. This is the way I like to work. However, to pull this off, you need some
experience with Blazor first, so keep reading…

6
Chapter 1 Your First Blazor Project

Creating a Project with Visual Studio


For your first project, start Visual Studio and select Create a new project.
Type Blazor in the search box, and select the Blazor App project template as
illustrated in Figure 1-5.

Figure 1-5. Visual Studio New Project dialog

Click Next.
Name your project MyFirstBlazor, leave the rest to the preset defaults, and click
Create.
On the next screen, you can select what kind of Blazor project you want to generate.
Select Blazor WebAssembly App as in Figure 1-6, check the ASP.NET Core hosted
checkbox, and click Create.

7
Chapter 1 Your First Blazor Project

Figure 1-6. New ASP.NET Core web application

Wait for Visual Studio to complete. Then build your solution.

Generating the Project with dotnet cli


To generate the project with dotnet cli, start by opening a command line, and change the
current directory to wherever you want to create the project. Now execute this command
to create a new project from the blazorwasm template in the MyFirstBlazor directory:

dotnet new blazorwasm --hosted -o MyFirstBlazor

This command will take a little while because it will download a bunch of NuGet
packages from the Internet. When the command is ready, you can build your project using

cd MyFirstBlazor
dotnet build

Now open your project’s folder with Code. When Code has loaded everything (be
patient), it will pop a little question as in Figure 1-7.

8
Chapter 1 Your First Blazor Project

Figure 1-7. Code asking to add build and debug assets

Answer Yes. This will add a folder called .vscode with configuration files adding
support for building and running the project from Code. If you already have a .vscode
folder (because you copied an existing project, for example), you will not get this
question.
Thanks to this integration with Visual Studio Code, you can simply press F5 to build
and run your project…

R
 unning the Project
Press Ctrl-F5 to run (this should work for both Visual Studio and Code). Your (default)
browser should open and display the home page as shown in Figure 1-8.

Figure 1-8. Your first application – Home screen

This generated single-page application (SPA) has on the left side a navigation
menu allowing you to jump between different pages. On the right side, you will see the
selected screen, and in Figure 1-8, it is showing the Home screen. And in the top right
corner, there is an About link to https://blazor.net/ which is the “official” Blazor
documentation website.

9
Chapter 1 Your First Blazor Project

The Home Page


The home page shows the mandatory “Hello, world!” demo, and it also contains a survey
component you can click to fill out a survey (this is a real survey, so please let Microsoft
know you like Blazor!). The SurveyPrompt is the first example of a custom Blazor
component. We will discuss building components like SurveyPrompt in Chapter 3.

The Counter Page


In the navigation menu, click the Counter tab. Doing so opens a simple screen with a
number and a button as illustrated in Figure 1-9. Clicking the button will increment the
counter. Try it!

Figure 1-9. Your first application – Counter screen

The Fetch Data Page


In the navigation menu, click the Fetch data tab. Here you can watch a (random and
fake) weather forecast as shown in Figure 1-10. This forecast is generated on the server
when asked by the client. This is very important because the client (which is running in
the browser) cannot access data from a database directly, so you need a server that can
access databases and other data storage.

10
Chapter 1 Your First Blazor Project

Figure 1-10. Your first application – Fetch data screen

Examining the Project’s Parts


Now being able to play with these pages is all nice, but let us have a look at how all this
works. We will start with the server project which hosts our Blazor website. Then we will
look at the shared project which contains classes used by both server and client. Finally,
we will examine the client project which is the actual Blazor implementation.

The Solution
Visual Studio, Visual Studio Code, and Visual Studio for Mac use solution files to group
projects that will form an application. So, a typical Blazor project consists of a server,
a client, and a shared project grouped into a single solution. This simplifies building
everything since the solution allows tools to figure out in which order to compile
everything. Hey, you could even switch between Visual Studio, VS for Mac, and Code
because they both use the same project and solution files!

The Server
Web applications are a bunch of files that get downloaded by the browser from a server.
It is the server’s job to provide the files to the browser upon request. There is a whole
range of existing servers to choose from, for example, IIS on Windows or Apache on

11
Chapter 1 Your First Blazor Project

Linux. ASP.NET Core has a built-in server that you generated with the --hosted option,
which you can then run on Windows, Linux, or OS X.
The topic of this book is Blazor, so we’re not going to discuss all the details of
the server project that got generated (Microsoft has very good documentation on
.NET Core), but I do want to show you an important thing. In the server project
(MyFirstBlazor.Server), look for Startup.cs. Open this file and scroll down to the
Configure method shown in Listing 1-1.

Listing 1-1. The server project’s Startup.Configure method

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseWebAssemblyDebugging();
  }
  else
  {
    app.UseExceptionHandler("/Error");
    app.UseHsts();
  }

  app.UseHttpsRedirection();
  app.UseBlazorFrameworkFiles();
  app.UseStaticFiles();

  app.UseRouting();

  app.UseEndpoints(endpoints =>
  {
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("index.html");
  });
}

12
Chapter 1 Your First Blazor Project

The Configure method is responsible for installing middleware. Middleware objects


are little .NET components that each have a clear responsibility. When you type in a URI, the
browser sends a request to the server, which then passes it on to the middleware components.
Some of these will take the request and return a response; some of them take the response and
do something with it. Look at the first lines in the Configure method in Listing 1-2.

Listing 1-2. The UseDeveloperExceptionPage middleware

if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseWebAssemblyDebugging();
  }

Would you like to see a detailed error page when the server has an uncaught
exception? The UseDeveloperExceptionPage takes care of that. Of course, you don’t need
that in production (you should handle all exceptions correctly <grin>) so this middleware
is only used when running in a development environment. How does the server know
if you are running in development or release? The if statement you see here checks an
environment variable called ASPNETCORE_ENVIRONMENT, and if the environment variable is
set to Development, it knows you are running in development mode.
The Fetch data screen downloads weather information from the server. These kinds
of requests will be handled by the MVC middleware. We will discuss this in more detail
in Chapter 5.
The Blazor bootstrap process requires a bunch of special files, especially dotnet.
wasm (dotnet.wasm is the .NET runtime compiled as WebAssembly). These are served by
the Blazor middleware, which is handled by the UseBlazorFrameworkFiles middleware.
Later in this chapter, you will see why.

The Shared Project


When you click the Fetch data tab, your Blazor project fetches some data from the server.
The shape of this data needs to be described in detail (computers are picky things), and
in classic projects, you would describe this model’s shape twice, once for the client and
again for the server because these would use different languages. Not with Blazor! In
Blazor, both client and server use C#, so we can describe the model once and share it
between client and server as shown in Listing 1-3.

13
Chapter 1 Your First Blazor Project

Listing 1-3. The shared WeatherForecast class

using System;

namespace MyFirstBlazor.Shared
{
public class WeatherForecast
{
  public DateTime Date { get; set; }

  public int TemperatureC { get; set; }

  public string Summary { get; set; }

  public int TemperatureF


   => 32 + (int)(TemperatureC / 0.5556);
}
}

The Client Blazor Project


Open the client project’s wwwroot folder and look for index.html. The contents of that file
should appear as shown in Listing 1-4. To be honest, this looks mostly like a normal HTML
page. But on closer inspection, you’ll see that there is a weird <app> HTML tag there.

<app>Loading...</app>

The <app> HTML element does not exist! It is an example of a Blazor component.
You will also find an <script> element near the end.

<script src="_framework/blazor.webassembly.js"></script>

This script will install Blazor by downloading dotnet.wasm and your assemblies.

Listing 1-4. index.html

<!DOCTYPE html>
<html>

14
Chapter 1 Your First Blazor Project

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>PizzaPlace</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css"
          rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
</head>

<body>
    <app>Loading...</app>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">Ï</a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
</body>

</html>

R
 outing
What is that <app> element? Open Program.cs from the MyFirstBlazor.Client
project and look for the Main method as in Listing 1-5. Here you can see the App
component is associated with the app tag from index.html. A Blazor component uses
a custom tag like <app>, and the Blazor runtime replaces the tag with the component’s
markup which is normal HTML recognized by the browser. We will discuss Blazor
components in Chapter 3.

Listing 1-5. The Configure method associating the app element to the App
component
public static async Task Main(string[] args)
{
  var builder = WebAssemblyHostBuilder.CreateDefault(args);

15
Chapter 1 Your First Blazor Project

  builder.RootComponents.Add<App>("app");

  builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new


Uri(builder.HostEnvironment.BaseAddress) });
  await builder.Build().RunAsync();
}

The main thing the App component does is to install the router as in Listing 1-6. You
can find this code in the app.razor file in the client project. The router is responsible for
loading a Blazor component depending on the URI in the browser. When the route is not
found, it will display the <NotFound> content, which currently shows a simple not found
message. For example, if you browse to the / URI, the router will look for a component
with a matching @page directive.

Listing 1-6. The App component

<Router AppAssembly="@typeof(Program).Assembly">
  <Found Context="routeData">
    <RouteView RouteData="@routeData"
               DefaultLayout="@typeof(MainLayout)" />
  </Found>
  <NotFound>
    <LayoutView Layout="@typeof(MainLayout)">
      <p>Sorry, there's nothing at this address.</p>
    </LayoutView>
  </NotFound>
</Router>

In our current MyFirstBlazor project, this will match the Index component which
you can find in the Index.razor file from the Pages folder. The Index component
displays a Hello World message and the survey link as in Listing 1-7.

Listing 1-7. The Index component

@page "/"
<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />


16
Chapter 1 Your First Blazor Project

L ayout Components
Look at Figures 1-8 and 1-9. Both have the same menu. This menu is shared among all
our Blazor components and is known as a layout component. We will discuss layout
components in Chapter 7. But how does Blazor know which component is the layout
component? Look again at Listing 1-6. When the route is found, it uses a default layout
called MainLayout. In our project, the layout component can be found in MainLayout.
razor from the Shared folder, which I’ve listed in Listing 1-8.

Listing 1-8. The MainLayout component

@inherits LayoutComponentBase

<div class="sidebar">
  <NavMenu />
</div>

<div class="main">
  <div class="top-row px-4">
    <a href="http://blazor.net" target="_blank"
       class="ml-md-auto">About</a>
  </div>

  <div class="content px-4">


    @Body
  </div>
</div>

The first div with class sidebar contains a single Blazor component: NavMenu. This
is where your navigation menu gets defined. The sidebar will display a menu, allowing
you to navigate between Home, Counter, and Fetch data. We will look in more detail at
navigation and routing in Chapter 7.
The next div with class main has two parts. The first is the About link you see on every
page. The second part contains the Body; this is where the selected page will be shown.
For example, when you click the Counter link in the navigation menu, this is where the
Counter.razor Blazor component will go.

17
Chapter 1 Your First Blazor Project

Debugging Client-Side Blazor


Of course, while building your Blazor app, you will encounter unexpected behavior from
time to time. Debugging the server-side can be done just like any .NET project using
Visual Studio or Code. But with Client-Side Blazor, your code will be running in the
browser. You will be happy to learn that the Visual Studio/Code debugger works with
Blazor, although limited. You can put breakpoints in your code, step through your code,
and observe variables holding simple types like bool, int, and string.

Debugging with Visual Studio


To enable debugging with Visual Studio, open the launchSettings.json file from the
Server project. You will need to set the inspectUri property in here, like in Listing 1-9
(the template normally will configure this for you). This property enables the IDE
to detect that this is a Blazor WebAssembly app and instructs the script debugging
infrastructure to connect to the browser through Blazor’s debugging proxy.

Listing 1-9. Enable debugging in Visual Studio

"MyFirstBlazor.Server": {
      "commandName": "Project",
      "launchBrowser": true,
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/
debug/ws-proxy?browser={browserInspectUri}",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001;http://localhost:5000"
    }

Now run your application in Visual Studio with the debugger by pressing F5. Be
patient while your Blazor site starts to run. Now you can put a breakpoint in your code,
for example, on the IncrementCount method of the Counter.razor component as in
Figure 1-11, line 14. Simply click in the gray area left to your code (also known as the
gutter) and a red dot will appear, indicating that the debugger will stop at this code.

18
Chapter 1 Your First Blazor Project

Figure 1-11. Setting a breakpoint in the IncrementCount method

Go back to your Blazor application and click the Counter’s Click me button. The
debugger should stop on the IncrementCount method. You can now examine the
content of simple variables in the Locals window, like in Figure 1-12.

Figure 1-12. Using the Locals debugger window to inspect simple variables

D
 ebugging in Chrome
To debug a Client-Side Blazor application, first make sure you build the debug version,
which is the default. Then run your application, and in Chrome, press Shift-Alt-D in
Windows and Linux or Shift-Cmd-D on macOS.
The first time you do this with your application, you will need to start the Chrome
remote debugger. Instructions for this are automatically generated by chrome as shown
in Figure 1-13. Simply follow the instructions.

19
Chapter 1 Your First Blazor Project

Figure 1-13. How to start Chrome with the debug server enabled

Once the remote debugger has been started, you should see your application
running again. Press the magic key combination again. Open the Sources tab in the
debugger and expand file:// to see your files. Figure 1-14 shows the files from the
initial MyFirstBlazor app.

Figure 1-14. The Chrome debugger with all your components

20
Chapter 1 Your First Blazor Project

Select Counter.razor, and add a breakpoint in the IncrementCount method, as


shown in Figure 1-15, line 14.

Figure 1-15. Add a breakpoint in the Chrome debugger

Switch back to the tab where your application is running and click the Click me
button. The debugger should stop on the breakpoint. Switch back to the Chrome
debugger. Press F10 to step to the next statement. Press F8 to continue running.
Open FetchData.razor and put a breakpoint on the @foreach statement. Switch
back to your Blazor application, and select the Fetch Data tab. Your breakpoint should
be hit, meaning that you can also put breakpoints on razor directives.

The Client-Side Blazor Bootstrap Process


Examine Listing 1-4 again. At the bottom, you will find the <script> element responsible
for bootstrapping Blazor in the browser. Let’s look at this process.
Go back to your browser and open its developer tools (most browsers will open
the developer tools when you press F12). We will have a look at what happens at the
network layer.

21
Chapter 1 Your First Blazor Project

In all screenshots, I will be using the Chrome browser, mainly because it is available
on all platforms (Windows, Linux, and OS X) and because it is very popular with a lot
of web developers. If you prefer to use another browser, go right ahead!

Refresh your browser to see what gets downloaded from the server as in Figure 1-­16.
If Figure 1-16 does not match what you see (please ignore some minor details), you
want to clear the browser’s cache. Browsers use a cache to avoid reloading files from
the server, but when you are developing, you will need to clear the cache to ensure you
are getting the latest changes from the server. First, you will see index.html (shown as
localhost) being downloaded, which in turn downloads bootstrap.min.css and site.
css, and then blazor.webassembly.js. A little lower you will see that dotnet.js gets
downloaded, which in turn will download dotnet.wasm. This is the Mono runtime
compiled to run on WebAssembly!

Figure 1-16. Examining the bootstrap process using the network log

22
Another Random Scribd Document
with Unrelated Content
"Is he so ill?" he asked, under his trembling breath.
"I'm afraid he's going to be very ill. And to see him in so much
trouble—"
"What is the matter? In God's name, has anything happened to
him?"
She turned her face away to hide her grief. "He said he would tell
you himself. Oh, if I've been too hard with him! But I did it for the
best. I didn't know until the doctor came that he was going to be ill,
or I would have waited. Do anything you can to quiet him—anything
he should ask you to do," she implored, and pointed towards the
door of the room in which the boy lay.
Conscience-stricken and speechless, the parson opened it and
entered.
The small white bed stood against the wall beneath an open
window, and one bright-headed sunflower, growing against the
house outside, leaned in and fixed its kind face anxiously upon the
sufferer's.
The figure of the boy was stretched along the edge of the bed, his
cheek on one hand and his eyes turned steadfastly towards the
middle of the room, where, on a table, the violin lay exposed to
view.
He looked quickly towards the door as the parson entered, and an
expression of relief passed over his face.
"Why, David," said the parson, chidingly, and crossing to the bed
with a bright smile. "Sick? This will never do;" and he sat down,
imprisoning one of the burning palms in his own.
The boy said nothing, but looked at him searchingly, as though
needing to lay aside masks and disguises and penetrate at once to
the bottom truth. Then he asked, "Are you mad at me?"
"My poor boy!" said the parson, his lips trembling a little as he
tightened his pressure—"my poor boy! why should I be mad at
you?"
"You never could do anything with me."
"Never mind that now," said the parson, soothingly, but adding, with
bitterness, "it was all my fault—all my fault."
"It wasn't your fault," said the boy. "It was mine."
A change had come over him in his treatment of the parson.
Shyness had disappeared, as is apt to be the case with the sick.
"I want to ask you something," he added, confidentially.
"Anything—anything! Ask me anything!"
"Do you remember the wax figures?"
"Oh yes, I remember them very well," said the parson, quickly,
uneasily.
"I wanted to see 'em, and I didn't have any money, and I stole a
quarter from Mr. Leuba."
Despite himself a cry escaped the parson's lips, and dropping the
boy's hand, he started from his chair and walked rapidly to and fro
across the room, with the fangs of remorse fixed deep in his
conscience.
"Why didn't you come to me?" he asked at length, in a tone of
helpless entreaty. "Why didn't you come to me? Oh, if you had only
come to me!"
"I did come to you," replied the boy.
"When?" asked the parson, coming back to the bedside.
"About three o'clock yesterday."
About three o'clock yesterday! And what was he doing at that time?
He bent his head over to his very knees, hiding his face in his hands.

"But why didn't you let me know it? Why didn't you come in?"
"Mrs. Spurlock told me you were at work on a sermon."
"God forgive me!" murmured the parson, with a groan.
"I thought you'd lend me a quarter," said the boy, simply. "You took
the other boys, and you told me I must be certain to go. I thought
you'd lend me a quarter till I could pay you back."
"Oh, David!" cried the parson, getting down on his knees by the
bedside, and putting his arms around the boy's neck, "I would have
lent you—I would have given you—anything I have in this poor
world!"
The boy threw his arms around the parson's neck and clasped him
close. "Forgive me!"
"Oh, boy! boy! can you forgive me?" Sobs stifled the parson's
utterance, and he went to a window on the opposite side of the
room.
When he turned his face inward again, he saw the boy's gaze fixed
once more intently upon the violin.
"There's something I want you to do for me," he said. "Mr. Leuba
gave me a violin last night, and mamma says I ought to sell it and
pay him back. Mamma says it will be a good lesson for me." The
words seemed wrung from his heart's core. "I thought I'd ask you to
sell it for me. The doctor says I may be sick a long time, and it
worries me." He began to grow excited, and tossed from side to
side.
"Don't worry," said the parson, "I'll sell it for you."
The boy looked at the violin again. To him it was priceless, and his
eyes grew heavy with love for it. Then he said, cautiously: "I
thought you'd get a good price for it. I don't think I could take less
than a hundred dollars. It's worth more than that, but if I have to
sell it, I don't think I could take less than a hundred dollars," and he
fixed his burning eyes on the parson's.
"Don't worry! I'll sell it for you. Oh yes, you can easily get a hundred
dollars for it. I'll bring you a hundred dollars for it by to-morrow
morning."
As the parson was on the point of leaving the room, with the violin
under his arm, he paused with his hand on the latch, an anxious
look gathering in his face. Then he came back, laid the violin on the
table, and going to the bedside, took the boy's hands in both of his
own.
"David," said the moral philosopher, wrestling in his consciousness
with the problem of evil—"David, was it the face of the Saviour that
you wished to see? Was it this that tempted you to—" and he bent
over the boy breathless.
"I wanted to see the Sleeping Beauty."
The parson turned away with a sigh of acute disappointment.
It was on this night that he was seen to enter his room with a boy's
violin under his arm, and later to hang it, and hang his beloved flute,
tied with a blue ribbon, above the meagre top shelf of books—
Fuller's Gospel, Petrarch, Volney's Ruins, Zollicoffer's Sermons, and
the Horrors of San Domingo. After that he remained motionless at
his table, with his head bowed on his folded arms, until the candle
went out, leaving him in inner and outer darkness. Moralist, logician,
philosopher, he studied the transgression, laying it at last solely to
his own charge.
At daybreak he stood outside the house with the physician who had
been with the boy during the night. "Will he die?" he asked.
The physician tapped his forehead with his forefinger. "The chances
are against him. The case has peculiar complications. All night it has
been nothing but the wax figures and the stolen quarter and the
violin. His mother has tried to persuade him not to sell it. But he
won't bear the sight of it now, although he is wild at the thought of
selling it."
"David," said the parson, kneeling by the bedside, and speaking in a
tone pitiful enough to have recalled a soul from the other world
—"David, here's the money for the violin; here's the hundred
dollars," and he pressed it into one of the boy's palms. The hand
closed upon it, but there was no recognition. It was half a year's
salary.
The first sermon that the parson preached in the new church was on
the Sunday after the boy's death. It was expected that he would rise
to the occasion and surpass himself, which, indeed, he did, drawing
tears even from the eyes of those who knew not that they could
shed them, and all through making the greatest effort to keep back
his own. The subject of the sermon was "The Temptations of the
Poor." The sermon of the following fortnight was on the "Besetting
Sin," the drift of it going to show that the besetting sin may be the
one pure and exquisite pleasure of life, involving only the exercise of
the loftiest faculty. And this was followed by a third sermon on "The
Kiss that Betrayeth," in which the parson ransacked history for
illustrations to show that every species of man—ancient, mediæval,
and modern—had been betrayed in this way. During the delivery of
this sermon the parson looked so cold and even severe that it was
not understood why the emotions of any one should have been
touched, or why the widow Babcock should have lowered her veil
and wept bitterly.
And thus being ever the more loved and revered as he grew ever the
more lovable and saint-like, he passed onward to the close. But not
until the end came did he once stretch forth a hand to touch his
flute; and it was only in imagination then that he grasped it, to
sound the final roll-call of his wandering faculties, and to blow a last
good-night to his tired spirit.
I.
It had been a year of strange disturbances—a desolating drought, a
hurly-burly of destructive tempests, killing frosts in the tender
valleys, mortal fevers in the tender homes. Now came tidings that all
day the wail of myriads of locusts was heard in the green woods of
Virginia and Tennessee; now that Lake Erie was blocked with ice on
the very verge of summer, so that in the Niagara new rocks and
islands showed their startling faces. In the Blue-grass Region of
Kentucky countless caterpillars were crawling over the ripening apple
orchards and leaving the trees as stark as when tossed in the thin
air of bitter February days.
Then, flying low and heavily through drought and tempest and frost
and plague, like the royal presence of disaster, that had been but
heralded by its mournful train, came nearer and nearer the dark
angel of the pestilence.
M. Xaupi had given a great ball only the night before in the dancing-
rooms over the confectionery of M. Giron—that M. Giron who made
the tall pyramids of meringues and macaroons for wedding-suppers,
and spun around them a cloud of candied webbing as white and
misty as the veil of the bride. It was the opening cotillon party of the
summer. The men came in blue cloth coats with brass buttons, buff
waistcoats, and laced and ruffled shirts; the ladies came in white
satins with ethereal silk overdresses, embroidered in the figure of a
gold beetle or an oak leaf of green. The walls of the ball-room were
painted to represent landscapes of blooming orange-trees, set here
and there in clustering tubs; and the chandeliers and sconces were
lighted with innumerable wax-candles, yellow and green and rose.
Only the day before, also, Clatterbuck had opened for the summer a
new villa-house, six miles out in the country, with a dancing-pavilion
in a grove of maples and oaks, a pleasure-boat on a sheet of crystal
water, and a cellar stocked with old sherry, Sauterne, and Château
Margaux wines, with anisette, "Perfect Love," and Guigholet cordials.
Down on Water Street, near where now stands a railway station,
Hugh Lonney, urging that the fear of cholera was not the only
incentive to cleanliness, had just fitted up a sumptuous bath-house,
where cold and shower baths might be had at twelve and a half
cents each, or hot ones at three for half a dollar.
Yes, the summer of 1833 was at hand, and there must be new
pleasures, new luxuries; for Lexington was the Athens of the West
and the Kentucky Birmingham.
Old Peter Leuba felt the truth of this, as he stepped smiling out of
his little music-store on Main Street, and, rubbing his hands briskly
together, surveyed once more his newly-arranged windows, in which
were displayed gold and silver epaulets, bottles of Jamaica rum,
garden seeds from Philadelphia, drums and guitars and harps.
Dewees & Grant felt it in their drug-store on Cheapside, as they sent
off a large order for calomel and superior Maccoboy, rappee, and
Lancaster snuff. Bluff little Daukins Tegway felt it, as he hurried on
the morning of that day to the office of the Observer and Reporter,
and advertised that he would willingly exchange his beautiful
assortment of painted muslins and Dunstable bonnets for flax and
feathers. On the threshold he met a florid farmer, who had just
offered ten dollars' reward for a likely runaway boy with a long fresh
scar across his face; and to-morrow the paper would contain one
more of those tragical little cuts, representing an African slave
scampering away at the top of his speed, with a stick swung across
his shoulder and a bundle dangling down his back. In front of
Postlethwaite's Tavern, where now stands the Phœnix Hotel, a
company of idlers, leaning back in Windsor chairs and planting their
feet against the opposite wall on a level with their heads, smoked
and chewed and yawned, as they discussed the administration of
Jackson and arranged for the coming of Daniel Webster in June,
when they would give him a great barbecue, and roast in his honor
a buffalo bull taken from the herd emparked near Ashland. They
hailed a passing merchant, who, however, would hear nothing of the
bull, but fell to praising his Rocky Mountain beaver and Goose Creek
salt; and another, who turned a deaf ear to Daniel Webster, and
invited them to drop in and examine his choice essences of
peppermint, bergamot, and lavender.
But of all the scenes that might have been observed in Lexington on
that day, the most remarkable occurred in front of the old court-
house at the hour of high noon. On the mellow stroke of the clock in
the steeple above the sheriff stepped briskly forth, closely followed
by a man of powerful frame, whom he commanded to station
himself on the pavement several feet off. A crowd of men and boys
had already collected in anticipation, and others came quickly up as
the clear voice of the sheriff was heard across the open public
square and old market-place.
He stood on the topmost of the court-house steps, and for a
moment looked down on the crowd with the usual air of official
severity.
"Gentlemen," he then cried out sharply, "by an ordah of the cou't I
now offah this man at public sale to the highes' biddah. He is able-
bodied but lazy, without visible property or means of suppoht, an' of
dissolute habits. He is therefoh adjudged guilty of high
misdemeanahs, an' is to be sole into labah foh a twelvemonth. How
much, then, am I offahed foh the vagrant? How much am I offahed
foh ole King Sol'mon?"
Nothing was offered for old King Solomon. The spectators formed
themselves into a ring around the big vagrant and settled down to
enjoy the performance.
"Staht 'im, somebody."
Somebody started a laugh, which rippled around the circle.
The sheriff looked on with an expression of unrelaxed severity, but
catching the eye of an acquaintance on the outskirts, he exchanged
a lightning wink of secret appreciation. Then he lifted off his tight
beaver hat, wiped out of his eyes a little shower of perspiration
which rolled suddenly down from above, and warmed a degree to
his theme.
"Come, gentlemen," he said, more suasively, "it's too hot to stan'
heah all day. Make me an offah! You all know ole King Sol'mon; don't
wait to be interduced. How much, then, to staht 'im? Say fifty
dollahs! Twenty-five! Fifteen! Ten! Why, gentlemen! Not ten dollahs?
Remembah this is the Blue-grass Region of Kentucky—the land of
Boone an' Kenton, the home of Henry Clay!" he added, in an
oratorical crescendo.
"He ain't wuth his victuals," said an oily little tavern-keeper, folding
his arms restfully over his own stomach and cocking up one piggish
eye into his neighbor's face. "He ain't wuth his 'taters."
"Buy 'im foh 'is rags!" cried a young law-student, with a Blackstone
under his arm, to the town rag-picker opposite, who was
unconsciously ogling the vagrant's apparel.
"I might buy 'im foh 'is scalp," drawled a farmer, who had taken part
in all kinds of scalp contests and was now known to be busily
engaged in collecting crow scalps for a match soon to come off
between two rival counties.
"I think I'll buy 'im foh a hat-sign," said a manufacturer of ten-dollar
Castor and Rhorum hats. This sally drew merry attention to the
vagrant's hat, and the merchant felt rewarded.
"You'd bettah say the town ought to buy 'im an' put 'im up on top of
the cou't-house as a scarecrow foh the cholera," said some one else.
"What news of the cholera did the stage-coach bring this mohning?"
quickly inquired his neighbor in his ear; and the two immediately fell
into low, grave talk, forgot the auction, and turned away.
"Stop, gentlemen, stop!" cried the sheriff, who had watched the
rising tide of good-humor, and now saw his chance to float in on it
with spreading sails. "You're runnin' the price in the wrong direction
—down, not up. The law requires that he be sole to the highes'
biddah, not the lowes'. As loyal citizens, uphole the constitution of
the commonwealth of Kentucky an' make me an offah; the man is
really a great bargain. In the first place, he would cos' his ownah
little or nothin', because, as you see, he keeps himself in cigahs an'
clo'es; then, his main article of diet is whiskey—a supply of which he
always has on han'. He don't even need a bed, foh you know he
sleeps jus' as well on any doohstep; noh a chair, foh he prefers to sit
roun' on the curb-stones. Remembah, too, gentlemen, that ole King
Sol'mon is a Virginian—from the same neighbohhood as Mr. Clay.
Remembah that he is well educated, that he is an awful Whig, an'
that he has smoked mo' of the stumps of Mr. Clay's cigahs than any
other man in existence. If you don't b'lieve me, gentlemen, yondah
goes Mr. Clay now; call him ovah an' ask 'im foh yo'se'ves."
He paused, and pointed with his right forefinger towards Main street,
along which the spectators, with a sudden craning of necks, beheld
the familiar figure of the passing statesman.
"But you don't need anybody to tell you these fac's, gentlemen," he
continued. "You merely need to be reminded that ole King Sol'mon is
no ohdinary man. Mo'ovah he has a kine heaht, he nevah spoke a
rough wohd to anybody in this worl', an' he is as proud as Tecumseh
of his good name an' charactah. An', gentlemen," he added, bridling
with an air of mock gallantry and laying a hand on his heart, "if
anythin' fu'thah is required in the way of a puffect encomium, we all
know that there isn't anothah man among us who cuts as wide a
swath among the ladies. The'foh, if you have any appreciation of
virtue, any magnanimity of heaht; if you set a propah valuation upon
the descendants of Virginia, that mothah of Presidents; if you
believe in the pure laws of Kentucky as the pioneer bride of the
Union; if you love America an' love the worl'—make me a gen'rous,
high-toned offah foh ole King Sol'mon!"
He ended his peroration amid a shout of laughter and applause, and,
feeling satisfied that it was a good time for returning to a more
practical treatment of his subject, proceeded in a sincere tone:
"He can easily earn from one to two dollahs a day, an' from three to
six hundred a yeah. There's not anothah white man in town capable
of doin' as much work. There's not a niggah han' in the hemp
factories with such muscles an' such a chest. Look at 'em! An', if you
don't b'lieve me, step fo'wahd and feel 'em. How much, then, is bid
foh 'im?"
"One dollah!" said the owner of a hemp factory, who had walked
forward and felt the vagrant's arm, laughing, but coloring up also as
the eyes of all were quickly turned upon him. In those days it was
not an unheard-of thing for the muscles of a human being to be thus
examined when being sold into servitude to a new master.
"Thank you!" cried the sheriff, cheerily. "One precinc' heard from!
One dollah! I am offahed one dollah foh ole King Sol'mon. One
dollah foh the king! Make it a half. One dollah an' a half. Make it a
half. One dol-dol-dol-dollah!"
Two medical students, returning from lectures at the old Medical
Hall, now joined the group, and the sheriff explained:
"One dollah is bid foh the vagrant ole King Sol'mon, who is to be
sole into labah foh a twelvemonth. Is there any othah bid? Are you
all done? One dollah, once—"
"Dollah and a half," said one of the students, and remarked half
jestingly under his breath to his companion, "I'll buy him on the
chance of his dying. We'll dissect him."
"Would you own his body if he should die?"
"If he dies while bound to me, I'll arrange that."
"One dollah an' a half," resumed the sheriff; and falling into the tone
of a facile auctioneer he rattled on:
"One dollah an' a half foh ole Sol'mon—sol, sol, sol,—do, re, mi, fa,
sol—do, re, mi, fa, sol! Why, gentlemen, you can set the king to
music!"
All this time the vagrant had stood in the centre of that close ring of
jeering and humorous by-standers—a baffling text from which to
have preached a sermon on the infirmities of our imperfect
humanity. Some years before, perhaps as a master-stroke of
derision, there had been given to him that title which could but
heighten the contrast of his personality and estate with every
suggestion of the ancient sacred magnificence; and never had the
mockery seemed so fine as at this moment, when he was led forth
into the streets to receive the lowest sentence of the law upon his
poverty and dissolute idleness. He was apparently in the very prime
of life—a striking figure, for nature at least had truly done some
royal work on him. Over six feet in height, erect, with limbs well
shaped and sinewy, with chest and neck full of the lines of great
power, a large head thickly covered with long reddish hair, eyes blue,
face beardless, complexion fair but discolored by low passions and
excesses—such was old King Solomon. He wore a stiff, high, black
Castor hat of the period, with the crown smashed in and the torn
rim hanging down over one ear; a black cloth coat in the old style,
ragged and buttonless; a white cotton shirt, with the broad collar
crumpled, wide open at the neck and down his sunburnt bosom;
blue jeans pantaloons, patched at the seat and the knees; and
ragged cotton socks that fell down over the tops of his dusty shoes,
which were open at the heels.
In one corner of his sensual mouth rested the stump of a cigar. Once
during the proceedings he had produced another, lighted it, and
continued quietly smoking. If he took to himself any shame as the
central figure of this ignoble performance, no one knew it. There
was something almost royal in his unconcern. The humor, the
badinage, the open contempt, of which he was the public target, fell
thick and fast upon him, but as harmlessly as would balls of pith
upon a coat of mail. In truth, there was that in his great, lazy,
gentle, good-humored bulk and bearing which made the gibes seem
all but despicable. He shuffled from one foot to the other as though
he found it a trial to stand up so long, but all the while looking the
spectators full in the eyes without the least impatience. He suffered
the man of the factory to walk round him and push and pinch his
muscles as calmly as though he had been the show bull at a country
fair. Once only, when the sheriff had pointed across the street at the
figure of Mr. Clay, he had looked quickly in that direction with a
kindling light in his eye and a passing flush on his face. For the rest,
he seemed like a man who has drained his cup of human life and
has nothing left him but to fill again and drink without the least
surprise or eagerness.
The bidding between the man of the factory and the student had
gone slowly on. The price had reached ten dollars. The heat was
intense, the sheriff tired. Then something occurred to revivify the
scene. Across the market-place and towards the steps of the court-
house there suddenly came trundling along in breathless haste a
huge old negress, carrying on one arm a large shallow basket
containing apple crab-lanterns and fresh gingerbread. With a series
of half-articulate grunts and snorts she approached the edge of the
crowd and tried to force her way through. She coaxed, she begged,
she elbowed and pushed and scolded, now laughing, and now with
the passion of tears in her thick, excited voice. All at once, catching
sight of the sheriff, she lifted one ponderous brown arm, naked to
the elbow, and waved her hand to him above the heads of those in
front.
"Hole on, marseter! Hole on!" she cried, in a tone of humorous
entreaty. "Don' knock 'im off till I come! Gim me a bid at 'im!"
The sheriff paused and smiled. The crowd made way tumultuously,
with broad laughter and comment.
"Stan' aside theah an' let Aun' Charlotte in!"
"Now you'll see biddin'!"
"Get out of the way foh Aun' Charlotte!"
"Up, my free niggah! Hurrah foh Kentucky!"
A moment more and she stood inside the ring of spectators, her
basket on the pavement at her feet, her hands plumped akimbo into
her fathomless sides, her head up, and her soft, motherly eyes
turned eagerly upon the sheriff. Of the crowd she seemed
unconscious, and on the vagrant before her she had not cast a
single glance.
She was dressed with perfect neatness. A red and yellow Madras
kerchief was bound about her head in a high coil, and another was
crossed over the bosom of her stiffly starched and smoothly ironed
blue cottonade dress. Rivulets of perspiration ran down over her
nose, her temples, and around her ears, and disappeared
mysteriously in the creases of her brown neck. A single drop
accidentally hung glistening like a diamond on the circlet of one of
her large brass ear-rings.
The sheriff looked at her a moment, smiling, but a little
disconcerted. The spectacle was unprecedented.
"What do you want heah, Aun' Charlotte?" he asked, kindly. "You
can't sell yo' pies an' gingerbread heah."
"I don' wan' sell no pies en gingerbread," she replied,
contemptuously. "I wan' bid on him," and she nodded sidewise at
the vagrant.
"White folks allers sellin' niggahs to wuk fuh dem; I gwine buy a
white man to wuk fuh me. En he gwine t' git a mighty hard mistiss,
you heah me!"
The eyes of the sheriff twinkled with delight.
"Ten dollahs is offahed foh ole King Sol'mon. Is theah any othah bid?
Are you all done?"
"'Leben," she said.
Two young ragamuffins crawled among the legs of the crowd up to
her basket and filched pies and cake beneath her very nose.
"Twelve!" cried the student, laughing.
"Thirteen!" she laughed too, but her eyes flashed.
"You are bidding against a niggah," whispered the student's
companion in his ear.
"So I am; let's be off," answered the other, with a hot flush on his
proud face.
Thus the sale was ended, and the crowd variously dispersed. In a
distant corner of the court-yard the ragged urchins were devouring
their unexpected booty. The old negress drew a red handkerchief out
of her bosom, untied a knot in a corner of it, and counted out the
money to the sheriff. Only she and the vagrant were now left on the
spot.
"You have bought me. What do you want me to do?" he asked
quietly.
"Lohd, honey!" she answered, in a low tone of affectionate chiding,
"I don' wan' you to do nothin'! I wuzn' gwine t' 'low dem white folks
to buy you. Dey'd wuk you till you dropped dead. You go 'long en do
ez you please."
She gave a cunning chuckle of triumph in thus setting at naught the
ends of justice, and, in a voice rich and musical with affection, she
said, as she gave him a little push:
"You bettah be gittin' out o' dis blazin' sun. G' on home! I be 'long
by-en-by."
He turned and moved slowly away in the direction of Water Street,
where she lived; and she, taking up her basket, shuffled across the
market-place towards Cheapside, muttering to herself the while:
"I come mighty nigh gittin' dah too late, foolin' 'long wid dese pies.
Sellin' him 'ca'se he don' wuk! Umph! If all de men in dis town dat
don' wuk wuz to be tuk up en sole, d' wouldn' be 'nough money in
de town to buy 'em! Don' I see 'em settin' 'roun' dese taverns f'om
mohnin' till night?"
She snorted out her indignation and disgust, and sitting down on the
sidewalk, under a Lombardy poplar, uncovered her wares and kept
the flies away with a locust bough, not discovering, in her
alternating good and ill humor, that half of them had been filched by
her old tormentors.
This was the memorable scene enacted in Lexington on that
memorable day of the year 1833—a day that passed so briskly. For
whoever met and spoke together asked the one question: Will the
cholera come to Lexington? And the answer always gave a nervous
haste to business—a keener thrill to pleasure. It was of the cholera
that the negro woman heard two sweet passing ladies speak as she
spread her wares on the sidewalk. They were on their way to a little
picture-gallery just opened opposite M. Giron's ball-room, and in one
breath she heard them discussing their toilets for the evening and in
the next several portraits by Jouett.
So the day passed, the night came on, and M. Xaupi gave his
brilliant ball. Poor old Xaupi—poor little Frenchman! whirled as a
gamin of Paris through the mazes of the Revolution, and lately come
all the way to Lexington to teach the people how to dance. Hop
about blithely on thy dry legs, basking this night in the waxen
radiance of manners and melodies and graces! Where will be thy
tunes and airs to-morrow? Ay, smile and prompt away! On and on!
Swing corners, ladies and gentlemen! Form the basket! Hands all
around!
While the bows were still darting across the strings, out of the low,
red east there shot a long, tremulous bow of light up towards the
zenith. And then, could human sight have beheld the invisible, it
might have seen hovering over the town, over the ball-room, over M.
Xaupi, the awful presence of the plague.
But knowing nothing of this, the heated revellers went merrily home
in the chill air of the red and saffron dawn. And knowing nothing of
it also, a man awakened on the door-step of a house opposite the
ball-room, where he had long since fallen asleep. His limbs were
cramped and a shiver ran through his frame. Staggering to his feet,
he made his way down to the house of Free Charlotte, mounted to
his room by means of a stair-way opening on the street, threw off
his outer garments, kicked off his shoes, and taking a bottle from a
closet pressed it several times to his lips with long outward breaths
of satisfaction. Then, casting his great white bulk upon the bed, in a
minute more he had sunk into a heavy sleep—the usual drunken
sleep of old King Solomon.
He, too, had attended M. Xaupi's ball, in his own way and in his
proper character, being drawn to the place for the pleasure of seeing
the fine ladies arrive and float in, like large white moths of the
summer night; of looking in through the open windows at the many-
colored waxen lights and the snowy arms and shoulders, of having
blown out to him the perfume and the music; not worthy to go in,
being the lowest of the low, but attending from a door-step of the
street opposite—with a certain rich passion in his nature for splendor
and revelry and sensuous beauty.

II.
About 10 o'clock the sunlight entered through the shutters and
awoke him. He threw one arm up over his eyes to intercept the
burning rays. As he lay out-stretched and stripped of grotesque rags,
it could be better seen in what a mould nature had cast his figure.
His breast, bare and tanned, was barred by full, arching ribs and
knotted by crossing muscles; and his shirt-sleeve, falling away to the
shoulder from his bent arm, revealed its crowded muscles in the
high relief of heroic bronze. For, although he had been sold as a
vagrant, old King Solomon had in earlier years followed the trade of
a digger of cellars, and the strenuous use of mattock and spade had
developed every sinew to the utmost. His whole person, now half
naked and in repose, was full of the suggestions of unspent power.
Only his face, swollen and red, only his eyes, bloodshot and dull,
bore the impress of wasted vitality. There, all too plainly stamped,
were the passions long since raging and still on fire.
The sunlight had stirred him to but a low degree of consciousness,
and some minutes passed before he realized that a stifling, resinous
fume impregnated the air. He sniffed it quickly; through the window
seemed to come the smell of burning tar. He sat up on the edge of
the bed and vainly tried to clear his thoughts.
The room was a clean but poor habitation—uncarpeted,
whitewashed, with a piece or two of the cheapest furniture, and a
row of pegs on one wall, where usually hung those tattered coats
and pantaloons, miscellaneously collected, that were his purple and
fine linen. He turned his eyes in this direction now and noticed that
his clothes were missing. The old shoes had disappeared from their
corner; the cigar stumps, picked up here and there in the streets
according to his wont, were gone from the mantel-piece. Near the
door was a large bundle tied up in a sheet. In a state of
bewilderment, he asked himself what it all meant. Then a sense of
the silence in the street below possessed him. At this hour he was
used to hear noises enough—from Hugh Lonney's new bath-house
on one side, from Harry Sikes's barber-shop on the other.
A mysterious feeling of terror crept over and helped to sober him.
How long had he lain asleep? By degrees he seemed to remember
that two or three times he had awakened far enough to drink from
the bottle under his pillow, only to sink again into heavier
stupefaction. By degrees, too, he seemed to remember that other
things had happened—a driving of vehicles this way and that, a
hurrying of people along the street. He had thought it the breaking-
up of M. Xaupi's ball. More than once had not some one shaken and
tried to arouse him? Through the wall of Harry Sikes's barber-shop
had he not heard cries of pain—sobs of distress?
He staggered to the window, threw open the shutters, and, kneeling
at the sill, looked out. The street was deserted. The houses opposite
were closed. Cats were sleeping in the silent door-ways. But as he
looked up and down he caught sight of people hurrying along cross-
streets. From a distant lumber-yard came the muffled sound of rapid
hammerings. On the air was the faint roll of vehicles—the hush and
the vague noises of a general terrifying commotion.
In the middle of the street below him a keg was burning, and, as he
looked, the hoops gave way, the tar spread out like a stream of
black lava, and a cloud of inky smoke and deep-red furious flame
burst upward through the sagging air. Just beneath the window a
common cart had been backed close up to the door of the house. In
it had been thrown a few small articles of furniture, and on the
bottom bedclothes had been spread out as if for a pallet. While he
looked old Charlotte hurried out with a pillow.
He called down to her in a strange, unsteady voice:
"What is the matter? What are you doing, Aunt Charlotte?"
She uttered a cry, dropped the pillow, and stared up at him. Her face
looked dry and wrinkled.
"My God! De chol'ra's in town! I'm waitin' on you! Dress, en come
down en fetch de bun'le by de dooh." And she hurried back into the
house.
But he continued leaning on his folded arms, his brain stunned by
the shock of the intelligence. Suddenly he leaned far out and looked
down at the closed shutters of the barber-shop. Old Charlotte
reappeared.
"Where is Harry Sikes?" he asked.
"Dead en buried."
"When did he die?"
"Yestidd'y evenin'."
"What day is this?"
"Sadd'y."
M. Xaupi's ball had been on Thursday evening. That night the
cholera had broken out. He had lain in his drunken stupor ever
since. Their talk had lasted but a minute, but she looked up
anxiously and urged him.
"D' ain' no time to was'e, honey! D' ain' no time to was'e. I done got
dis cyart to tek you 'way in, en I be ready to start in a minute. Put
yo' clo'es on en bring de bun'le wid all yo' yudder things in it."
With incredible activity she climbed into the cart and began to roll up
the bedclothes. In reality she had made up her mind to put him into
the cart, and the pallet had been made for him to lie and finish his
drunken sleep on, while she drove him away to a place of safety.
Still he did not move from the window-sill. He was thinking of Harry
Sikes, who had shaved him many a time for nothing. Then he
suddenly called down to her:
"Have many died of the cholera? Are there many cases in town?"
She went on with her preparations and took no notice of him. He
repeated the question. She got down quickly from the cart and
began to mount the staircase. He went back to bed, pulled the sheet
up over him, and propped himself up among the pillows. Her soft,
heavy footsteps slurred on the stair-way as though her strength
were failing, and as soon as she entered the room she sank into a
chair, overcome with terror. He looked at her with a sudden sense of
pity.
"Don't be frightened," he said, kindly. "It might only make it the
worse for you."
"I can' he'p it, honey," she answered, wringing her hands and
rocking herself to and fro; "de ole niggah can' he'p it. If de Lohd jes
spah me to git out'n dis town wid you! Honey, ain' you able to put
on yo' clo'es?"
"You've tied them all up in the sheet."
"De Lohd he'p de crazy ole niggah!"
She started up and tugged at the bundle, and laid out a suit of his
clothes, if things so incongruous could be called a suit.
"Have many people died of the cholera?"
"Dey been dyin' like sheep ev' since yestidd'y mohnin'—all day, en all
las' night, en dis mohnin'! De man he done lock up de huss, en dey
been buryin' 'em in cyarts. En de grave-diggah he done run away, en
hit look like d' ain' nobody to dig de graves."
She bent over the bundle, tying again the four corners of the sheet.
Through the window came the sound of the quick hammers driving
nails. She threw up her arms into the air, and then seizing the
bundle dragged it rapidly to the door.
"You heah dat? Dey nailin' up cawfins in de lumbah-yahd! Put on yo'
clo'es, honey, en come on."
A resolution had suddenly taken shape in his mind.
"Go on away and save your life. Don't wait for me; I'm not going.
And good-bye, Aunt Charlotte, in case I don't see you any more.
You've been very kind to me—kinder than I deserved. Where have
you put my mattock and spade?"
He said this very quietly, and sat up on the edge of the bed, his feet
hanging down, and his hand stretched out towards her.
"Honey," she explained, coaxingly, from where she stood, "can't you
sobah up a little en put on yo' clo'es? I gwine to tek you 'way to de
country. You don' wan' no tools. You can' dig no cellahs now. De
chol'ra's in town en de people's dyin' like sheep."
"I expect they will need me," he answered.
She perceived now that he was sober. For an instant her own fear
was forgotten in an outburst of resentment and indignation.
"Dig graves fuh 'em, when dey put you up on de block en sell you
same ez you wuz a niggah! Dig graves fuh 'em, when dey allers
callin' you names on de street en makin' fun o' you!"
"They are not to blame. I have brought it on myself."
"But we can' stay heah en die o' de chol'ra!"
"You mustn't stay. You must go away at once."
"But if I go, who gwine tek cyah o' you?"
"Nobody."
She came quickly across the room to the bed, fell on her knees,
clasped his feet to her breast, and looked up into his face with an
expression of imploring tenderness. Then, with incoherent cries and
with sobs and tears, she pleaded with him—pleaded for dear life; his
and her own.
It was a strange scene. What historian of the heart will ever be able
to do justice to those peculiar ties which bound the heart of the
negro in years gone by to a race of not always worthy masters? This
old Virginia nurse had known King Solomon when he was a boy
playing with her young master, till that young master died on the
way to Kentucky.
At the death of her mistress she had become free with a little
property. By thrift and industry she had greatly enlarged this. Years
passed and she became the only surviving member of the Virginian
household, which had emigrated early in the century to the Blue-
grass Region. The same wave of emigration had brought in old King
Solomon from the same neighborhood. As she had risen in life, he
had sunk. She sat on the sidewalks selling her fruits and cakes; he
sat on the sidewalks more idle, more ragged and dissolute. On no
other basis than these facts she began to assume a sort of maternal
pitying care of him, patching his rags, letting him have money for his
vices, and when, a year or two before, he had ceased working
almost entirely, giving him a room in her house and taking in
payment what he chose to pay.
He brushed his hand quickly across his eyes as she knelt before him
now, clasping his feet to her bosom. From coaxing him as an
intractable child she had, in the old servile fashion, fallen to
imploring him, with touching forgetfulness of their real relations:
"O my marseter! O my marseter Solomon! Go 'way en save yo' life,
en tek yo' po' ole niggah wid you!"
But his resolution was formed, and he refused to go. A hurried
footstep paused beneath the window and a loud voice called up. The
old nurse got up and went to the window. A man was standing by
the cart at her door.
"For God's sake let me have this cart to take my wife and little
children away to the country! There is not a vehicle to be had in
town. I will pay you—" He stopped, seeing the distress on her face.
"Is he dead?" he asked, for he knew of her care of old King
Solomon.
"He will die!" she sobbed. "Tilt de t'ings out on de pavement. I
gwine t' stay wid 'im en tek cyah o' 'im."

III.
A little later, dressed once more in grotesque rags and carrying on
his shoulder a rusty mattock and a rusty spade, old King Solomon
appeared in the street below and stood looking up and down it with
an air of anxious indecision. Then shuffling along rapidly to the
corner of Mill Street, he turned up towards Main.
Here a full sense of the terror came to him. A man, hurrying along
with his head down, ran full against him and cursed him for the
delay:
"Get out of my way, you old beast!" he cried. "If the cholera would
carry you off it would be a blessing to the town."
Two or three little children, already orphaned and hungry, wandered
past, crying and wringing their hands. A crowd of negro men with
the muscles of athletes, some with naked arms, some naked to the
waist, their eyes dilated, their mouths hanging open, sped along in
tumultuous disorder. The plague had broken out in the hemp factory
and scattered them beyond control.
He grew suddenly faint and sick. His senses swam, his heart seemed
to cease beating, his tongue burned, his throat was dry, his spine
like ice. For a moment the contagion of deadly fear overcame him,
and, unable to stand, he reeled to the edge of the sidewalk and sat
down.
Before him along the street passed the flying people—men on
horseback with their wives behind and children in front, families in
carts and wagons, merchants in two-wheeled gigs and sulkies. A
huge red and yellow stage-coach rolled ponderously by, filled within,
on top, in front, and behind with a company of riotous students of
law and of medicine. A rapid chorus of voices shouted to him as they
passed:
"Good-bye, Solomon!"
"The cholera'll have you befoah sunset!"
"Better be diggin' yoah grave, Solomon! That 'll be yoah last cellah."
"Dig us a big wine cellah undah the Medical Hall while we are away."
"And leave yo' body there! We want yo' skeleton."
"Good-bye, old Solomon!"
A wretched carry-all passed with a household of more wretched
women; their tawdry and gay attire, their haggard and painted and
ghastly faces, looking horrible in the blaze of the pitiless sunlight.
They, too, simpered and hailed him and spent upon him their
hardened and degraded badinage. Then there rolled by a high-
swung carriage, with the most luxurious of cushions, upholstered
with morocco, with a coat-of-arms, a driver and a footman in livery,
and drawn by sparkling, prancing horses. Lying back on the satin
cushions a fine gentleman; at the window of the carriage two rosy
children, who pointed their fingers at the vagrant and turned and
looked into their father's face, so that he leaned forward, smiled,
leaned back again, and was whirled away to a place of safety.
Thus they passed him, as he sat down on the sidewalk—even
physicians from their patients, pastors from their stricken flocks.
Why should not he flee? He had no ties, except the faithful affection
of an old negress. Should he not at least save her life by going away,
seeing that she would not leave him?
The orphaned children wandered past again, sobbing more wearily.
He called them to him.
"Why do you not go home? Where is your mother?" he asked.
"She is dead in the house," they answered; "and no one has come to
bury her."
Slowly down the street was coming a short funeral train. It passed—
a rude cortege: a common cart, in the bottom of which rested a box
of plain boards containing the body of the old French dancing-
master; walking behind it, with a cambric handkerchief to his eyes,
the old French confectioner; at his side, wearing the robes of his
office and carrying an umbrella to ward off the burning sun, the
beloved Bishop Smith; and behind them, two by two and with linked
arms, perhaps a dozen men, most of whom had been at the ball.
No head was lifted or eye turned to notice the vagrant seated on the
sidewalk. But when the train had passed he rose, laid his mattock
and spade across his shoulder, and, stepping out into the street, fell
into line at the end of the procession.
They moved down Short Street to the old burying-ground, where the
Baptist church-yard is to-day. As they entered it, two grave-diggers
passed out and hurried away. Those before them had fled. They had
been at work but a few hours. Overcome with horror at the sight of
the dead arriving more and more rapidly, they, too, deserted that
post of peril. No one was left. Here and there in the church-yard
could be seen bodies awaiting interment. Old King Solomon stepped
quietly forward and, getting down into one of the half-finished
graves, began to dig.
The vagrant had happened upon an avocation.

IV.
All summer long, Clatterbuck's dancing-pavilion was as silent in its
grove of oaks as a temple of the Druids, and his pleasure-boat
nestled in its moorings, with no hand to feather an oar in the little
lake. All summer long, no athletic young Kentuckians came to bathe
their white bodies in Hugh Lonney's new bath-house for twelve and
a half cents, and no one read Daukins Tegway's advertisement that
he was willing to exchange his Dunstable bonnets for flax and
feathers. The likely runaway boy, with a long, fresh scar across his
face, was never found, nor the buffalo bull roasted for Daniel
Webster, and Peter Leuba's guitars were never thrummed on any
moonlit verandas. Only Dewees and Grant were busy, dispensing,
not snuff, but calomel.
Grass grew in the deserted streets. Gardens became little
wildernesses of rank weeds and riotous creepers. Around shut
window-lattices roses clambered and shed their perfume into the
poisoned air, or dropped their faded petals to strew the echoless
thresholds. In darkened rooms family portraits gazed on sad vacancy
or looked helplessly down on rigid sheeted forms.
In the trees of poplar and locust along the streets the unmolested
birds built and brooded. The oriole swung its hempen nest from a
bough over the door of the spider-tenanted factory, and in front of
the old Medical Hall the blue-jay shot up his angry crest and
screamed harshly down at the passing bier. In a cage hung against
the wall of a house in a retired street a mocking-bird sung, beat its
breast against the bars, sung more passionately, grew silent and
dropped dead from its perch, never knowing that its mistress had
long since become a clod to its full-throated requiem.
Famine lurked in the wake of the pestilence. Markets were closed. A
few shops were kept open to furnish necessary supplies. Now and
then some old negro might have been seen, driving a meat-wagon in
from the country, his nostrils stuffed with white cotton saturated
with camphor. Oftener the only visible figure in the streets was that
of a faithful priest going about among his perishing fold, or that of
the bishop moving hither and thither on his ceaseless ministrations.
But over all the ravages of that terrible time there towered highest
the solitary figure of that powerful grave-digger, who, nerved by the
spectacle of the common misfortune, by one heroic effort rose for
the time above the wrecks of his own nature. In the thick of the
plague, in the very garden spot of the pestilence, he ruled like an
unterrified king. Through days unnaturally chill with gray cloud and
drizzling rain, or unnaturally hot with the fierce sun and suffocating
damps that appeared to steam forth from subterranean caldrons, he
worked unfaltering, sometimes with a helper, sometimes with none.
There were times when, exhausted, he would lie down in the half-
dug graves and there sleep until able to go on; and many a midnight
found him under the spectral moon, all but hidden by the rank
nightshade as he bent over to mark out the lines of one of those
narrow mortal cellars.
What weaknesses he fought and conquered through those days and
nights! Out of what unforeseen depths of nature did he draw the
tough fibre of such a resolution! To be alone with the pestilential
dead at night—is not that a test of imperial courage? To live for
weeks braving swift death itself—is not that the fierce and
ungovernable flaring up of the soul in heroism? For all the mockery
and derision of his name, had it not some fitness? For had he not a
royal heart?

V.
Nature soon smiles upon her own ravages and strews our graves
with flowers, not as memories, but for other flowers when the spring
returns.
It was one cool, brilliant morning late in that autumn. The air blew
fresh and invigorating, as though on the earth there were no
corruption, no death. Far southward had flown the plague. A
spectator in the open court-square might have seen many signs of
life returning to the town. Students hurried along, talking eagerly.
Merchants met for the first time and spoke of the winter trade. An
old negress, gayly and neatly dressed, came into the market-place,
and sitting down on a sidewalk displayed her yellow and red apples
and fragrant gingerbread. She hummed to herself an old cradle-
song, and in her soft, motherly black eyes shone a mild, happy
radiance. A group of young ragamuffins eyed her longingly from a
distance. Court was to open for the first time since the spring. The
hour was early, and one by one the lawyers passed slowly in. On the
steps of the court-house three men were standing: Thomas Brown,
the sheriff; old Peter Leuba, who had just walked over from his
music-store on Main Street; and little M. Giron, the French
confectioner. Each wore mourning on his hat, and their voices were
low and grave.
"Gentlemen," the sheriff was saying, "it was on this very spot the
day befoah the cholera broke out that I sole 'im as a vagrant. An' I
did the meanes' thing a man can evah do. I hel' 'im up to public
ridicule foh his weaknesses an' made spoht of 'is infirmities. I
laughed at 'is povahty an' 'is ole clo'es. I delivahed on 'im as
complete an oration of sarcastic detraction as I could prepare on the
spot, out of my own meanness an' with the vulgah sympathies of
the crowd. Gentlemen, if I only had that crowd heah now, an' ole
King Sol'mon standin' in the midst of it, that I might ask 'im to
accept a humble public apology, offahed from the heaht of one who
feels himself unworthy to shake 'is han'! But, gentlemen, that crowd
will nevah reassemble. Neahly ev'ry man of them is dead, an' ole
King Sol'mon buried them."
"He buried my friend Adolphe Xaupi," said François Giron, touching
his eyes with his handkerchief.
"There is a case of my best Jamaica rum for him whenever he comes
for it," said old Leuba, clearing his throat.
"But, gentlemen, while we are speakin' of ole King Sol'mon we ought
not to fohget who it is that has supported 'im. Yondah she sits on
the sidewalk, sellin' 'er apples an' gingerbread."
The three men looked in the direction indicated.
"Heah comes ole King Sol'mon now," exclaimed the sheriff.
Across the open square the vagrant was seen walking slowly along
with his habitual air of quiet, unobtrusive preoccupation. A minute
more and he had come over and passed into the court-house by a
side door.
"Is Mr. Clay to be in court to-day?"
"He is expected, I think."
"Then let's go in; there will be a crowd."
"I don't know; so many are dead."
They turned and entered and found seats as quietly as possible; for
a strange and sorrowful hush brooded over the court-room. Until the
bar assembled, it had not been realized how many were gone. The
silence was that of a common overwhelming disaster. No one spoke
with his neighbor, no one observed the vagrant as he entered and
made his way to a seat on one of the meanest benches, a little apart
from the others. He had not sat there since the day of his indictment
for vagrancy. The judge took his seat and, making a great effort to
control himself, passed his eyes slowly over the court-room. All at
once he caught sight of old King Solomon sitting against the wall in
an obscure corner; and before any one could know what he was
doing, he hurried down and walked up to the vagrant and grasped
his hand. He tried to speak, but could not. Old King Solomon had
buried his wife and daughter—buried them one clouded midnight,
with no one present but himself.
Then the oldest member of the bar started up and followed the
example; and then the other members, rising by a common impulse,
filed slowly back and one by one wrung that hard and powerful
hand. After them came the other persons in the court-room. The
vagrant, the grave-digger, had risen and stood against the wall, at
first with a white face and a dazed expression, not knowing what it
meant; afterwards, when he understood it, his head dropped
suddenly forward and his tears fell thick and hot upon the hands
that he could not see. And his were not the only tears. Not a man in
the long file but paid his tribute of emotion as he stepped forward to
honor that image of sadly eclipsed but still effulgent humanity. It
was not grief, it was not gratitude, nor any sense of making
reparation for the past. It was the softening influence of an act of
heroism, which makes every man feel himself a brother hand in
hand with every other—such power has a single act of moral
greatness to reverse the relations of men, lifting up one, and
bringing all others to do him homage.
It was the coronation scene in the life of old King Solomon of
Kentucky.
"The woods are hushed, their music is no more:
The leaf is dead, the yearning passed away:
New leaf, new life—the days of frost are o'er:
New life, new love, to suit the newer day."

THE WOODS ARE HUSHED.


It was near the middle of the afternoon of an autumnal day, on the
wide, grassy plateau of Central Kentucky.
The Eternal Power seemed to have quitted the universe and left all
nature folded in the calm of the Eternal Peace. Around the pale blue
dome of the heavens a few pearl-colored clouds hung motionless, as
though the wind had been withdrawn to other skies. Not a crimson
leaf floated downward through the soft, silvery light that filled the
atmosphere and created the sense of lonely, unimaginable spaces.
This light overhung the far-rolling landscape of field and meadow
and wood, crowning with faint radiance the remoter low-swelling
hill-tops and deepening into dreamy half-shadows on their eastern
slopes. Nearer, it fell in a white flake on an unstirred sheet of water
which lay along the edge of a mass of sombre-hued woodland, and
nearer still it touched to spring-like brilliancy a level, green meadow
on the hither edge of the water, where a group of Durham cattle
stood with reversed flanks near the gleaming trunks of some leafless
sycamores. Still nearer, it caught the top of the brown foliage of a
little bent oaktree and burned it into a silvery flame. It lit on the
back and the wings of a crow flying heavily in the path of its rays,
and made his blackness as white as the breast of a swan. In the

Вам также может понравиться