Home .NET BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment

BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment

by admin

Hi Everyone, If you’ve heard of Blazor but still don’t understand what it is.You’re at the right place.This is the first article in a series of 12 articles that will take you through ♪ all the circles of hell ♪ the whole process of creating an application on Blazor At the end we will have a finished website of a small pizzeria, quite on the level of finished websites of some pizzerias. So you will have something to be proud of 😉
This is going to be a bit of a non-typical HelloWorld I deliberately went for some complications that are better to take as rules right away, in particular this typical three-layer architecture : View-Domain-DataAccess
I think it’s better to follow it right away than to show something artificial that has no relation to life. As practice shows, many developers, get stuck at the HelloWorld level and then use what they see when designing a priori large applications (hello to my ex-GreenestBankCountry and its Service.cs with all the application code in one file, no kidding).
I’ll tell you how to map data between layers without pain and without having to write many lines of code. We’re also going to get the whole thing into AzureDevOps. Yes, it’s a necessary part of any development process nowadays, we’re all flying around in the cloud today, some in on-premises , someone in Azure or AWS
Also, so that the first article is not a trivial story about how to press one button in Visual Studio, and then another, I thought it would be a good idea to do a little challange and try to do something for the first time on Linux
I expect that you have a minimal knowledge of ASP.NET, C#. Although this is HelloWorld, I won’t tell you what Program.cs is.
Next, let’s discuss what else is needed for programming under Linux
Attention: The next couple of paragraphs express my impression from actually working with Linux, having installed it in the most well-intentioned way, if Linux makes you ecstatic and you can’t live a day without opening the command line, then you can spoil your mood by continuing reading this article!

Distribution :Ubuntu

You can’t really get comfortable programming on Linux, but if you want to concentrate on the task at hand, put Ubuntu19.10 I managed to put it on the second time, good thing at least the second time. And all commands ran the first time, almost all of them. I would strongly advise against installing any other distributions, I spent a whole day to setup the last one. OpenSuse and then just tore it down.
Why would it even be necessary to develop under Linux ?If only because NetCore supports it and maybe your employer will decide to save money and run everything on proda in Linux. And in my opinion it’s better to write under the OS which you actually will run your application.

IDEWinner : Rider

As I said, comfortable under Linux writing will not work anyway, so we’ll choose the lesser of all evils, Rider.
In addition to her, there are also two other popular toli IDE or text editors MonoDevelop and Visual Studio Code I will tell you about the disadvantages of each solution in more detail.

MonoDevelop

The prettiest of the three editors. Readable fonts (low-quality fonts are the first thing you will notice when you move to Linux). But unfortunately there is nothing behind the nice shell, despite the installed Net Core2.1 and 3.1 , MonoDevelop I was persistently creating ConsoleApplication with the Target .Net Core 1.1. Blazorproject was not able to create or run a manually created project that had already been created.

Visual Studio Code

Strictly speaking, this is not IDE It’s a text editor with syntax highlighting and build options. On the plus side, on the 3rd or 4th try, VSCode miraculously ran the project I created WebAssembly when MonoDevelop and Rider refused to do it. This is a plus. I’ll go on with the cons: the default font is unreadable and small, I think after a few months of regular use, your eyes will go crazy.
The next disadvantage comes from the fact that it is a text editor, a simple action like renaming, moving projects? Everything that Visual Studio does automatically and we take for granted is done manually here.

Rider

This is much better than the comrades above, Ridereven picked up where I left off template for Blazor WebAssembly And even created an application, but this IDE refused to run it for some reason. I must say for the sake of fairness, Blazor Server, built and ran without any problems.
Also Rider allows you to add a git repository when you create a project. But in doing so. gitignore was empty for some reason.
So again, manual intervention is required, and Rider, just in case, let me remind you, competes with VS and JetBrains takes money for their product. And as usual the problem, in general on linux in principle, is bad fonts, they are some very thin, badly readable. The elements are also all small and you still have to aim at them. Also several times, in two days of work, Rider hung the system when loading a simple solution. I had to reset the computer, which is not good (update: by the time I finished this article it had already happened 5 times).
Winner in the category Best C# IDE Under Linux :
Rider – in spite of all the shortcomings, I managed to get this IDE built and ran the project steadily, again, the browser for some reason did not run by default, this must be done manually.
Below in the screenshot, Rider(note the fonts), and trying to run Blazor WebAssembly project he created himself, with MonoDevelop similar situation.
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment

