Understanding Web Assembly and Blazor

Suvendu Giri  Print 
22 Nov 2018
 
Beginner
185

Technologies we used to use for making web applications for various needs have been constantly changing at a frightening pace. As a developer, you might be worried about these constant changes as every time you have to almost start again. There is a significant amount of effort required to learn these changes or new technologies but what they in turn, give to the end users are just much more than the effort we spent learning. New technologies emerge with the need of the moment. For example, how online shopping has changed the way we do shopping, how we got rid of those frustrating installation for playing games as the high-end games are going online, making more secure banking or money transaction apps and there are many. All these are getting possible with the options these changing or emerging technologies are providing to us. In this post, we are going to understand how WebAssembly is going to be a game changer in the near future and how Blazor as a web framework stands as a competitor to the growingly popular JS frameworks.

WebAssembly

Before diving into the concept of WebAssembly, let’s recall the meaning of assembly. Assembly typically means code that is similar to machine understandable language and is human readable. Assembly codes are processor dependent so, for different processor architecture, there will be different assembly code. However, WebAssembly is a bit different than assembly as it is not meant for the processors rather is targeted for the web browsers. Once the code is available to the browser, it’s their responsibility to convert them to the code that machine can execute.

Now the big question here is why would we need WebAssembly? Recently, SaaS(Software as a service) applications have been increasingly in demand from both consumer and the business owner’s point of view. Service providers or the product owners want to reach maximum possible customers and they want customer’s hardware-software infrastructure not to be a barrier achieving so. On the other hand, customers now days are looking for the services which don’t ask them to install/purchase additional tools or applications. If you are a guy using computers for more than a decade, you must have remembered the process of installing a new software or game. It would ask you to install few small pieces of software and there was a high chance that you would end up knowing that few of such pieces would require a higher CPU architecture or later version of OS etc. If you now time travel again to the current era, you wouldn’t require such pieces anymore. Why is that? Isn’t it because you have started adding a pre/post-fix ‘Online’ to your search query in Google? Be it a loan calculator or be it an image editing tool, we want it to happen then and there, and we want it to happen within our web browsers. That’s what the application approaches have been heading to.

Now, let’s assume, we want to build video editing software in SaaS model. So, we want users having access to the internet and a web browser should be able to make use of the full functionality of our application. So, what technologies we are going to need? HTML, CSS and JavaScript apart from the other backend technologies, obviously. You would need lots of JavaScript code to make the user experience similar to an installed standalone application but the problem is JavaScript was not invented for these things. It wasn’t meant to be fast and when we are going to interact with lots of graphics, sound and other things, JavaScript struggles to give the desired output.

So, let’s welcome the newest probably member in the technology stacks named WebAssembly. “WebAssembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++ with a compilation target so that they can run on the web. It is also designed to run alongside JavaScript, allowing both to work together.” –MDN web docs So, churning out the above definition, we can say a few things about WebAssembly :

  • WebAssembly runs in browsers.

  • It is fast & efficient due to less download size.

  • Free to choose the language to code.

  • It runs in a sandboxed environment separate from the host runtime.

  • If you like to know more about WebAssembly, I would suggest visiting the official online documentation at https://webassembly.org/docs/high-level-goals/.

Browser Support

As engineers who crafted WebAssembly were mainly from Microsoft, Mozilla, Google, Apple, and few others, it was obvious that they provide respective browser support. It is going to be industry standard sooner or later. Almost all desktop browsers now support WebAssembly which includes all major web browsers such as Chrome, Edge, Firefox, Safari etc. Major mobile browsers such as Chrome for Android, Firefox for Android, Safari for iOS etc. also support WebAssembly. You can check the browser support details by visiting https://caniuse.com/#feat=wasm. Here is a snapshot was taken on 09/11/2018 for reference.

Note : The numbers on the boxes denote the version, green boxes represent “Supported” whereas the maroon ones represent “Not Supported”.

Limitations

While it sounds promising, WebAssembly has some limitations as well. But it’s relatively very new and it is expected to be loaded with much more functionalities and thus possibilities. Some of the limitations of WebAssembly are :

  • As WebAssembly code runs in an isolated environment, it has no direct access to the HTML DOM.

  • Amount of serialization required is huge because at the moment WebAssembly functions allow only numeric parameters.

  • Lack of garbage collector. However, as proposed the future versions may have some mechanism to use the garbage collector of the host.

Blazor

