An Introduction to Blazor

As a full stack developer it is important to always keep your ears to the ground and keep up with the latest and greatest. One of the more interesting projects that has come out in the past couple of years has been WebAssembly. No, its not the fabled “JavaScript killer”, at least not right now. But its maturation could one day legitimately usher in a time when JavaScript is not the only language for the web and the web is simply a compile target.

Blazor is a project put together by Steve Sanderson (of Microsoft fame) that uses WebAssembly and Mono to build C# applications for the browser; without plugins of extensions. It simply compiles the .NET Core code you write to IL which is then targeted to WebAssembly (put very simply). This project is very much in its early stages and has not (as of this writing) received official backing from Microsoft outside of it being a “experiment”.

But Blazor represents an idea, one that I think we will see more of in the coming years, and developer seek to utilize WebAssembly to open the web up to new programming models. With that in mind, let’s talk about how to get started in Blazor:

The Setup

For Blazor to work you will need Visual Studio 15.7 (or later), .NET Core 2.1 GA (or later), and the Blazor Language Services Extension (here). Once all of these are installed you are free to create Blazor application using the standard ‘Create New ASP .NET Core Application’ template (there will be two Blazor related options in the subsequent dialog)

New Blazor app dialog

Blazor
This template is your typical SPA style application that can be deployed to any web site; I refer to this as the React/Angular SPA style application. In it you can make various web calls to APIs not your own and bring back data. This is the template that I currently favor

Blazor (ASP .NET Core hosted)
Similar to the OG Blazor template, this one includes a .NET Core Web API Backend that you can call into. One of the advantages of Blazor is you can truly share code between the backend and frontend without issue. At the time of this writing, however, this one had stopped working for whatever reason. This is the approach you would take if you want your SPA to work with an API that was yours; you would need to deploy the API to a separate location from the web content, as is the case with any SPA deployment.

For now, I suggest using the Blazor template. You can run this straight out of the gate. IOt has two nice examples of client side operations: Counter which uses C# to track click counts and FetchData which shows async init operations in action to load a local JSON file (the Hosted template actually retrieves this data from a web service).

Component Driven Design

The concept of a “component” in UI design is nothing new, I remember them from way back in the day with UserControls in ASP .NET, and now we have Angular and React embracing it as the way to go for SPA applications.

In Blazor, you create Razor files (.cshtml) in which  you embed both C# and HTML, these are components and they are surfaced as such. In this files index.html there are three components: ForecastDayList, LocationDisplayand CurrentWeather.

Selection_001

This is a very common approach with web content these days and it makes it easier to design and do things like CSS isolation and emphasize reusability. The cool thing here is these components are surfaced for us automatically by .NET without any using statements.

Routing

This is somewhat new since the first time I opened Blazor at the MVP Summit, they didnt have this though it was talked about how important it was as a feature.

Selection_004

Before we had to refresh the page entirely, and dont even get me started on adding parameters. Now you can just drop this line at the top and everything is handled for you (though you can replace it if you like). If you want to add parameters simple add it with the :pName syntax you will see in React and Angular, plus others.

The reason this works is because, again, Blazor adoptive of the Component design pattern. All these routes do is say “if you see this path, load this component” – we do the same thing in React in Angular.

Event Handling

Much like with traditional ASP .NET applications, C# code can be embedded in these Razor pages using the Razor syntax (the now famous @ prefix). It offers a clean and simple way to elegantly blending code with markup.

For HTML elements we can use shorthands that let us reference our C# code directly. The default template has a great example of this with Counter.

Selection_002

One thing I will point out is to be careful using reference variables, since they will be null to start in most cases. We can see the use of the onclick attribute which is a special keyword for Razor in this case and will point at our method, IncrementCount in this case. The page automatically refreshes as the value changes; newly released there are lifecycle methods that let you hook into this process: OnAfterRender (here).

This is the simplest example of handling interactivity on pages, we can do some more complex things like using Async to bring down data from a remote source.

Handling Async

One of the coolest features in the .NET world, and it has begun to find its away outside there (in ECMA7) is async/await, .NET’s syntactical sugar to make writing asynchronous operations easier. For the uninitiated, async/await is NOT parallel programming, it creates a sort of event loop in the background where code waits for an operation to complete and then resumes at that point. While other code may execute in the interim, parallel programming is doing things at once. With async/await the system is still utilizing a single thread.