If it’s so bad, why use Linux ?

Let me remind you that this is a learning project, the goal was to show that you can still work with Linux.
In addition, the imperfections of the development tools under Linux pushes us to a lot of manual activities that will allow us to learn a bit more about how the Net under the hood and understand how much work the same Visual Studio does for us.

What do we want to get?

At the end we get a nice-looking application, like the example below :
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
Now let’s get down to business. Let’s start by installing .Net Core 3.1

Installing .Net Core 3.1

Net Core 3.1.1 SDK latest version available at the moment SDK available in the repository Ubuntu Blazor changes very quickly so to work with Blazor WebAssembly use exactly 3.1.1, the latest stable version.
First we need to register the Microsoft key and their repository, this is done with the following commands in the application Terminal (click on Win and type Term and it should appear in the list of available ones):
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment

  1. wget -q https://packages.microsoft.com/config/ubuntu/19.10/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
  2. sudo dpkg -i packages-microsoft-prod.deb

Now let’s go straight to installing the .Net Core SDK:

  1. sudo apt-get update
  2. sudo apt-get install apt-transport-https
  3. sudo apt-get update
  4. sudo apt-get install dotnet-sdk-3.1

Installing the Blazor WebAssembly template

With installation Net Core are done, now we need to install Blazor WebAssembly Template which let me remind you is still at the stage of Preview from which it will go straight to release in May. Literally the day before I started writing this article the updated version 3.2.0-preview1.20073.1(h) was released on January 28th

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.2.0-preview1.20073.1

Installing Git

If you still do not have Git then it’s a good time to do it. Strictly speaking, you don’t have to do the first command at all, Ubuntu will ask you for a password, if the command requires an elevation of privileges, we will anticipate it=)

  1. sudo su
  2. add-apt-repository ppa:git-core/ppa
  3. apt update; apt install git

That’s not all, when executed in the browser Blazor uses Mono , which means we need to install it as well.

MonoInstallation

The first thing to do is to add the repositories Mono into the system :

  1. sudo apt install gnupg ca-certificates
  2. sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
  3. echo "deb https://download.mono-project.com/repo/ubuntu stable-bionic main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list
  4. sudo apt update

Now let’s install directly the Mono :

sudo apt install mono-complete

This is a slow process that took about 10 minutes on my laptop with a Core-i5 6200U processor, because the compilation of the sources is done directly on your computer.
Congratulations! We have installed everything you need to develop Blazor WebAssembly projects.
Now we can move on to the project itself.
But before that, let’s take a little break from typing commands and refresh our memory on what is BlazorWebAssembly.

BlazorWebAssemblyand what to do with it

Blazor it’s web framework designed to run either on the client side in a browser via WebAssembly technology(using Netruntime more precisely Mono implementation, which lately, thanks to the discovery of .Net source code is almost indistinguishable from the original platform), or on the server side with hosting in the Asp.Net Core application and exchanging data via SignalR technology(by creating Circuits connections).
As you can see from the description above Blazor!= .Net WebAssembly implementation.
If you take out of this bundle WebAssembly , you can develop a BlazorServer application and it will work even in the IE11 , who has never heard anything about modern technology and thank goodness won’t hear any more.
Since we are making an application based on the approach of Blazor WebAssembly So we’ll take a closer look at it.

  1. At the beginning the static page index.html is loaded in it has a non-standard tag app which is a placeholder for the future application. As well as the blazor.webassembly.js script, which initiates the loading of all the assemblies and initialization of the application. The assemblies are downloaded by themselves. Blazor application, its dependencies (e.g. AutoMapper, AutoFac) and the Mono runtime.
    Developers from the team Blazor are constantly working on optimizing the process of downloading the builds, thus shortening the time which passes between entering the address and opening the page.
    Back in the previous version Blazor ( 3.1.0-preview4.19579.2 which was released two months ago), the linker used to clean up unused code only from the .Net libraries, and now it also cleans up the code of the Blazor libraries, which has also slightly reduced the time it takes to download the application to the user’s computer.
    Blazor application is a set of static files, which means that it is equally suitable for designing large applications and static sites that will run entirely on the client side, without interacting with the server.
  2. Perhaps the main disadvantage of this approach is that it’s hard to debug, you can’t set breakpoints, you just can’t hit them, although I think this is temporary, you could connect to IE and debug JS code.
    And perhaps the second obvious disadvantage is the need to download all the sources, again, I think there is still a lot of room for optimization.
  3. Actually, after downloading and all the preparatory processes, our application runs in UI browser thread and starts its execution. You can call any JS code from C#and vice versa.

