Learning Blazor Build Single-Page Apps with WebAssembly and C# Compliments of David Pine Foreword by Steve Sanderson Learning Blazor Take advantage of your C# skills to build UI components and client-side experiences with .NET. With this practical guide, “The Blazor open you’ll learn how to use Blazor WebAssembly to develop next- source web framework generation web experiences. Built on top of ASP.NET Core, is a whole new way Blazor represents the future of .NET single-page application to develop powerful investments. applications for the web. Author David Pine, who focuses on .NET and Azure content Learning Blazor uses development at Microsoft, explains how WebAssembly tons of examples and enables many non-JavaScript-based programming languages prescriptive code based to run on the client browser. In this book, you’ll learn about on David Pine’s deep real-time web functionality with ASP.NET Core SignalR and experience as a content discover strategies for bidirectional JavaScript interop. David developer on the .NET also covers component data binding, hierarchical event- team to get you writing driven communications, in-memory state management, and Blazor web apps with C# local storage. today!” This book shows you how to: —Scott Hanselman • Create a beautiful, feature-rich Blazor app Partner Program Manager, Developer Division, Microsoft • Develop and localize an enterprise-scale app using GitHub Actions and Azure Cognitive Services Translator • Create advanced validation scenarios for input-based David Pine is a senior content developer at Microsoft, where he components with forms focuses on .NET and Azure developer • Automatically deploy and host to Azure Static Web Apps, content. He’s recognized as a Google and rely on HTTP services Developer Expert in Web Technologies and is a Twilio Champion. Before joining • Use a geolocation service and speech synthesis and Microsoft, David was a Microsoft MVP recognition native to the browser in Developer Technologies for several • Author a custom modal verification mechanism for validating years. He thrives in the developer community, sharing his knowledge a user through speaking engagements around the world. PROGRAMMING Twitter: @oreillymedia linkedin.com/company/oreilly-media US $59.99 CAN $74.99 youtube.com/oreillymedia IISSBBNN:: 997788--11--049928--0119382441--76 Praise for Learning Blazor Learning Blazor is the perfect resource for developers who are looking to build modern web applications using bleeding-edge web technologies. David leverages his skills as a senior content developer to help you get started with Blazor! —Scott Hunter, VP Director Azure Developer Experience, Microsoft David Pine’s Learning Blazor takes developers on the perfect journey to learning how to build and deploy their Blazor applications. David leverages his extensive content development and presentation skills to inspire you to build Blazor web apps today. —Maria Naggaga, Principal Product Manager Lead, ASP.NET and .NET Interactive, Microsoft Like its author, this book will inspire folks to try new things with Blazor and to be excited about the possibilities of building apps it brings. David’s delightful style of writing code as eloquent as his prose, coupled with a genuine love for .NET and using it creatively, will make any developer fall in love with web development all over again. —Brady Gaster, Principal Program Manager, .NET Team, Microsoft As an experienced Blazor developer, I learned more about localization and testing from David Pine in 20 minutes of reading than I did in days of searching for similar insight online. Not only is Learning Blazor an educational piece, but it’s also a great reference that I will return to when building future Blazor applications. —Jeff Fritz, Live Streamer and Principle Program Manager, .NET Team, Microsoft Learning Blazor is a well-paced guide that is perfectly suited for anyone with .NET experience who would like to learn Blazor to build web apps, and for anyone looking to refine their Blazor skills. —Lana Lux, Game Developer, Tech Streamer, and Founder of Lux Games Learning Blazor is one of the most informative books I have ever read, and it makes you want to start developing with WebAssembly and C# right away. Learning Blazor uses a great storyline and practical real-world examples to explain a modern technology and how it can be combined with JavaScript and HTML. A must-read for every web developer. —Fabian Gosebrink, Senior Developer, Microsoft MVP, and Google Developer Expert, Offering Solutions Software There are so many gems in here that you are guaranteed to learn something regardless of your experience level. It has inspired me to add techniques and features to my projects that I’ve never considered before. —Cecil L. Phillip, Staff Developer Advocate, Stripe Learning Blazor Build Single-Page Apps with WebAssembly and C# David Pine Foreword by Steve Sanderson BBeeiijjiinngg BBoossttoonn FFaarrnnhhaamm SSeebbaassttooppooll TTookkyyoo Learning Blazor by David Pine Copyright © 2023 David Pine. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Acquisitions Editor: Amanda Quinn Indexer: nSight, Inc. Development Editor: Rita Fernando Interior Designer: David Futato Production Editor: Gregory Hyman Cover Designer: Karen Montgomery Copyeditor: Stephanie English Illustrator: Kate Dullea Proofreader: Piper Editorial Consulting, LLC October 2022: First Edition Revision History for the First Edition 2022-09-26: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098113247 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Blazor, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author, and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. This work is part of a collaboration between O’Reilly and Progress Software. See our statement of editorial independence. 978-1-492-09841-6 [LSI] Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. Blazing into Blazor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 The Origin of Blazor 1 Blazor Hosting 3 Blazor Server 3 Blazor WebAssembly 4 Blazor Hybrid 6 Single-Page Applications, Redefined 6 Why Adopt Blazor 7 .NET’s Potential in the Browser 8 .NET Is Here to Stay 9 Familiarity 9 Safe and Secure 10 Code Reuse 10 Tooling 11 Open Source Software 13 Your First Blazor App with the .NET CLI 14 Build the App 15 Install Dev-cert 15 Run the App 16 The Code Must Live On 17 Perusing the “Learning Blazor” Sample App 19 Summary 21 iii 2. Executing the App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Requesting the Initial Page 24 App Startup and Bootstrapping 25 Blazor WebAssembly App Internals 32 Detecting Client Culture at Startup 34 Layouts, Shared Components, and Navigation 35 Summary 59 3. Componentizing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Design with the User in Mind 61 Leveraging “Pwned” Functionality 63 “Have I Been Pwned” Client Services 65 Restricting Access to Resources 73 The Introduction Component Says “Hi” 75 The Joke Component and Services 77 Aggregating Joke Services—Laughter Ensues 81 DI from Library Authors 88 Forecasting Local Weather 89 Summary 103 4. Customizing the User Login Experience. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 A Bit More on Blazor Authentication 105 Client-Side Custom Authorization Message Handler Implementation 106 The Web.Client ConfigureServices Functionality 113 Native Speech Synthesis 117 Sharing and Consuming Custom Components 123 Chrome: The Overloaded Term 124 Modal Modularity and Blazor Component Hierarchies 124 Exploring Blazor Event Binding 129 Summary 137 5. Localizing the App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 What Is Localization? 139 The Localization Process 140 The Language Selection Component 143 Automating Translations with GitHub Actions 151 Localization in Action 154 Summary 165 6. Exemplifying Real-Time Web Functionality. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 Defining the Server-Side Events 167 iv | Table of Contents Exposing Twitter Streams and Chat Functionality 168 Writing Contextual RPC and Inner-Process Communication 174 Configuring the Hub Endpoint 177 Consuming Real-Time Data on the Client 181 Configuring the Client 181 Sharing a Hub Connection 182 Consuming Real-Time Data in Components 190 Summary 204 7. Using Source Generators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 What Are Source Generators? 205 Building a Case for Source Generators 206 C# Source Generators in Action 209 Source Generating the localStorage API 209 Source Generating the Geolocation API 215 Example Usage of the ILocalStorageService 223 Summary 231 8. Accepting Form Input with Validation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 The Basics of Form Submission 233 Framework-Provided Components for Forms 234 Models and Data Annotations 235 Defining Component Models 236 Defining and Consuming Validation Attributes 237 Implementing a Contact Form 240 Implementing Speech Recognition as User Input 252 Reactive Programming with the Observer Pattern 259 Managing Callbacks with a Registry 261 Applying the Speech Recognition Service to Components 263 Form Submission Validation and Verification 266 Summary 268 9. Testing All the Things. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 Why Test? 269 Unit Testing 269 Defining Unit-Testable Code 270 Writing an Extension Method Unit Test 272 Component Testing 276 End-to-End Testing with Playwright 279 Automating Test Execution 284 Summary 286 Table of Contents | v