.NET Nakama

Let's talk about Blazor, baby!

April 04, 2021 (~13 Minute Read)
BLAZOR CLIENT-SIDE FRAMEWORK WEBASSEMBLY WASM SIGNALR

Introduction

There are a lot of .NET developers that have mostly worked in backend systems, in older and sometimes legacy web-frontend (such as WebForms, MVC, HTML + jQuery, etc.). There will be a time that we will need to create a web application (user interface - UI) for our API projects, and we will consider learning a client-side JavaScript framework, such as Angular, React, Vue.js, etc. These frameworks have their own similarities, differences, and learning curves. Believe me, there is a notable learning curve. So, the main questions that arise are the following:

  • Are we willing to invest in learning a client-side JavaScript framework?
  • Do we have the time to do it (from our company, wife and children 😛, etc.)?
  • Could we use our expertise in .NET?
  • At the end of the day, will we be productive?

Blazor is here exactly for those reasons, to build interactive client-side web UI with .NET C# instead of JavaScript (mind-blown!). So, as in Salt-N-Pepa’s song, in this article we will:

🎵 Let’s talk about Blazor, baby! Let’s talk about you and me, let’s talk about all the good things, and the bad things, that may be, let’s talk about Blazor 🎵

Blazor

Blazor is an open-source web framework for building interactive client-side web UI by using .NET. It is provided as a feature of ASP.NET that extends the .NET developer platform with tools and libraries.

It offers all the benefits of a modern front-end framework (e.g. components, binding, events, etc.) while working entirely in C#. Blazor applications are composed of reusable web UI components, which combine HTML, C#, JS and CSS. They can call APIs to request data or perform server-side operations. By now, you may have some questions, so let’s answer them directly:

  • Yes! We can keep running our C# code on the server (if needed).
  • Yes! We can run C# in the web browser 🎉. Allowing us to write both client and server-side code in C#, to share code and libraries (thanks to .NET Standard).
  • Yes! We can invoke JavaScript functions from .NET methods and vice versa (a.k.a. JavaScript interoperability or JS interop). So, we can still take advantage of the JavaScript libraries and frameworks that we are using 😉.
  • Yes! Blazor can be used for migrating existing web forms application to .NET Core or the latest .NET. In that case, you can review this free e-book to see whether it makes sense to migrate your project.

In the following section, we will see the two hosting models (editions) that are supported by Blazor in detail, their pros and cons and a list of learning resources. A short sneak peek:

