Building Blazor WebAssembly Applications with gRPC - Václav Pekárek - E-Book

Building Blazor WebAssembly Applications with gRPC E-Book

Václav Pekárek

0,0
22,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Building Blazor WebAssembly Applications with gRPC will take you to the next level in your web development career. After working through all the essentials of gRPC, Blazor, and source generators, you will be far from a beginner C# developer and would qualify as a developer with intermediate knowledge of the Blazor ecosystem.

After a quick primer on the basics of Blazor technology, REST, gRPC, and source generators, you’ll dive straight into building Blazor WASM applications. You’ll learn about everything from two-way bindings and Razor syntax to project setup. The practical emphasis continues throughout the book as you steam through creating data repositories, working with REST, and building and registering gRPC services. The chapters also cover how to manage source generators, C# and debugging best practices, and more. There is no shorter path than this book to solidify your gRPC-enabled web development knowledge.

By the end of this book, your knowledge of building Blazor applications with one of the most modern and powerful frameworks around will equip you with a highly sought-after skill set that you can leverage in the best way possible.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 214

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Building Blazor WebAssembly Applications with gRPC

Learn how to implement source generators and gRPC in your Blazor apps for better performance

Václav Pekárek

BIRMINGHAM—MUMBAI

Building Blazor WebAssembly Applications with gRPC

Copyright © 2022 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.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Jane D’Souza

Senior Editor: Divya Anne Selvaraj

Technical Editor: Joseph Aloocaran

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Rekha Nair

Production Designer: Roshan Kawale

Marketing Coordinator: Anamika Singh

First published: October 2022

Production reference: 1061022

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80461-055-8

www.packt.com

To my parents, Jaroslava and Antonín, for their sacrifices and for the education they gave me. To my wife, Sylvie, for pushing me further and believing in me.

- Václav Pekárek

Contributors

About the author

Václav Pekárek is an experienced developer with 10 years of web development experience using .NET and C#. He is also a Microsoft Certified Professional.

Václav is the owner of a small IT company in Ostrava, Czech Republic. You can contact him on his LinkedIn page, on Twitter at @vaclavpekarek, or via email at [email protected].

I want to thank my wife Sylvie for her support during the entire course of writing this book. I also want to thank Divya Anne Selvaraj for her ideas for improvements and for keeping the book on track, and Jane D’Souza for making this happen.

About the reviewer

Eduardo Padilla is a seasoned senior consultant and software architect/developer with more than 20 years of experience using Microsoft technologies. He has worked in different industries (health, finance, travel, legal, logistics, and telecommunications) for Fortune 500 companies.

Eduardo is very enthusiastic about emerging technologies and how to use them to improve existing solutions, which made him look into Blazor and the myriad of possibilities it opened. He became an early adopter, the same way as he did with the .NET implementation of gRPC.

Eduardo provides consulting services through his small company in Miami, FL. Feel free to contact him at [email protected] or through his LinkedIn page.

Table of Contents

Preface

1

Introducing Blazor, gRPC, and Source Generators

Technical requirements

Using the Blazor framework to create websites

Using Blazor WebAssembly for single-page applications

Harnessing advantages of progressive web applications using Blazor

Understanding how Blazor uses Razor syntax

Using JavaScript in Blazor

Understanding the REST API as the default Blazor communication interface

Understanding gRPC and how it is different from REST

How protocol buffers work

Why we still use REST

What are source generators and how do they work?

Summary

Further reading

2

Creating a Blazor WebAssembly Application

Technical requirements

Learning how to write Razor syntax

Writing implicit Razor expressions

Writing explicit Razor expressions

Writing inline expressions

Writing code block expressions

Writing control structures

Writing top-level directives

Writing inline directives

Creating Razor components

Using components in other components

Passing parameters to components

Creating components with child content

Communicating with the parent component

Understanding the component life cycle

Structuring component code

Understanding page routing in Blazor

Navigating between pages

Page directive

Route constraints

Catch-all parameters

Project overview and preparation

Creating a demo Blazor WebAssembly project