There haven’t been pictures here in a while, so here’s one for you below 🙂
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment

Dotnet utility

From here we will actively use the utility from the .Net Core SDK – dotnet.
It allows you to do many useful things, we are only interested in a few :

dotnet build

The command above, builds the solus, if run from the folder with the solus, no arguments are required.

dotnet new blazorwasm-ho-o BlazingPizza

Allows you to create a new project based on a template which comes after the word new, in our case it is blazorwasm Here, for example, you could specify classlib or console
Next are the template-specific parameters, in this case they are -ho , this parameter tells us that our application will be hosted on the ASP.NET Core application, also Net will create Controllers for us, which we can then use to create web api and access it not only from the Blazor app but also from other clients.
The last parameter -o specifies the folder in which the created solution will be placed, by default this is the current directory.

dotnet run

Another command, which comes in handy as the name implies, starts our application.

Project creation

So, let’s run the familiar command to generate our solushen. Choose a place you know, like the folder RiderProjects, which you created RiderIDE and is located at /home/{userName}:

dotnet new blazorwasm -ho -o BlazingPizza

After creating the project, let’s shoot it down and finally run it to enjoy some results (the first command is done at file level of BlazingPizza.sln):

dotnet build

Everything should have gone without problems, let’s go to the Server folder and run :

dotnet run

And finally we see the coveted result :
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
Great, everything works. Now let’s forget about the appearance of the site for a while and switch to the content.
The result of the first command (dotnet new) is the following folder structure :
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
I don’t think this is the best scheme, it would be better if the folders were prefixed with the name of the solution, it’s more convenient (VisaulStudio does it that way when creating new projects) and it would let you know it is not some additional service folder. Over time, the project can get a lot of folders that do not contain C# code, and if you go into the Explorer , it will be hard to know where everything is, and there may be some deployment scripts are laid down that in every folder whose name begins with the name of the solution, there is a project, this is normal, because this is a perennial behavior Visual Studio and you can rely on it.
So let’s rename the existing projects and the folders that contain them (so far we know nothing about IDE , we are in Linux and it won’t help the first time, because folders and projects have different names):
Client => BlazingPizza.Client
Server => BlazingPizza.Server
Shared => BlazingPizza.Shared

Corresponding changes should be shown in the solus file BlazingPizza.sln Where the path to the project is specified "[Server]~" and below replace with "BlazingPizza.[Server]~" as in the screenshot below :
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
Let’s make similar changes in the file BlazingPizza.Server.csproj:
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
And finally BlazingPizza.Client.csproj should also look like the screenshot below :
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
Enough with the changes for now, we have accumulated enough stuff that it would be a shame to lose, so let’s connect the version control system to our soluto. To do this, let’s finally open our IDE Rider and the solus, here it’s the same as in Visual Studio, you can open it by selecting the solus file.
Once everything is loaded, we go to menu VCS => Enable Version Control Integration And here we connect Git Rider will add service files to the folder with the solution and will highlight all files in red, it means that these files are not fixed in the version control system.
First time Rider Will offer to commit everything in the project, including the contents of the folders bin and obj , we don’t need it of course, all because the file gitignore which is added by default is empty. Move it to the root at the same level as the file BlazingPizza.sln and replace its content with the content from under the cat.
Contents of the .gitignore file