Blazor Server Blazor WebAssembly
The client-side code is executed on the server. We can imagine that the project is divided into two parts: the thin-client (front) and the server. The thin-client send requests (automatically and optimized) to the server for any UI event using SinglarR. This hosting model requires an HTTP-server that runs .NET. The whole client-side code (including the C#) is executed in the browser using WebAssembly. This hosting model would only need an HTTP-server to serve static-files.
Blazor Server Blazor WebAssembly

Blazor Server (Hosting Model)

The Blazor Server hosting model was released as a part of .NET Core 3 (in October 2019). In Blazor Server, the component rendering logic is decoupled from how the UI updates are applied. Meaning that the client’s web browser will download only a small page (thin client) and any UI events and UI updates will be handled from the server over a SignalR connection (Figure 1). Thus, the bulk of the processing load will be happening on the server. The requests of the thin-client to the server are optimized (to be small and fast) and are handled by Blazor. As we can see from Figure 1, the server contains the .NET runtime and our Razor Components, and the DOM (in the web browser) is updated by using SignalR.

ASP.NET Core SignalR is an open-source library that simplifies the real-time web functionality of applications. Real-time web functionality enables server-side code to push content to the clients instantly (e.g. send asynchronous notifications). Traditionally, a web page retrieves new data any time the user performs a refresh or when the page performs Ajax (simple or long) polling to retrieve new data.

As we can understand, Blazor Server applications are hosted on an ASP.NET Core server (in ASP.NET Razor format). If you are thinking about the reasons to select this hosting model, consider that executing code on the server has the flexibility to do anything you would normally do on the server, such as connecting directly to a database, communicating will local or internal-network services, etc.

The Blazor Server hosting model.
Figure 1. - The Blazor Server hosting model (Source).

Blazor WebAssembly (Hosting Model)

Blazor WebAssembly was introduced (in May 2020) as another option for Blazor applications, allowing us to build Single-Page Applications (SPA) using .NET (C#), which run in the browser using WebAssembly. Running C# in the web browser allows us to write both client and server-side code in C#, to share code and libraries. Also, it’s important to notice that Blazor WebAssembly applications can be hosted everywhere (even in GitHub pages) because it’s a static SPA. But… how is that possible?

All this can be feasible with WebAssembly (Wasm), a binary instruction format optimized (as a stack-based virtual machine) for fast download and execution at native speed. It is designed as a portable compilation target for programming languages (i.e. compile to wasm), enabling deployment on the web for client and server applications. Wasm is an open web standard and it’s supported in all major web browsers (including mobile browsers) without using plugins.

Wasm cannot interact with DOM directly, but it sends messages to a JavaScript handler (…Blazor will take care of that 😉). The .NET code is executed via Wasm in the browser’s JavaScript sandbox, with all the protections that the sandbox provides against malicious actions on the client’s machine. Meaning that it enforces the same-origin and all permissions security policies of the browser. For those reasons, we can say that Wasm is secure and even more secure than JavaScript.

As we can see from Figure 2, our C# code files and Razor files are compiled into .NET assemblies, which are downloaded to the browser, including the .NET runtime (which can be cached). Blazor bootstraps the .NET runtime and configures it to load our application assemblies. The Blazor client-side runtime uses JavaScript interop to handle DOM manipulation and browser API calls.

SPAs are downloaded to the client’s web browser before running. So, the size of a SPA is important, thus we should consider the needs that lead us to use a SPA. Commonly, the SPA development style is selected for applications that will expose a rich user interface with many features and when the team is familiarized with a client-side framework.

Using Blazor WebAssembly we (as .NET developers) can start building projects quicker (in comparison to other client-frameworks) because we are familiar with the ecosystem, the language, the libraries, etc. without the need for significant JavaScript development. But, we have to keep in mind that Blazor WebAssembly is a new framework, which will lead to updates and changes.

The Blazor WebAssembly hosting model.
Figure 2. - The Blazor WebAssembly hosting model (Source).

Progressive Web Applications

Blazor WebAssembly can be created as a Progressive Web Application (PWA). A PWA is usually a SPA that allows the users to “install” it on their device (Desktop or Mobile) and use it in the same way as any other installed application. The user can still use the PWA on their browser without installing it (as a SPA). An installed PWA will still executed in a browser’s tab but in its own window without any menu and address bars. Also, it will provide the following capabilities:

  • Launched from a shortcut in the operating system (in the start menu, dock, or home screen).
  • Work offline (independent of network speed).
  • Receive push notifications from a backend server (even while the user isn’t using the app).
  • Automatically update in the background.

PWA installation is supported by Google Chrome, Apple Safari, Firefox for Android, and Microsoft Edge but not Firefox for desktop.

To create a Blazor WebAssembly PWA, select on the Create a New Project dialogue the Progressive Web Application check box. The offline support is achieved in Blazor WebAssembly by using a service worker, which acts like a proxy server between the web application, the browser, and the network (when available).

Pros and Cons Review

Let’s talk about all the good things (pros) and the bad things (cons) about Blazor and its hosting models.

The Good Things about Blazor

  • It uses .NET and C#.
    • Start building a project quicker (in comparison to other client-frameworks) because we know the ecosystem, the language, the libraries, etc.
    • No need to learn a separate language or technology.
  • It is supported without the need for plugins.
  • Very little JavaScript required.
  • Dependency Injection.
  • Live reloading in the browser during development.
  • JavaScript Interoperability (if needed): We can continue using the large ecosystem of JavaScript libraries that exist for client-side UI while we can write our logic in C#.
  • Uses .NET standard library.
    • Share code and libraries: Blazor applications can use existing .NET Standard libraries that allow us to use them both on the server and in the browser. For example, the same validation code and DTOs can be applied to the client and on the server.
    • Share Components that combining, Markup, C#, JS, and CSS as razor component libraries which can be shared via NuGet, assembly, etc.
  • Tools: Use the tools that you know (Visual Studio, VS Code, Rider, etc.).
  • Community: There is a continuously growing community and adoption of Blazor. Check some of the learning resources on the following section.
  • Documentation: A very important aspect for developers. Microsoft provides rich and updated documentation for Blazor (and for all of their products) with many examples, guidelines, best practices, etc.
  • Blazor WebAssembly:
    • Supports making a Single Page Application (SPA).
    • Can be hosted everywhere (even in GitHub pages) as static files.
    • Running .NET code directly in the browser.
    • An API layer is required. It promotes the Separation of Concerns (SoC) design principle and uses the advantages of APIs.
    • Can work offline (PWA).
  • Blazor Server:
    • The size of the client-side components is very small.
    • Works with thin clients.

The Bad Things about Blazor

  • It is a new framework. So, it will take some time to gain adoption and it may lead to updates and code changes.
  • Blazor WebAssembly:
    • Requires the whole runtime to be shipped before loading the page.
    • Large initial download size (.NET assemblies and runtime).
      • It is better suited to some web applications than others.
      • Probably wouldn’t be used for pages, such as home page, landing pages, etc. where there’s no business logic and it’s very important to be loaded as quickly as possible (for users and SEO).
    • Limited debugging capability and .NET tooling. Check this link for news regarding debugging capabilities.
    • Doesn’t work with thin clients. In cases where a non-standard browser is used (that doesn’t support WebAssembly).
    • PWA installation is not supported in Firefox for desktop.
    • An API layer is required. For some cases, an extra server could be required.
    • Developers should be very cautious regarding their sensitive code because it will be sent to the client.
  • Blazor Server:
    • A server that supports .NET is required.
    • Reduced and Complicated Scalability because the server-side uses SignalR.
      • SignalR has a limit to the number of simultaneous connections that can be handled.
      • Sticky sessions must be used.

Learn Recourses

The following resources will help you get started with Blazor. Even that we are keeping our .NET expertise, we will still have to learn about Blazor.

Description Link
Get Started with Blazor https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor
Blazor Documentation https://docs.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-5.0
Start learning from the creator of Blazor. Steve Sanderson’s videos about Blazor in .NET 5, future features, etc. https://channel9.msdn.com/Events/Speakers/steve-sanderson
Carl Franklin’s video classes about Blazor. You will dive into Blazor in no time from introductions to advanced concepts. https://blazortrain.com/
Awesome-Blazor is a GitHub repo with everything you will need about Blazor (tutorials, sample projects, and many, many more). https://github.com/AdrienTorris/awesome-blazor
More video resources about Blazor from Channel9. https://channel9.msdn.com/Search?term=blazor&sortBy=recent&lang-en=true
Learn how to create Blazor Games, such as Tic Tac Toe, Minesweeper, Blackjack, etc. http://blazorgames.net/
Several Blazor demos projects (with source code). https://lupblazordemos.z13.web.core.windows.net/

Summary

Blazor is very exciting news for .NET developers. It opens the road for building client-side web applications by using .NET and C#. We can take advantage of our existing expertise and knowledge, without learning a client-side JavaScript framework, such as Angular, React, Vue.js, etc. At the end of the day, we will be more productive with a smaller learning curve!

A Blazor application can be created either as a Blazor Server or as a Blazor WebAssembly. Their main difference is where the .NET code is executed, on the server or in the browser, respectively. Resulting, in different needs on a hosting server, which is why they are also referred to as hosting models.

Running .NET code in the browser is achieved by using the WebAssembly (Wasm) binary instruction format (to compile our project). Wasm is an open web standard and it’s supported in all major web browsers (including mobile browsers) without plugins. It’s secure and theoretically faster than JavaScript (because it’s compiled).

We have seen the pros and cons of Blazor and its hosting models, so you can decide if Blazor can be a good choice for your projects and team, and which hosting model you would use depending on each project’s needs.

If you are excited about Blazor, you could start with the proposed learning resources. They were a big help to me. Blazor baby!

If you liked this article (or not), do not hesitate to leave comments, questions, suggestions, complaints, or just say Hi in the section below. Don't be a stranger 😉!

Dont't forget to follow my feed and be a .NET Nakama. Have a nice day 😁.