Examining the project

Preparing the demo project

Summary

3

Creating a Database Using Entity Framework Core

Technical requirements

Creating a data repository using EF

Installing NuGet packages

Enabling EF

Creating database representation in C#

Configuring EF Core

Migrating code to the database

Creating entities in the database

Using generic services for data manipulation

Creating models

Mappings between models

Creating data services

Creating a new record

Reading a single record

Reading all records

Updating records

Deleting records

Registering data services

Summary

Further reading

4

Connecting Client and Server with REST API

Technical requirements

Exposing CRUD operations in API controllers

Consuming a REST API in Blazor components

Creating and editing data

Viewing the data

Extending the demo project

Summary

5

Building gRPC Services

Technical requirements

What are the benefits of using gRPC services?

How does communication work in gRPC?

Understanding the protocol buffer language

Creating messages

Field types

Default values

The reserved keyword

Defining methods

gRPC services in C#

Two ways of implementing

Implementing gRPC services using .proto files

Creating Blazor components

Preparation for generic components

Creating generic list components

Creating generic form components

Summary

6

Diving Deep into Source Generators

Technical requirements

What can source generators generate?

What is a syntax tree?

What is a semantic model?

Implementing source generators

Using partial classes and methods

Partial classes

Partial methods

Creating attributes for your needs

Writing the first generator

Required packages

Limiting the generator

Generating the code

Referencing the generators

Exploring generated code

Summary

7

Best Practices for C# and gRPC

gRPC is not the new REST

Generated code can be harder to debug

Exploring generated code

Using a debugger

Emitting generated files

Testing the generator

Type less, generate more

Summary

Index

Other Books You May Enjoy

1

Introducing Blazor, gRPC, and Source Generators

Let us start our journey in this book by first getting to know our three main technological co-travelers: Blazor, gRPC, and source generators.

The Blazor framework is an open source web framework developed by Microsoft. It is a free-to-use, single-page application (SPA) framework that enables a smooth development process while writing both the server and client parts of the application in .NET and C#. It can be used for dynamic websites but can also generate static websites without the need for expensive website hosting.

On the other hand, Google Remote Procedure Call (gRPC) is a multi-environment open source Remote Procedure Call (RPC) framework. It uses HTTP/2 for connecting services between data centers, but also for connecting mobile applications and browsers to backend services. gRPC includes optional features for authentication, bidirectional streaming, health checks, and more, along with support for cross-platform client and server code generation for many languages.

RPC was first developed in the 1970s and implemented in the 1980s. In 2015, Google built gRPC on top of the existing RPC protocol and it became a new standard supported by many languages.

Last but not the least, we will be working with source generators, a new feature for C# developers, available from .NET Standard 2.0. This feature allows us to programmatically read and analyze our code before its compilation and extend or create new code that is included in the compilation process. We can think of source generators as templating mechanisms that can emit C# source code.

Before we move further, we also need to explain what WebAssembly (WASM) stands for. WASM is a binary-code format for portable executable programs. It enables creating high-performant programs running inside a web browser without a close connection to the browser itself. This means that WASM can also run in other environments. WASM is an open standard supported by many languages and operating systems.

The Blazor WebAssembly framework will act as the glue that binds together all the technologies we will be working with to build our application. In this book, we will get to know each of these technologies better and understand their purpose. We will also build a real, highly performant gRPC-powered Blazor WebAssembly application using all of these technologies.

By the end of this chapter, you will have learned about the Blazor WebAssembly framework and how it can extend your focus from backend development to frontend development, without the need for a different programming language. You will learn about the gRPC protocol and how you can use it instead of Representational State Transfer (REST) in server-to-server and browser-to-server communication. In the last part of the chapter, you will learn about techniques to avoid writing repetitive code using source generators.

In this chapter, we will cover the following topics:

Using the Blazor framework to create websitesUnderstanding the REST API as the default Blazor communication interfaceWhat is gRPC and how is it different from REST?What are source generators and how do they work?

Technical requirements

All projects in this book will use Windows 11. If you are using an older version of Windows, you can expect some differences.