# Default ignored files/workspace.xml## Ignore Visual Studio temporary files, build results, and## files generated by popular Visual Studio add-ons.#### Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore# User-specific files*.suo*.user*.userosscache*.sln.docstates# User-specific files (MonoDevelop/Xamarin Studio)*.userprefs# Build results[Dd]ebug/[Dd]ebugPublic/[Rr]elease/[Rr]eleases/x64/x86/bld/[Bb]in/[Oo]bj/[Ll]og/# Visual Studio 2015/2017 cache/options directory.vs/# Uncomment if you have tasks that create the project's static files in wwwroot#wwwroot/# Visual Studio 2017 auto generated filesGenerated Files/# MSTest test Results[Tt]est[Rr]esult*/[Bb]uild[Ll]og.*# NUNIT*.VisualState.xmlTestResult.xml# Build Results of an ATL Project[Dd]ebugPS/[Rr]eleasePS/dlldata.c# Benchmark ResultsBenchmarkDotNet.Artifacts/# .NET Coreproject.lock.jsonproject.fragment.lock.jsonartifacts/**/Properties/launchSettings.json# StyleCopStyleCopReport.xml# Files built by Visual Studio*_i.c*_p.c*_i.h*.ilk*.meta*.obj*.iobj*.pch*.pdb*.ipdb*.pgc*.pgd*.rsp*.sbr*.tlb*.tli*.tlh*.tmp*.tmp_proj*.log*.vspscc*.vssscc.builds*.pidb*.svclog*.scc# Chutzpah Test files_Chutzpah*# Visual C++ cache filesipch/*.aps*.ncb*.opendb*.opensdf*.sdf*.cachefile*.VC.db*.VC.VC.opendb# Visual Studio profiler*.psess*.vsp*.vspx*.sap# Visual Studio Trace Files*.e2e# TFS 2012 Local Workspace$tf/# Guidance Automation Toolkit*.gpState# ReSharper is a .NET coding add-in_ReSharper*/*.[Rr]e[Ss]harper*.DotSettings.user# JustCode is a .NET coding add-in.JustCode# TeamCity is a build add-in_TeamCity*# DotCover is a Code Coverage Tool*.dotCover# AxoCover is a Code Coverage Tool.axoCover/*!.axoCover/settings.json# Visual Studio code coverage results*.coverage*.coveragexml# NCrunch_NCrunch_*.*crunch*.local.xmlnCrunchTemp_*# MightyMoose*.mm.*AutoTest.Net/# Web workbench (sass).sass-cache/# Installshield output folder[Ee]xpress/# DocProject is a documentation generator add-inDocProject/buildhelp/DocProject/Help/*.HxTDocProject/Help/*.HxCDocProject/Help/*.hhcDocProject/Help/*.hhkDocProject/Help/*.hhpDocProject/Help/Html2DocProject/Help/html# Click-Once directorypublish/# Publish Web Output*.[Pp]ublish.xml*.azurePubxml# Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted*.pubxml*.publishproj# Microsoft Azure Web App publish settings. Comment the next line if you want to# checkin your Azure Web App publish settings, but sensitive information contained# in these scripts will be unencryptedPublishScripts/# NuGet Packages*.nupkg# The packages folder can be ignored because of Package Restore**/[Pp]ackages/*# except build/, which is used as an MSBuild target.!**/[Pp]ackages/build/# Uncomment if necessary however generally it will be regenerated when needed#!**/[Pp]ackages/repositories.config# NuGet v3's project.json files produces more ignorable files*.nuget.props*.nuget.targets# Microsoft Azure Build Outputcsx/*.build.csdef# Microsoft Azure Emulatorecf/rcf/# Windows Store app package directories and filesAppPackages/BundleArtifacts/Package.StoreAssociation.xml_pkginfo.txt*.appx# Visual Studio cache files# files ending in .cache can be ignored*.[Cc]ache# but keep track of directories ending in .cache!*.[Cc]ache/# OthersClientBin/~$**~*.dbmdl*.dbproj.schemaview*.jfm*.pfx*.publishsettingsorleans.codegen.cs# Including strong name files can present a security risk# (https://github.com/github/gitignore/pull/2483#issue-259490424)#*.snk# Since there are multiple workflows, uncomment next line to ignore bower_components# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)#bower_components/# RIA/Silverlight projectsGenerated_Code/# Backup report files from converting an old project file# to a newer Visual Studio version.Backup files are not needed, # because we have git ;-)_UpgradeReport_Files/Backup*/UpgradeLog*.XMLUpgradeLog*.htmServiceFabricBackup/*.rptproj.bak# SQL Server files*.mdf*.ldf*.ndf# Business Intelligence projects*.rdl.data*.bim.layout*.bim_*.settings*.rptproj.rsuser# Microsoft FakesFakesAssemblies/# GhostDoc plugin setting file*.GhostDoc.xml# Node.js Tools for Visual Studio.ntvs_analysis.datnode_modules/# Visual Studio 6 build log*.plg# Visual Studio 6 workspace options file*.opt# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)*.vbw# Visual Studio LightSwitch build output**/*.HTMLClient/GeneratedArtifacts**/*.DesktopClient/GeneratedArtifacts**/*.DesktopClient/ModelManifest.xml**/*.Server/GeneratedArtifacts**/*.Server/ModelManifest.xml_Pvt_Extensions# Paket dependency manager.paket/paket.exepaket-files/# FAKE - F# Make.fake/# JetBrains Rider.idea/*.sln.iml# CodeRush.cr/# Python Tools for Visual Studio (PTVS)__pycache__/*.pyc# Cake - Uncomment if you are using it# tools/**# !tools/packages.config# Tabs Studio*.tss# Telerik's JustMock configuration file*.jmconfig# BizTalk build output*.btp.cs*.btm.cs*.odx.cs*.xsd.cs# OpenCover UI analysis resultsOpenCover/# Azure Stream Analytics local run outputASALocalRun/# MSBuild Binary and Structured Log*.binlog# NVidia Nsight GPU debugger configuration file*.nvuser# MFractors (Xamarin productivity tool)working folder.mfractor/# sqlite*.db# Don't ignore server launchSettings.json.We need a specific port number for auth to work.!**/BlazingPizza.Server/Properties/launchSettings.json