To use the power of WebAssembly when you are already in Microsoft or more precisely in C# ecosystem, Blazor is the experimental framework which uses C# as the language and runs completely in the web browser. Blazor is Browser + Razor. Although TypeScript had removed some of the pains that JavaScript had, it still needs to be transpiled (generate equivalent JavaScript in the background). However, Blazor has no such overheads and it’s powerful & faster like JavaScript and sometimes even faster. In addition, you can use the power of one of the most popular languages, C# and it runs completely in the browser so you can make some useful and most importantly usable applications.

Important Features

While the approach itself got a lot of appreciation from C# developers and buzz among the people of a varied domain, here are few of the important features which need to be highlighted.

  • Runs completely in the browser.

  • Runs in a memory safe sandboxed environment and nearly faster as native applications.

  • All the necessary SPA features are supported by Blazor such as routing, dependency injection, components etc.

  • Blazor applications can be deployed on machines having no .NET, just as static files.

  • All modern browsers support Blazor as they all support WebAssembly.

How Blazor works

Now that we understand what WebAssembly is and we know that Blazor with the help of WebAssembly brings C# to the browser, the question is how Blazor works and we would like to see a simple demo later to understand if we are ready to accept this experimental framework from Microsoft guys or not. Blazor runs on Mono, an open source version of .Net framework. Please check the official website for more details about Microsoft sponsored Mono - https://www.mono-project.com/. It runs via WebAssembly in 2 modes – interpreted and AOT modes. In the interpreted mode, Mono runtime gets compiled into WebAssembly which browser can then load and execute. Mono runtime will then load application dlls and execute. Whereas in ahead of time or AOT mode, the application gets compiled into WebAssembly at build time which can then be executed as normal WebAssembly.

If you are not familiar with Razor, I would suggest you checking razor documents at Microsoft site : https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor.

Demo

We’ll start with a very basic demo like HelloWorld application in this article and in the next article we’ll be seeing some more featured and few real-life examples.

Pre-requisites to get started

Like all other frameworks or development technologies, before you start development you need to get the framework or SDK and the right tools installed on your machine. As this is a basic example I don’t want you to install some heavy tools like Visual Studio and all.

  • A compatible browser – Chrome or Firefox may be.

  • .Net core 2.1 SDK (2.1.500 or later)

  • Visual Studio Code

  • Step by step example

  • Install .Net core from above link

  • Install Blazor templates using Command Prompt

  •  dotnet new -i Microsoft.AspNetCore.Blazor.Templates
    
  • Create a new application

  •  dotnet new blazor -o HelloWorldBlazor
    
  • Go to the application directory

  •  cd HelloWorldBlazor
    
  • Run the application

  •  dotnet run
    

Now open the browser and navigate to http://localhost:5000 or https://localhost:5001. You should be able to see the application something like the following :

Now your next task is to go to the menu and click on Counter. Click on the “Click Me” button. Noticed any page refresh?

No refresh as you are working with JavaScript or JQuery, right? However, if you navigate through the source code of Counter.cshtml or FetchData.cshtml, you’ll find there is no JavaScript but just html, razor and C# code. This is the beauty of Blazor.

Surfing the code

Open the application folder i.e. HelloWorldBlazor in Visual Studio Code. Let’s check the index.cshtml page. If you are already familiar with Razor then it will not look new to you.

 @page "/"
 <h1>Hello, world!
 Welcome to your new app.
 <SurveyPrompt Title="How is Blazor working for you?" />

The @page directive in the first line represents the routing and is mapped to the home root. Then the next 2 lines are just normal HTML markups. The last line may look something new to you. This is called a component in Blazor. This component is defined in Shared/SurveyPrompt.cshtml.

 <div class="alert alert-secondary mt-4" role="alert">
 <span class="oi oi-pencil mr-2" aria-hidden="true"></span> 
 <strong>@Title</strong>
 
 <span class="text-nowrap">
 Please take our
 <a target="_blank" class="font-weight-bold" href="https://go.microsoft.com/fwlink/?linkid=2041371">brief survey</a>
 </span>
 and tell us what you think.
 </div>
 
 @functions {
 [Parameter]
 string Title { get; set; } // Demonstrates how a parent component can supply parameters
 }

Note that the component name is the same as the component page name. The Blazor function at the end of the component makes it possible to pass a value from the parent, Index page in this case to the component with the help of [Parameter] annotation. That’s all in this article. Please explore through the other pages and in case there are any questions, feel free to add as comments.

Conclusion

So, with this basic article, we tried to understand how Blazor works using WebAssembly. We also had an overview of WebAssembly and how it is going to be the game changer. We also created a HelloWorld application using the default Blazor template and tried to understand how it works. There is a lot to explore and grab, which I will try to explain in the next few articles. Please share your feedback about this article. Thanks, happy learning!

Crack Your Technical Interview
 
Join Our Hands-on Training Programs
+