All of the projects are built using Microsoft Visual Studio 2022 Community Edition version 17.1.1. If you need to install Visual Studio 2022, select Free Download under Community at https://visualstudio.microsoft.com/downloads/. Run the installer. When prompted, select the option for ASP.NET and web development.

Once the installation process completes, the welcome window of Visual Studio will open. You can click the Continue without code link on the right side of the window to open the Visual Studio IDE without any solution.

Tip

If you already have Visual Studio Professional or Enterprise edition, everything should work the same way. However, the newer version (or preview) of Visual Studio can handle some code actions differently. Rider from JetBrains can be used as well.

Our projects require .NET 6.0. If you have installed Visual Studio 2022, .NET 6.0 should be already installed. You can check the installed version by running the following command in Windows PowerShell:

dotnet --version

If the required version is not installed, download the installer from https://dotnet.microsoft.com/en-us/download/dotnet/6.0. After running the installer, you can open Windows PowerShell again and run the preceding command. The command should print the correct version of .NET installed on your computer.

Our project in this book will use SQL Server 2019 Developer Edition for the database. Microsoft provides a free version of SQL Server for developers. To install SQL Server Developer, open https://www.microsoft.com/en-us/sql-server/sql-server-downloads and download the Developer edition. Run the installer and when prompted, select Basic installation. Accept the Microsoft SQL Server License Terms. Click the Install button to let the installer complete the installation. You can customize the installation by clicking on Install SMSS. SQL Server Management Studio (SSMS) is a tool to manage SQL databases and is highly recommended to install.

Tip

Any edition of the SQL Server can be used to run this project. However, versions older than 2015 are not recommended.

In this book, we will use Blazor WebAssembly in .NET 6 for all projects.

You can find the complete source code for this book on GitHub at https://github.com/PacktPublishing/gRPC-Powered-Blazor-WebAssembly-Development.

All the code for this chapter can be found at https://github.com/PacktPublishing/gRPC-Powered-Blazor-WebAssembly-Development/tree/main/ch1.

Using the Blazor framework to create websites

The Blazor framework can be used in different hosting models. Blazor Server, WebAssembly, and Hybrid hosting models are supported, and each of them has different use cases and advantages and disadvantages.

The Server hosting model uses SignalR technology to send data from the client to the server. Then the server does the work and sends back the data required to update the UI of the application.

The WebAssembly hosting model has its client part of the application downloaded to the client with all the binaries needed to run the application. The WebAssembly application then does all the work on the client’s computer. This approach is faster but requires downloading larger files to the client. Since the end of 2017, all major browsers support WebAssembly, including mobile browsers. For old browsers, WebAssembly needs to be compiled to asm.js by JavaScript polyfill.

The Blazor Hybrid model can also be used to blend the desktop and native mobile frameworks. The components in the Hybrid model have access to mobile phone capabilities.

In this book, we will be using the Blazor WebAssembly hosting model. We are not focusing on mobile app development, so the Hybrid model is not useful for our purposes. Also, we want to create an application in which we don’t care as much about every millisecond of loading time, as we care about the speed of the application. And because WASM does its work inside the browser, all the re-rendering and UI updates are faster than in the server hosting model.

Using Blazor WebAssembly for single-page applications

Since Blazor is a dynamic framework; it can be used for an SPA. Blazor re-renders only the parts of the page that need to be changed, without the need to request all HTML for the page from the server and reload the page in the browser. This behavior creates a much better user experience on the website.

During the rendering process of the page, the browser creates the Document Object Model (DOM). The model is a render tree graph of each element used on the page. At the same time, Blazor creates its own virtual DOM. This virtual DOM holds more information than the DOM of the browser. There is a place for each element that can possibly be rendered on the page if the conditions change. When the user requests some change on the page, such as clicking on a link or submitting a form, Blazor re-renders the virtual DOM. These changes are then compared to the browser DOM. Only the difference is rendered to the client.