After that, the number of non-committed files should drop sharply to 31.
Create our first commit on the Repository tab:
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
Enter "initial commit" in the commit description and include all files in the commit by clicking on "Unversioned files" => "Add to VCS" :
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
With the infrastructure more or less done, let’s talk a little bit about the content of the solushen.

Contents Solution

BlazingPizza.Client Contains the UI components for our application.Also in this application in the file Startup.cs is < arr > which creates a client-side entry point into our application. The key component of the application is App.razor it is associated with the tag < arr > on the index.html page and is loaded first when the application starts.
wwwroot/index.html – the root page of our Web application, which is an usual html page with a non-standard element < app >
There is also the script _framework/blazor.webassembly.js which is responsible for loading Net runtime that is Mono and all assemblies of the application. After that, it performs initialization to start the application.
BlazingPizza.Server We added this project in our software because when we created the application from the blazorwasm template we added the option -ho, which means "Hosted deployment with ASP.NET Core- in this case we will host and handle application requests ASP.NET Core application. In the same way, the utility dotnet by using the -ho switch created for us controllers which can be used to implement the web api. Of course not only web applications but also anything else, mobile applications, or for example some external clients can address it. The second model is Standalone hosting for example on IIS, we won’t discuss it here.
BlazingPizza.Shared(to be renamed BlazingPizza.DomainModels) Contains classes that you can browse between the client part and the server part. This is supposed to save you time and effort. But as they say, the road to hell is paved with good intentions.
A simple example: we have a class Pizza, you want to use it on the client side to display the pizza, and give it to the controller. At first everything is fine, then you get the idea to put some display related attributes on it or add some calculable property Then you get a mobile client where you don’t need this logic and it will be written in JavaScript or Kotlin

Right now let’s rename the project BlazingPizza.Shared in BlazingPizza.DomainModels It should be said here that Rider despite the marking of experimental did a great job. Run the project and make sure that everything is working and nothing is broken
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment
It would be nice to create a comit with changes here, if only just to see how much Rider has done for us, just to remind you if it was Visual Studio Code , all this would have to be done manually yourself, see the diff files by clicking on them.
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment

Let’s add new Projects

Let’s add some more projects, starting with BlazingPizza.ViewModels. It will display the display models on the client. To add, right click on the solus and select Add => New Project (the type of project in this and subsequent ones in this part Class Library )
BlazingPizza:an app on Blazorfrom start to finish.Part 1.Setting up the Environment

BlazingPizza.DataAccess.Models Models used in the layer to access data from the database
BlazingPizza.DataAccess.Infrastructure Everything that is responsible for interacting with the database
BlazingPizza.Services.Interfaces The interfaces for services are separated from the implementations, so that if you use other implementations than the default one, you don’t have to drag them along with you.
BlazingPizza.Services Services implementations, e.g. PizzaService which will add pizza to the DB While doing some checks related to business logic.

If something went wrong, or you just don’t want to take the time to set it up and start right away with the second lesson, sources here
Oh yeah, almost forgot 🙂 Link to the original project (MIT License)

You may also like