📜 ⬆️ ⬇️

We write HabraKvest on ASP.NET Core and Angular2

Every time with the release of the new framework, I want to try it in and write some application on it. The last time the quest format went perfectly. By this, I propose to see what has changed in almost a year and a half and write another quest - and we'll look at the frameworks, and you can play.
Result:
- sorts on githaba for those who are interested to look at the source
- link to the quest for those who are interested in what happened or spend their time on another logical quest.

Under the cat described the complete process from creating a project to its deployment.


Prerequisites


Almost any IDE or text editor will work with ASP.NET Core and Angular2. Of course, ASP.NET needs Visual Studio for full debugging, but with the release of the new Core version it is not necessary for development, you can work with the code in Sublime \ Atom \ ... and run the application (after installing the SDK) from the command line using:
dotnet run 

Source code, installer, documentation for the .NET command line interface and the SDK can be found at:
dotnet.imtqy.com
Moreover, all this is now available not only on Windows but also on Max, Linux, as well as Docker.

Probably many will experience cognitive dissonance after seeing
 sudo apt-get install dotnet-dev-1.0.0-preview2-003121 

')

Create a project


There are several ways to create a new ASP.NET core application:
1) Using Visual Studio
2) From the console - dotnet new
3) Using third-party generators .

We will not go into all the problems of creating and configuring a project, especially since we need not an empty application, but already with Angular2 connected and, preferably, customized build scripts.
ASP.NET Core JavaScript Services github.com/aspnet/JavaScriptServices is ideal for this, which allows you to create ASP.NET Core applications with a JavaScript framework to choose from: Angular 2, React, and Knockout.
To do this, we need: ASP.NET Core, Node.js and the yeoman generator with the aspnet-spa template. The latter can be installed using:
 npm install -g yo generator-aspnetcore-spa 

Now creating a new project comes down to
 cd <__> yo aspnetcore-spa 



We select Angular2 a template, the name of the project and the generator itself will create all structure, dependences, etc. (this may take a few minutes).
At first it may seem that this generator uses too many libraries, especially if you are not a fan of the latter or have worked very little with the front end. But personally, my opinion is that this is one of the most balanced patterns. I especially want to highlight the following properties:

TypeScript


Of course, developing applications on Angular2 is possible on simple JavaScript, TypeScript gives us the possibility of typing, autocompletion, more familiar (for most) syntax for OOP. As well as the Angular2 team actively uses TypeScript and it seems that TypeScript will be (or already is) an unofficial default language for Angular2.

Webpack


It seems that the webpack is quickly becoming a favorite in the battle of front-end tools. It is especially important to note its capabilities with constant code changes. In fact, the developer can forget about constantly rebuilding the project and refreshing the page using Hot Module Replacement ( HMR ). After we tried to write the front-end on one monitor, while on the second one he was changing before his eyes, he did not want to go back to tools without the possibility of hot-swapping.

Other bonuses


Server pre-render, lazy loading, convenient work with Development and Production builds.
You can find out more in the blog of one of the JavaScriptServices developers:
blog.stevensanderson.com/2016/05/02/angular2-react-knockout-apps-on-aspnet-core
or to see a real example in one of the last public stand-ups of the ASP.NET team:


We collect the project


As mentioned earlier, to build and run a project, you can use the console command:
 dotnet run 


As a result, the site will be built and run locally:


Or, do the same from Visual Studio.
If after the build you will be notified that not all npm modules are installed,

Most likely this is a problem because one of the modules is not supported in Windows, but since the dependency is not mandatory, the application should work fine.

As a result, you should run a working application with three simple pages.


Getting Started


Consider the main differences in comparison with previous versions of frameworks.

Project structure


It looks like the JavaScriptServices project structure is webpack-oriented. That is, it is npm + webpack, respectively, there are no gulp and bower. As far as I understand, bower just decided not to add to the starting project, since there are not many dependencies on JavaScript libraries, npm handles everything. And all the functions of gulp (or grunt) are now performed by the webpack .

As for the file structure, the server files are the same as before, but there are some differences on the front-end. For example, in the folder with static files wwwroot there is only a folder dist, where, in fact, all JavaScript is compiled.
In comparison with the first version of Angular, it is striking that there are no views and controllers - all in the components and for each html part of the components there is a TypeScript part.

Features in progress


Webpack is of course very happy in terms of hot-swappable modules, the development of the front-end part is much nicer because of this.
It should also be noted that WebPack errors are excellently shown already at the ASP.NET level, a very convenient integration. However, after an erroneous state (for example, pulling up a non-existent component), the hot swap did not work for me, perhaps in such cases it is still necessary to refresh the page manually.

It is also very convenient that you can TypeScript debug in the browser and all this is already built in by default.


First of all, I redid the pages with examples for the ones I need. It turned out to be very simple, despite the fact that my knowledge of Angular2 and TypeScript is close to zero. In general, the syntax of the new Angular seems very readable, at least at first glance. And the ability to describe interfaces, classes, and types in TypeScript makes it very understandable.
An example of a simple component:

I think most developers who see TypeScript for the first time will immediately understand what is happening here.