Re-rendering non-change elements costs CPU time and memory and slows down the overall process on the client (browser). However, comparing DOM models works much faster. Most modern SPA frameworks use their own kind of virtual DOM to prevent unnecessary updates in the browser.

Harnessing advantages of progressive web applications using Blazor

One of the other benefits of using Blazor for creating a website is native support for progressive web applications (PWAs). Such applications can be packed to run in the WebView on Windows and mobile phones (iOS and Android) and look like native apps. Many companies use PWAs as they are easier and cheaper to develop. PWAs can be used to build just one website that renders well across many devices.

Like everything, PWA has disadvantages. Missing the browser’s API to communicate with device hardware can lead to requiring a native application. iOS also prevents push notifications. This will, however, likely change in the future.

Understanding how Blazor uses Razor syntax

Razor syntax is a combination of HTML markup and C# code. Using both in one file helps to create a better and faster development process where you can render elements if the code meets some conditions, or easily render tables using for loops.

Razor syntax is not new in the .NET world. The syntax is used in Razor Pages and the model view controller (MVC). The main difference is that Blazor uses Razor syntax to create Razor components, while MVC and Razor Pages use it to render the whole page. You may find it easy to figure out the difference by looking at file extensions. Razor components use the .razor extension, while MVC uses .cshtml.

Razor components are the main building blocks for the Blazor application. Each component creates its own reusable user interface (UI) that can be used anywhere on the website. A single component can consist of one .razor file (such as MyComponent.razor), which can include both HTML markup and C# code with some logic. Optionally, the logic of the component can be extracted to a partial class with the same name as the Razor component. The convention is to name the file the same as the component with a .cs extension, such as MyComponent.razor.cs:

MyComponent.razor

<h1>Here is my @Title</h1>

MyComponent.razor.cs

@code {     [Parameter] public string Title { get; set; } }

Razor components can be also packed with custom Cascading Style Sheets (CSS) files to provide some specific component design. As the component author, you can create custom CSS for your component that will not interfere with the other components, but still allow the developer to modify styles with the global CSS. This ability is a huge advantage over MVC or other server-side frameworks. Another advantage is that the CSS included in the component is downloaded to the client only when the component is used. This advantage can lead to lowering the amount of data needed by the client.

Interesting fact

The name of the Blazor framework was created by combining the words Browser and Razor.

Now that we have some understanding of how Blazor can be used to create fast and responsive websites with reusable UI components written in Razor syntax, let us learn about how JavaScript can be used in Blazor web applications.

Using JavaScript in Blazor

Most modern web applications are using JavaScript frameworks, such as Vue.js, Angular, React, and others. Blazor is a framework in itself. However, this does not mean that we can’t use JavaScript API in our Blazor applications. On top of that, we can use JavaScript to call our C# code.

The process of these calls is called JavaScript interoperability (JS interop).

Calling JavaScript APIs

All JS interop calls are by default asynchronous. On Blazor Server, the JS interop calls are sent over the network. Regardless of the called code, the call is done asynchronously. However, there are synchronous JS interop calls for the Blazor WebAssembly hosting model.

Calling .NET from JavaScript

To allow calling the .NET method from JavaScript, the method must have a JSInvokable attribute. This attribute creates a binding between JavaScript calls and .NET. It allows us to specify a name for JavaScript calls, which is different from the original method name.

Calling the .NET method from JavaScript is then done by calling DotNet.invokeMethodAsync returning a JS Promise or DotNet.invokeMethod returning the result of the operation. The synchronous version (invokeMethod) does not support the Blazor Server hosting model.

With knowledge about interactions between the Blazor application and JavaScript APIs, you can create rich, dynamic websites that have access to all JavaScript features in the browser and can also benefit from the C# language and capability. Let us now learn a bit about the REST API, which is the default Blazor interface for communication between the browser (client) and the server part of the application before talking about gRPC. Understanding REST API will provide us with a better context to understand the workings and benefits of gRPC.

Understanding the REST API as the default Blazor communication interface

REST is an architecture for distributed systems. It is an easy way to read, edit, or delete data on the server using HTTP calls from