The ability to bring this feature to SPA programming is, in a word, awesome.

Selection_005

This file can be found in full here on my GitHub – I tried to get as much of here as possible. There looks to be a lot going on but, we can take this as a very small slice and not worry too much about other things.

When you specify an Event Handler you can either choose to return void or Task (void for an method marked as async). This differs from traditional ASP .NET which had the old event handler signature that necessitated void be allowed as a return from an async method, something you dont ever want to do (but that is another story).

Our page defines a number of properties and uses the bind attribute to record the user entered value. When executed this will operate as any async method does. And as we saw with the Counter page, as the variables change the page will re-render. In this case populating the data for our other components.

You can view this application, deployed as HTML to S3, here.

Dependency Injection

Also in use here is the @inject handler which allows us to inject dependencies into our components. You define these in the Program.cs file of your main, its very similar to what we see with ASP .NET Core server apps. Based on the type you “label” for the dependency you can @inject that type.

As a side, I noticed while doing this that you will always to @inject HttpClient in some way as there appears to be a special version of sorts in use (or it has certain configurations). The out of the box on in System.Net does not seem to work. Just an FYI

This is awesome, I want to use it for my next app!!

I wouldnt. Blazor is still VERY experimental and missing some key features that make it unsuitable for a mission critical application; the lack of Microsoft officially recognizing it should be you wary. The key things are:

  1. Lack of debugging within Visual Studio. You are wholly reliant on Console.WriteLine for debug information as the Mono team has not yet added debugging hooks. I expect this will come soon though
  2. Application size. If you are familiar with Xamarin and Mono you know there is a vast difference between the assembly you create during development and the one you deploy to the AppStore, principally in size. Blazor is not yet supportive of the AOT compilation style that would enable it to get a binary size that is palatable as a download. That is the biggest reason, in my mind to avoid this in Production for right now

The main point here is to play with this and offer feedback to the team working on Blazor at Microsoft. They are very active in this project and many of the requests that I have made have been fulfilled. The team is well aware of the projects current shortcomings and is working to eventually make this a legitimate offering to the larger community.

What is the future?

It has been interesting the reaction to WebAssembly some of the hardcore web developers I know have had. Some see it as just another would be silver bullet ala Flash and Silverlight that will ultimately lose to JavaScript. That may be true but I dont recall Flash or Silverlight ever being a standardized thing that is quickly being adopted. If anything, the rise of WebAssembly could alter the landscape for web developers over the next few years to give us more options.

I think a lot of the negativity is born out of people who dont like JavaScript seeing WebAssembly and reaching for the “JavaScript is dead” hammer, Ive certainly seen quite a few articles going in that direction. My take: WebAssembly is an alternative. There are many things that JavaScript can do that are, well, awkward. For example, while I can create a 3D game in JavaScript, chances are C++ might be better for it. WebAssembly gives me the option to run my code natively in the browser. But would I want to use C++ to deliver a Line of Business application? Probably Not.

But that gets at the heart of the problem on the web. Right now, its only JavaScript. So regardless of what you want to do you really only have one language you can do it in. Thankfully that language has been shown flexible enough to carry us this far but, maybe with WebAssembly, web developers will finally get to a point where we can pick the best language for the job. Is it so bad that I could pick from Swift, Python, C#, or Java as my language and have it run natively in the browser? I dont see that as a problem, I see that as helping us move the web forward.

There is a chance that, one day, WebAssembly  could supplant JavaScript but that day is far off at best and, if you listen to the creators of WebAssembly talk, that has never been the goal of WebAssembly. Its always been about filling the gaps and giving developers more options to do things that might be awkward in JavaScript.

Regardless, that conversation goes off into direction that is not entirely related to Blazor but I think Blazor is the first of, I hope, many such tools that enable us to have more options when developing web applications.

6 thoughts on “An Introduction to Blazor

  1. Blazer is a technology which uses web assembly for running an application. It uses ASP.NET Core to build the application and has many similarities to the current UI Framework languages, like React or Angular.

    For a C# developer, it is a great platform to build an application, especially, a single page application. Although it is not available for the production system yet, an exciting time is ahead with this for sure.

    Like

Leave a comment