Entity Framework and Database


If you are familiar with previous versions of the Entity Framework, there should be no problems with the Entity Framework Core. As a last resort - you can view the documentation on docs.efproject.net/en/latest/intro.html

First, we put nuget packages for EF itself, as well as for tools for working with the database (the version of the latter is not yet stable):
 Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools –Pre 

github.com/gbdrm/HabraQuest/commit/959f4cb6c253dad0cc5e6eb34756ee5cc9c920f9

Next, add tool commands to project.json , to do this, open it, find the tools settings and add
 "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final", 

Perhaps in your template tools will already be added. Then nothing needs to be changed.

We add classes of model of our application and DbContext and register them in Startup.cs .
And of course ConnectionString in appsettings.json and also add code for configuration in Startup.cs .
github.com/gbdrm/HabraQuest/commit/7411eb4262bdef9f5fb810f6cf7d5a239221c0b5

The next step, a typical story with migrations, we add the initial migration and ask the database to be updated.
 Add-Migration Initial Update-Database 

Since the base does not exist yet, it must be created after the second command. This can be checked by looking at which databases exist if you join the SQL server using Visual or SQL Management Studio.
github.com/gbdrm/HabraQuest/commit/09b42dc0a8e45da1f461b38c2b41d79c4fc0b88a

Let's add a simple method to the Home controller and try to use the connection to the database as little as possible. Add a method to create a new player, which will return his token.
github.com/gbdrm/HabraQuest/commit/e67a322184517aa929d1347f6fd638c6290bf9d3

If we now run the application, we can test this method by adding / home / registernewplayer to the end of the address. As a result, we must get our player's token.


First steps in Angular 2


Since we have already created a primitive back-end, we can try to use it on the client. Let's try the following:
when a new user visits a page, check if he has a cookie with a token and, if not, ask him from the server. In order not to create your own bike, try using the existing library to work with cookies. For example, ng2-cookies .
To do this, we need to install it and connect it to the home component.
github.com/gbdrm/HabraQuest/commit/8c7aadd9607a0c4d0a1039707b08b0c4b720112c

It’s hard to describe my next few hours of persistent struggle with the stereotypes of JavaScript and the first Angular. It turned out that in the second version of the framework everything is completely different. I can only say that it ended up with the fact that I decided not to use services (I decided to better deal with rxjs observable, which is actively used in Angular 2), updated the packages before the next release of the candidate (fourth), added new forms (it turned out that they were heavily reworked and this process is not yet complete) and decided to maximize the code (most of the logic in one component). First you need to do something working, and then we will think about good practices. Also added a few stubs on the server side.
github.com/gbdrm/HabraQuest/commit/60c8239a89cae2357d0521973e091781027186ba

Of the interesting features - whether the studio or the resharper can pull up the correct imports for TypeScript, as well as in most cases the standard navigation by methods works. Because of this kind of features, writing code for the client side becomes much more pleasant, there is no more feeling that you are writing some kind of script that can fall anywhere. Instead, the basic elements of the syntax are checked automatically and there is confidence that everything will not break somewhere in the middle. And even if it breaks, one more check will be performed at the webpack level and as a result an error will be shown on the page, even without restarting.


However, sometimes, it starts to strain, when after each save the file - the page starts to redraw. But I think this is a matter of habit.

All the following code is not very important. Basically, this is the implementation of muffled moments. If you are still interested to view - source code is available at github.com/gbdrm/HabraQuest

Deployment


Since the back-end is written on .Net then we will deploy our application to Azure. By the way, over the past year and a half there are also plenty of changes here, the first time you can’t figure it out and where. For our application, it will be enough for us to create the most basic site with a database (Web App + SQL).
Deployments, as always, are not very smooth. First, it does not pass without errors. The site itself works, but as a result, Visual Studio shows errors in some external TypeScript modules. So far I have not figured out what it is. Secondly, it happens that when opening the site, the error “TaskCanceledException: A task was canceled” crashes. With this, too, is not yet completely clear, but it seems the problem is somewhere at the hosting level. And besides this, I played a little with migrations.

Although, in general, I was pleased with this step. Very detailed and understandable log, everything can be configured (base, migration). The first time, however, you need to wait some time (a few minutes) until everything is built, copied. And in general, it seems that the process is quite complicated, as far as I understood, everything is copied locally first, and then transferred to Azure, but these are details.

Result, conclusions


Everything turned out as planned. Personally, I am satisfied with new frameworks, I would be happy to switch to them. Of course, there are still not very stable moments, Angular 2 is also not officially released at all. But everything looks quite interesting and, most importantly, it works.
I am very pleased with the development of tools and approaches in development that allow you to do fewer routine tasks, such as updating the page, controlling the structure of the database.
Also, there are a lot of blogs, questions, documentation in the network, so with the solution of typical problems everything should be easy.

All results can be found at:
github.com/gbdrm/HabraQuest
habraquest.azurewebsites.net

It turned out pretty messy, as many different topics. Which of them are the most interesting for you to describe in the future?

Source: https://habr.com/ru/post/306292/


All Articles