everand.content_preview.content.explore_1_5m_audiobooks_ebooks_free_trial

Only $12.99 CAD/month after trial. Cancel anytime.

Web Development with Blazor: A practical guide to building interactive UIs with C# 12 and .NET 8
Web Development with Blazor: A practical guide to building interactive UIs with C# 12 and .NET 8
Web Development with Blazor: A practical guide to building interactive UIs with C# 12 and .NET 8
Ebook957 pages3 hours

Web Development with Blazor: A practical guide to building interactive UIs with C# 12 and .NET 8

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateApr 29, 2024
ISBN9781835466698
Web Development with Blazor: A practical guide to building interactive UIs with C# 12 and .NET 8
Author

Jimmy Engström

Jimmy Engström  has been developing ever since he was 7 years old and got his first computer. He loves to be on the cutting edge of technology, trying new things. When he got wind of Blazor, he immediately realized its potential and adopted it when it was in beta. He has been running Blazor in production since it was launched by Microsoft. His passion for the .NET industry and community has taken him around the world, speaking about development. Microsoft has recognized this passion by awarding him the Microsoft Most Valuable Professional award 10 years in a row.

Related to Web Development with Blazor

Related ebooks

Programming For You

View More

Reviews for Web Development with Blazor

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Web Development with Blazor - Jimmy Engström

    9781835465912.png

    Web Development with Blazor

    Third Edition

    A practical guide to building interactive UIs with C# 12 and .NET 8

    Jimmy Engström

    Web Development with Blazor

    Third Edition

    Copyright © 2024 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    Senior Publishing Product Manager: Suman Sen

    Acquisition Editor – Peer Reviews: Jane Dsouza

    Project Editor: Meenakshi Vijay

    Content Development Editor: Shazeen Iqbal

    Copy Editor: Safis Editing

    Technical Editor: Aneri Patel

    Proofreader: Safis Editing

    Indexer: Tejal Soni

    Presentation Designer: Rajesh Shirsath

    Developer Relations Marketing Executive: Priyadarshini Sharma

    First published: June 2021

    Second edition: March 2023

    Third Edition: April 2024

    Production reference: 2300824

    Published by Packt Publishing Ltd.

    Grosvenor House

    11 St Paul’s Square

    Birmingham

    B3 1RB, UK.

    ISBN 9781835465912

    www.packt.com

    Foreword

    Blazor is the .NET team’s effort to create the best modern framework we can for building rich web apps. Best could mean a few things, but besides the non-negotiables like being secure and reliable, one meaning we most strongly focus on is developer productivity. By empowering you to use all the tools and techniques of .NET, and through a streamlined and consistent architecture, Blazor aims to free you from incidental complexity, so you ship your web app faster and with more features your users want. This seems to be landing well with the community: even six years into the framework’s life, Blazor remains one of the fastest-growing parts of .NET.

    Of course, six years is a long time in software! Sometimes it surprises me how long we’ve been going and how far we’ve come. The web development industry has reinvented itself a few times during that period. And so Blazor has correspondingly pivoted several times, extending its reach and meeting new needs. Some of the biggest pivots so far have been:

    Initially, Blazor was designed as a framework solely for WebAssembly. However, in a strategic shift, it evolved into a multi-platform UI framework with the introduction of Blazor Server. Blazor Server was officially supported and released before the WebAssembly version, despite the latter being the original focus of development.

    Later, changing from being browser-only to running on native desktop and mobile apps with .NET MAUI. People don’t know this, but we actually used Blazor in an internal Microsoft desktop app prototype way earlier still, even before Blazor Server existed.

    Most recently in .NET 8, changing from being client-rendered (SPA-like) only to also supporting static server-side rendering (SSR).

    Despite the changing landscape, we’ve still always kept the same core component programming model, so Blazor app developers can bring forward their skills and code. Our hope is to keep doing so for many years to come, adapting to however the industry evolves.

    Blazor is a full, modern framework, so there’s potentially a lot to learn. That’s why I’m delighted you’re reading this book! With this third edition, Jimmy Engström has seamlessly merged everything new into his well-proven teaching structure that has been effective in getting readers going with Blazor. His thoughtful organization and brand-new samples and tutorials explain the range of options, along with the pros and cons of different ways to deliver a web app with .NET. It’s not oversimplified, either: as you’ll see when you read about innately subtle topics like authentication/authorization or state management, this book genuinely gets into the details you need to know.

    Jimmy has been a valued member of the Blazor community for years. I always enjoy catching up with him at the various conferences and community events we participate in around the world and online, and I know other Blazor team members feel the same. I’m confident in his ability to communicate not only how things work, but also why they work as they do, and what backstory has led us to this point. His enthusiasm and knowledge make him an ideal guide as you enter this world.

    Reader, I wish you the best of luck with your Blazor projects!

    Steve Sanderson,

    Developer/Architect at Microsoft and original creator of Blazor

    Contributors

    About the author

    Jimmy Engström has been developing ever since he was 7 years old and got his first computer. He loves to be on the cutting edge of technology, trying new things. When he got wind of Blazor, he immediately realized its potential and adopted it when it was in beta. He has been running Blazor in production since it was launched by Microsoft.

    His passion for the .NET industry and community has taken him around the world, speaking about development. Microsoft has recognized this passion by awarding him the Microsoft Most Valuable Professional award 10 years in a row.

    I dedicate this book to my mom and dad, who got me my first computer, which got me started with programming.

    To my brother, who took the time to teach me how to code, and to my sister, who helped me with my English homework growing up.

    I would also like to dedicate the book to my wife, Jessica, who has helped me along the way by both reviewing the book and picking up my slack. Love you! This book would never have been possible without you all! A huge thanks to the reviewers, who have done a tremendous job reviewing the book.

    – Jimmy Engström

    Jag dedikerar den här boken till min mamma och pappa som köpte min första dator, som fick mig att börja programmera. Till min bror som tog sig tiden att lära mig koda och till min syster som hjälpte mig med engelskaläxan när jag växte upp.

    Jag vill också dedikera boken till min fru som har hjälpt mig att se över boken och stöttat mig på alla tänkbara sätt. Älskar dig!

    Detta hade inte varit möjligt utan er alla.

    Ett stort tack till Stacy som sett över boken, du har gjort ett fantastiskt jobb.

    – Jimmy Engström

    About the reviewer

    Stacy Cashmore has been developing solutions since the mid-1990s in various companies and industries ranging from facilitating contract jobbing to allowing consumers to close a mortgage without the help of a financial adviser – with lots in between.

    She has a passion for sharing knowledge: using storytelling for sharing her experiences to help teams grow in the ways that they develop software and work together, and performing live coding demonstrations to inspire others to try new technologies.

    For her effort in the community, Stacy has been awarded the Microsoft MVP for Developer Technologies since 2020.

    I’d like to thank my family for putting up with the time I commit to the development community, and to Jessica Engstrom for convincing me that I had something to offer and to take up speaking and getting involved in the first place.

    Join our community on Discord

    Join our community’s Discord space for discussions with the author and other readers:

    https://packt.link/WebDevBlazor3e

    Contents

    Preface

    Who this book is for

    What this book covers

    To get the most out of this book

    Get in touch

    Hello Blazor

    Technical requirements

    Why Blazor?

    Preceding Blazor

    Introducing WebAssembly

    Introducing .NET 8

    Introducing Blazor

    Blazor Server

    Blazor WebAssembly

    Blazor WebAssembly versus Blazor Server

    Blazor Hybrid/.NET MAUI

    Server-Side Rendering (SSR)

    The feature formerly known as Blazor United

    Summary

    Further reading

    Creating Your First Blazor App

    Technical requirements

    Setting up your development environment

    Windows

    macOS and Linux (or Windows)

    Creating our first Blazor application

    Exploring the templates

    Blazor Web App

    Blazor WebAssembly Standalone App

    Creating a Blazor web application

    Using the command line

    Creating projects using the command line

    Figuring out the project structure

    Program.cs (BlazorWebApp project)

    Program.cs (BlazorWebApp.Client)

    App (BlazorWebApp)

    Routes

    MainLayout

    CSS

    Summary

    Managing State – Part 1

    Technical requirements

    Creating a data project

    Creating a new project

    Creating data classes

    Creating an interface

    Implementing the interface

    Adding the API to Blazor

    Summary

    Understanding Basic Blazor Components

    Technical requirements

    Exploring components

    Counter

    Weather

    Learning Razor syntax

    Razor code blocks

    Implicit Razor expressions

    Explicit Razor expressions

    Expression encoding

    Directives

    Adding an attribute

    Adding an interface

    Inheriting

    Generics

    Changing the layout

    Setting a namespace

    Setting a route

    Adding a using statement

    Understanding dependency injection

    Singleton

    Scoped

    Transient

    Injecting the service

    Changing the render mode

    Figuring out where to put the code

    In the Razor file

    In a partial class

    Inheriting a class

    Only code

    Lifecycle events

    OnInitialized and OnInitializedAsync

    OnParametersSet and OnParametersSetAsync

    OnAfterRender and OnAfterRenderAsync

    ShouldRender

    Parameters

    Cascading parameters

    Writing our first component

    Creating a components library

    Using our components library

    Creating our own component

    Summary

    Creating Advanced Blazor Components

    Technical requirements

    Exploring binding

    One-way binding

    Two-way binding

    Actions and EventCallback

    Using RenderFragment

    ChildContent

    Default value

    Building an alert component

    Exploring the new built-in components

    Setting the focus of the UI

    Influencing the HTML head

    Component virtualization

    Error boundaries

    Sections

    Summary

    Building Forms with Validation

    Technical requirements

    Exploring form elements

    EditForm

    InputBase<>

    InputCheckbox

    InputDate

    InputNumber

    InputSelect

    InputText

    InputTextArea

    InputRadio

    InputRadioGroup

    InputFile

    Adding validation

    ValidationMessage

    ValidationSummary

    Custom validation class attributes

    Looking at bindings

    Binding to HTML elements

    Binding to components

    Building an admin interface

    Listing and editing categories

    Listing and editing tags

    Listing and editing blog posts

    Adding an abstraction layer

    Locking the navigation

    Enhanced Form Navigation

    Summary

    Creating an API

    Technical requirements

    Creating the service

    Learning about Minimal APIs

    Adding the API controllers

    Adding APIs for handling blog posts

    Adding APIs for handling Categories

    Adding APIs for handling Tags

    Adding APIs for handling comments

    Creating the client

    Summary

    Authentication and Authorization

    Technical requirements

    Setting up authentication

    Configuring our Blazor app

    Securing our Blazor app

    Securing Blazor WebAssembly

    Adding roles

    Configuring Auth0 by adding roles

    Adding roles to Blazor

    Summary

    Sharing Code and Resources

    Technical requirements

    Adding static files

    Choosing between frameworks

    Adding a new style

    Adding CSS

    Making the admin interface more usable

    Making the menu more useful

    Making the blog look like a blog

    CSS isolation

    Summary

    JavaScript Interop

    Technical requirements

    Why do we need JavaScript?

    .NET to JavaScript

    Global JavaScript (the old way)

    JavaScript Isolation

    JavaScript to .NET

    Static .NET method call

    Instance method call

    Implementing an existing JavaScript library

    JavaScript interop in WebAssembly

    .NET to JavaScript

    JavaScript to .NET

    Summary

    Managing State – Part 2

    Technical requirements

    Storing data on the server side

    Storing data in the URL

    Route constraints

    Using a query string

    Implementing browser storage

    Creating an interface

    Implementing Blazor Server (InteractiveServer)

    Implementing WebAssembly (InteractiveWebAssembly)

    Implementing the shared code

    Using an in-memory state container service

    Implementing real-time updates on Blazor Server

    Implementing real-time updates on Blazor WebAssembly

    State management frameworks

    Root-level cascading values

    Summary

    Debugging the Code

    Technical requirements

    Making things break

    Debugging Blazor Server

    Debugging Blazor WebAssembly

    Debugging Blazor WebAssembly in the web browser

    Hot Reload

    Summary

    Testing

    Technical requirements

    What is bUnit?

    Setting up a test project

    Mocking the API

    Writing tests

    Authentication

    Testing JavaScript

    Blazm extension

    Summary

    Deploying to Production

    Technical requirements

    Continuous delivery options

    Hosting options

    Hosting Blazor Server/InteractiveServer

    Hosting InteractiveWebAssembly

    Hosting Blazor WebAssembly Standalone

    Hosting on IIS

    Summary

    Moving from, or Combining with, an Existing Site

    Technical requirements

    Introducing web components

    Exploring custom elements

    Exploring the Blazor component

    Adding Blazor to an Angular site

    Adding Blazor to a React site

    Adding Blazor to MVC/Razor Pages

    Adding web components to a Blazor site

    Migrating from Web Forms

    Summary

    Going Deeper into WebAssembly

    Technical requirements

    Exploring the WebAssembly template

    .NET WebAssembly build tools

    AOT compilation

    WebAssembly Single Instruction, Multiple Data (SIMD)

    Trimming

    Lazy loading

    Progressive web apps

    Native dependencies

    Common problems

    Progress indicators

    Prerendering on the server

    Preloading and persisting the state

    Summary

    Examining Source Generators

    Technical requirements

    What a source generator is

    How to get started with source generators

    Community projects

    InterfaceGenerator

    Blazorators

    C# source generators

    Roslyn SDK samples

    Microsoft Learn

    Summary

    Visiting .NET MAUI

    Technical requirements

    What is .NET MAUI?

    Creating a new project

    .NET MAUI App

    .NET MAUI Class Library

    .NET MAUI Blazor Hybrid App

    Looking at the template

    Developing for Android

    Running in an emulator

    Running on a physical device

    Developing for iOS

    Hot restart

    Simulator

    Developing for macOS

    Developing for Windows

    Developing for Tizen

    Summary

    Where to Go from Here

    Take-aways from running Blazor in production

    Solving memory problems

    Solving concurrency problems

    Solving errors

    Old browsers

    The next steps

    The community

    The components

    Summary

    Other Books You May Enjoy

    Index

    Landmarks

    Cover

    Index

    Preface

    Until now, creating interactive web pages meant using JavaScript. But with Blazor, a framework for creating .NET web applications, developers can easily build interactive and rich web applications using C#. This book will guide you through the most commonly encountered scenarios when starting your journey with Blazor.

    Firstly, you’ll discover how to leverage the power of Blazor and learn what you can do with server-side rendering (SSR), Blazor Server, Blazor WebAssembly, and Blazor Hybrid. This book will help you overcome some of the common obstacles that developers face by showing you how all of the elements work together practically. As you advance, you’ll learn how to create Blazor projects, how Razor syntax works, how to validate forms, and how to create your own components. The book then introduces you to the key concepts involved in web development with Blazor, which you can put into practice immediately.

    By the end of this Blazor book, you’ll have gained the confidence to create and deploy production-ready Blazor applications.

    Who this book is for

    The book is for web developers and software developers who want to explore Blazor to learn how to build dynamic web UIs. This book assumes familiarity with C# programming and web development concepts.

    What this book covers

    Chapter 1, Hello Blazor, will teach you the difference between Blazor server and Blazor WebAssembly and the new Static and Streaming SSR. You will get an overview of how the technology works and a brief history of where Blazor comes from. Knowing the structure and differences between the hosting models is essential for understanding the technology.

    Chapter 2, Creating Your First Blazor App, helps you understand how to install and set up your development environment. You will create your first Blazor app and learn about the structure of the project template.

    Chapter 3, Managing State – Part 1, teaches you how to create a repository to store your data (blog posts, categories, tags, and comments).

    Chapter 4, Understanding Basic Blazor Components, digs deeper into components, life cycle events, adding parameters, and sharing parameters between components. You will also create reusable components in this chapter.

    Chapter 5, Creating Advanced Blazor Components, digs even deeper into components, adding functionality such as child components, cascading parameters, and values, and covering how to use actions and callbacks.

    Chapter 6, Building Forms with Validation, looks at forms, how to validate forms, and how to build your own validation mechanism. This chapter will cover the most common use cases when handling forms, such as file upload, text, numbers, and triggering code when typing on the keyboard.

    Chapter 7, Creating an API, looks at creating an API using Minimal API. When using Blazor WebAssembly, we need an API to get data.

    Chapter 8, Authentication and Authorization, looks at adding authentication and authorization to Blazor and making sure navigation, such as redirecting to a login page, works as expected.

    Chapter 9, Sharing Code and Resources, teaches you how sharing code between projects. In this chapter, we continue building a shared library that can be packaged as a NuGet package and shared with others.

    Chapter 10, JavaScript Interop, explores how to leverage JavaScript libraries when using Blazor and make calls from C# to JavaScript. You will also examine how JavaScript can call C# functions in our Blazor app.

    Chapter 11, Managing State – Part 2, looks into the different ways of managing state (persisting data), such as using LocalStorage or just keeping data in memory using dependency injection. You will also implement real-time updates to your blog post using SignalR.

    Chapter 12, Debugging the Code, teaches you how to debug your applications and add extended logging to figure out what’s wrong with your application. You will not only look at traditional debugging but also at debugging C# code directly from within the web browser.

    Chapter 13, Testing, looks at automated testing so that you can make sure your components work as they should (and continue to do so). There is no built-in method to test Blazor applications, but there is an excellent community project called bUnit.

    Chapter 14, Deploying to Production, will take you through the different things you need to think about when running Blazor in production.

    Chapter 15, Moving from, or Combining with, an Existing Site, will show you how to integrate Blazor into an existing site and combine JavaScript frameworks like Angular or React with Blazor.

    Chapter 16, Going Deeper into WebAssembly, covers the specific things for Blazor WebAssembly.

    Chapter 17, Examining Source Generators, covers how Blazor relies heavily on source generators. In this chapter, you will learn how they work and relate to Blazor.

    Chapter 18, Visiting .NET MAUI, looks at the third hosting model, Blazor Hybrid. Using .NET MAUI, you can build iOS, Android, macOS, Tizen, and Windows applications by leveraging what you have learned in this book.

    Chapter 19, Where to Go from Here, is a short chapter with a call to action, some resources you can use, and a finale.

    To get the most out of this book

    I recommend reading the first few chapters to ensure you are up to speed with the basic concepts of Blazor in general. The project we are creating is adapted for real-world use but some parts are left out, such as proper error handing. You should, however, get a good grasp of the building blocks of Blazor.

    The book focuses on using Visual Studio 2022; that said, feel free to use whatever version you are comfortable with that supports Blazor.

    If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

    I would love for you to share your progress while reading this book or in Blazor development in general. Tweet me at

    @EngstromJimmy

    .

    I hope you have as much fun reading this book as I had writing it.

    Download the example code files

    The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Web-Development-with-Blazor-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Download the color images

    We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781835465912.

    Conventions used

    There are a number of text conventions used throughout this book.

    CodeInText

    : Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example; "

    EditForm

    will create an

    EditContext

    instance as a cascading value so that all the components you put inside of

    EditForm

    will access the same

    EditContext

    ."

    A block of code is set as follows:

    public

    void

    ConfigureServices

    (

    IServiceCollection services

    )

    { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton(); }

    Any command-line input or output is written as follows:

    dotnet new blazorserver -o BlazorServerSideApp cd Data

    Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: "Select Blazor Server App from the search results and press Next."

    Warnings or important notes appear like this.

    Tips and tricks appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: Email

    [email protected]

    , and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at

    [email protected]

    .

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit, http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

    Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at

    [email protected]

    with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

    Share your thoughts

    Once you’ve read Web Development with Blazor, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

    Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

    Download a free PDF copy of this book

    Thanks for purchasing this book!

    Do you like to read on the go but are unable to carry your print books everywhere?

    Is your eBook purchase not compatible with the device of your choice?

    Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

    Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

    The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.

    Follow these simple steps to get the benefits:

    Scan the QR code or visit the link below:

    https://packt.link/free-ebook/9781835465912

    Submit your proof of purchase.

    That’s it! We’ll send your free PDF and other benefits to your email directly.

    1

    Hello Blazor

    Thank you for picking up your copy of Web Development with Blazor. This book intends to get you started as quickly and smoothly as possible, chapter by chapter.

    This book will start by guiding you through the most common scenarios you’ll come across when you begin your journey with Blazor, and you will also dive into a few advanced scenarios later on. This book aims to show you what Blazor is – Blazor Server, Blazor WebAssembly, Blazor Hybrid, and on top of that, the new Server-Side Rendering (SSR) – and how it all works practically to help you avoid traps.

    This is the book’s third edition; much has happened since the first edition. .NET 6 and .NET 7 were released, and for the second edition, I updated the content to reflect the latest changes and functionalities at the time of writing.

    This edition has been updated to include all the new things in .NET 8, and there is a lot to uncover.

    I hold Blazor presentations all over the world, and there are common questions that I get asked a lot. Without going into too much detail, they are often related to download size or time when it comes to Blazor WebAssembly and continuous connection to Blazor Server. In .NET 8, we can leverage a new mode, SSR, that solves all of these problems in one swift blow. Okay, maybe not all problems, but we are well on our way to solving them. A common belief is that Blazor is WebAssembly, but WebAssembly is just one way of running Blazor. Many books, workshops, and blog posts on

    Enjoying the preview?
    Page 1 of 1