ASP.NET Core 5 and Angular - Valerio De Sanctis - E-Book

ASP.NET Core 5 and Angular E-Book

Valerio De Sanctis

0,0
55,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learning full-stack development calls for knowledge of both front-end and back-end web development. ASP.NET Core 5 and Angular, Fourth Edition will enhance your ability to create, debug, and deploy efficient web applications using ASP.NET Core and Angular. This revised edition includes coverage of the Angular routing module, expanded discussion on the Angular CLI, and detailed instructions for deploying apps on Azure, as well as both Windows and Linux.

Taking care to explain and challenge design choices made throughout the text, Valerio teaches you how to build a data model with Entity Framework Core, alongside utilizing the Entity Core Fluent API and EntityTypeConfiguration class. You’ll learn how to fetch and display data and handle user input with Angular reactive forms and front-end and back-end validators for maximum effect.

Later, you will perform advanced debugging and explore the unit testing features provided by xUnit.net (.NET 5) and Jasmine, as well as Karma for Angular. After adding authentication and authorization to your apps, you will explore progressive web applications (PWAs), learning about their technical requirements, testing, and converting SWAs to PWAs.

By the end of this book, you will understand how to tie together the front end and back end to build and deploy secure and robust web applications.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 942

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



ASP.NET Core 5 and Angular

Fourth Edition

Full-stack web development with .NET 5 and Angular 11

Valerio De Sanctis

BIRMINGHAM - MUMBAI

ASP.NET Core 5 and Angular

Fourth Edition

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Producer: Caitlin Meadows

Acquisition Editor – Peer Reviews: Saby Dsilva

Content Development Editor: Lucy Wan

Technical Editor: Aniket Shetty

Project Editor: Parvathy Nair

Copy Editor: Safis Editing

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Presentation Designer: Ganesh Bhadwalkar

First published: October 2016

Second edition: November 2017

Third edition: February 2020

Fourth edition: January 2021

Production reference: 1270121

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-80056-033-8

www.packt.com

packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionalsLearn better with Skill Plans built especially for youGet a free eBook or video every monthFully searchable for easy access to vital informationCopy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.Packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.Packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Valerio De Sanctis is a skilled IT professional with more than 20 years of experience in lead programming, web-based development, and project management using ASP.NET, PHP, and Java. He has held senior positions at a range of financial and insurance companies, most recently serving as Chief Technology Officer, Chief Security Officer, and Chief Operating Officer at a leading after-sales and IT service provider for multiple top-tier life and non-life insurance groups. He's also a Microsoft Most Valuable Professional (MVP) for Developer Technologies and Cloud and Datacenter Management.

He has written various books on web development, many of which have become best-sellers on Amazon, with tens of thousands of copies sold worldwide.

I would like to thank those who supported me in writing this book: my beloved and beautiful wife, Carla, for her awesome encouragement and invaluable support; my children, Viola and Daniele, as well as my parents and my sister. Last but not least, I would like to thank you, the reader, for picking up this book. I really hope you will enjoy it!

About the reviewer

Wouter Huysentruit is a seasoned software developer and architect with 20 years of experience in many different fields. He strives for solutions that are easy to understand and maintain. His current interest is in developing user-friendly web applications based on Microsoft technologies and Angular, in addition to working on many open-source projects for which he also received the Microsoft MVP award.

Wouter works for the Belgian company Noest as a .NET software architect. Next to his day job, Wouter also runs his own small company, Cup of Tea, with a focus on open-source software.

A big thanks goes out to my wife and kids for supporting me during the review of this book.

Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Get in touch

Getting Ready

Technical requirements

Two players, one goal

The ASP.NET Core revolution

ASP.NET Core 1.x

ASP.NET Core 2.x

ASP.NET Core 3.x

.NET 5

What's new in Angular?

GetAngular

AngularJS

Angular 2

Angular 4

Angular 5

Angular 6

Angular 7

Angular 8

Angular 9

Angular 10

Angular 11

Reasons for choosing .NET and Angular

A full-stack approach

MPAs, SPAs, PWAs, and NWAs

Multi-page applications

Single-page applications

Progressive web applications

Native web applications

Product owner expectations

A sample SPA project

Not your usual Hello World!

Preparing the workspace

Disclaimer – do (not) try this at home

The broken code myth

Stay hungry, stay foolish, yet be responsible as well

Setting up the project

Installing the .NET 5 SDK

Checking the SDK version

Creating the .NET and Angular project

Opening the new project in Visual Studio

Performing a test run

Summary

Suggested topics

References

Looking Around

Technical requirements

Solution overview

The ASP.NET back-end

Razor Pages

Advantages of using Razor Pages

Controllers

Advantages of using Controllers

WeatherForecastController

Configuration files

Program.cs

Startup.cs

appsettings.json

The Angular front-end

Workspace

angular.json

package.json

tsconfig.json

Other workspace-level files

The /ClientApp/src/ folder

The /app/ folder

Testing the app

HomeComponent

NavMenuComponent

CounterComponent

Our first app test

Creating a new app with the Angular CLI

Installing the Angular CLI

Creating a new Angular app

Comparing the Angular apps

Updating the Startup.cs file

Testing the NG Angular app

Getting to work

Static file caching

How the HTTP cache works

Improving our caching strategy

Client app cleanup

Trimming down the component list

The AppModule source code

Adding the AppRoutingModule

Updating the NavMenu

Summary

Suggested topics

References

Front-End and Back-End Interactions

Technical requirements

Introducing ASP.NET Core health checks

Adding the HealthChecks middleware

Adding an Internet Control Message Protocol (ICMP) check

Possible outcomes

Creating an ICMPHealthCheck class

Adding the ICMPHealthCheck to the pipeline

Improving the ICMPHealthCheck class

Adding parameters and response messages

Updating the middleware setup

Implementing a custom output message

Configuring the output message

Health checks in Angular

Creating the Angular component

Creating components using the Angular CLI

health-check.component.ts

health-check.component.html

health-check.component.css

Adding the component to the Angular app

AppModule

AppRoutingModule

NavMenuComponent

Testing it out

Summary

Suggested topics

References

Data Model with Entity Framework Core

Technical requirements

The WorldCities web app

Styling and CSS basics

Reasons to use a data server

The data source

The data model

Introducing Entity Framework Core

Installing Entity Framework Core

The SQL Server Data Provider

DBMS licensing models

What about Linux?

SQL Server alternatives

Data modeling approaches

Code-First

Database-First

Making a choice

Creating the entities

Defining the entities

The City entity

The Country entity

Defining relationships

Adding the Country property to the City entity class

Adding the Cities property to the Country entity class

Defining the database table names

Getting a SQL Server instance

Installing SQL Server 2019

Creating a SQL Database on Azure

Setting up a SQL Database

Configuring the instance

Configuring the database

Creating the WorldCities database

Adding the WorldCities login

Mapping the login to the database

Creating the database using Code-First

Setting up the DbContext

Entity type configuration methods

Data Annotations

Fluent API

EntityTypeConfiguration classes

Making a choice

Database initialization strategies

Updating the appsettings.json file

Securing the connection string

Introducing Secrets Storage

Adding the secrets.json file

Working with the secrets.json file

Creating the database

Updating Startup.cs

Adding the initial migration

Using the dotnet CLI

Using the Package Manager Console

Understanding migrations

Populating the database

Implementing SeedController

Importing the Excel file

Entity controllers

CitiesController

CountriesController

Testing it out

Summary

Suggested topics

References

Fetching and Displaying Data

Technical requirements

Fetching data

Requests and responses

JSON conventions and defaults

A (very) long list

city.ts

cities.component.ts

cities.component.html

cities.component.css

app.module.ts

app-routing.module.ts

nav-menu-component.html

Serving data with Angular Material

MatTableModule

Adding pagination with MatPaginatorModule

Client-side paging

Server-side paging

Adding sorting with MatSortModule

Extending ApiResult

Installing System.Linq.Dynamic.Core

Updating CitiesController

Updating the Angular app

Adding filtering

Extending ApiResult (again)

CitiesController

CitiesComponent

CitiesComponent template (HTML) file

CitiesComponent style (CSS) file

AngularMaterialModule

Performance considerations

Adding the countries to the loop

ASP.NET

CountriesController

Angular

country.ts

countries.component.ts

countries.component.html

countries.component.css

AppModule

AppRoutingModule

NavComponent

Testing CountriesComponent

Summary

Suggested topics

ASP.NET

Angular

References

Forms and Data Validation

Technical requirements

Exploring Angular forms

Forms in Angular

Reasons to use forms

Template-Driven Forms

The pros

The cons

Model-Driven/Reactive Forms

Building our first Reactive Form

ReactiveFormsModule

CityEditComponent

city-edit.component.ts

city-edit.component.html

city-edit.component.css

Adding the navigation link

app.module.ts

app-routing.module.ts

cities.component.html

Adding a new city

Extending the CityEditComponent

Adding the "Add a new City" button

Adding a new route

HTML select

Angular Material select (MatSelectModule)

Understanding data validation

Template-driven validation

The Safe Navigation Operator

Model-driven validation

Our first validators

Server-side validation

DupeCityValidator

Introducing the FormBuilder

Creating the CountryEditComponent

country-edit.component.ts

The IsDupeField server-side API

country-edit.component.html

country-edit.component.css

AppModule

AppRoutingModule

countries.component.html

Testing the CountryEditComponent

Improving the filter behavior

Throttling and debouncing

Definitions

Why would we want to throttle or debounce our code?

Debouncing calls to the back-end

Updating the CitiesComponent

Updating the CountriesComponent

What about throttling?

Summary

Suggested topics

References

Code Tweaks and Data Services

Technical requirements

Optimizations and tweaks

Template improvements

Form validation shortcuts

Class inheritance

Implementing a BaseFormComponent

Extending CityEditComponent

Extending CountryEditComponent

Bug fixes and improvements

Validating lat and lon

city-edit.component.ts

city-edit.component.html

Adding the number of cities

CountriesController

Creating the CountryDTO class

Angular front-end updates

DTO classes – should we really use them?

Separation of concerns

Security considerations

DTO classes versus anonymous types

Securing entities

Final thoughts

Adding the country name

CitiesController

Angular front-end updates

Data services

XMLHttpRequest versus Fetch (versus HttpClient)

XMLHttpRequest

Fetch

HttpClient

Building a data service

Creating the BaseService

Adding the common interface methods

Creating the CityService

Implementing the CityService

Creating the CountryService

Summary

Suggested topics

References

Back-End and Front-End Debugging

Technical requirements

Back-end debugging

Windows or Linux?

The basics

Conditional breakpoints

Conditions

Actions

Testing the conditional breakpoint

The Output window

Configuring the Output window

Debugging EF Core

The GetCountries() SQL query

Front-end debugging

Visual Studio JavaScript debugging

JavaScript source maps

Browser developer tools

Angular form debugging

A look at the Form Model

The pipe operator

Reacting to changes

The activity log

Client-side debugging

Unsubscribing the Observables

The unsubscribe() method

The takeUntil() operator

Other viable alternatives

Should we always unsubscribe?

Application logging

Introducing ASP.NET Core logging

DBMS structured logging with Serilog

Installing the NuGet packages

Configuring Serilog

Logging HTTP requests

Accessing the logs

Summary

Suggested topics

References

ASP.NET Core and Angular Unit Testing

Technical requirements

ASP.NET Core unit tests

Creating the WorldCities.Test project

Moq

Microsoft.EntityFramework.InMemory

Adding the WorldCities dependency reference

Our first test

Arrange

Act

Assert

Executing the test

Debugging tests

Test-driven development

Behavior-driven development

Angular unit tests

General concepts

Introducing the TestBed interface

Testing with Jasmine

Our first Angular test suite

The import section

The describe and beforeEach sections

Adding a mock CityService

Implementing the mock CityService

Configuring the fixture and the component

Creating the title test

Creating the cities tests

Running the test suite

Summary

Suggested topics

References

Authentication and Authorization

Technical requirements

To auth, or not to auth

Authentication

Third-party authentication

Authorization

Third-party authorization

Proprietary versus third-party

Proprietary auth with .NET Core

The ASP.NET Core Identity model

Entity types

Setting up ASP.NET Core Identity

Adding the NuGet packages

Creating ApplicationUser

Extending ApplicationDbContext

Adjusting our unit tests

Configuring the ASP.NET Core Identity middleware

Configuring IdentityServer

Revising SeedController

A word on async tasks, awaits, and deadlocks

Updating the database

Adding identity migration

Applying the migration

Updating the existing data model

Dropping and recreating the data model from scratch

Seeding the data

Authentication methods

Sessions

Tokens

Signatures

Two-factor

Conclusions

Implementing authentication in Angular

Creating the AuthSample project

Troubleshooting the AuthSample project

Exploring the Angular authorization APIs

Route Guards

HttpInterceptor

The authorization components

Testing registration and login

Implementing the auth API in the WorldCities app

Importing the front-end authorization APIs

api-authorization.constants

AppModule

AppRoutingModule

NavMenuComponent

Adjusting the back-end code

Installing the ASP.NET Core Identity UI package

Mapping Razor Pages to EndpointMiddleware

Securing the back-end action methods

Testing login and registration

Adding an email sending service

Transactional email API using SendGrid

Create a SendGrid account

Get the Web API key

Install the SendGrid NuGet package

Verify the integration

Implement the IEmailSender interface

Scaffold the Identity pages

Disable link-based account verification

Test the email-based account verification

External SMTP server using MailKit

Install the MailKit NuGet package

Set up the SMTP settings

Implement the IEmailSender interface

Startup class

Summary

Suggested topics

References

Progressive Web Apps

Technical requirements

PWA – distinctive features

Secure origin

Offline loading and Web App Manifest

Service workers versus HttpInterceptors

Introducing @angular/service-worker

The ASP.NET Core PWA middleware alternative

Implementing the PWA requirements

Manual installation

Adding the @angular/service-worker npm package

Updating the angular.json file

Importing ServiceWorkerModule

Updating the index.html file

Adding the Web App Manifest file

Adding the favicon

Adding the ngsw-config.json file

Automatic installation

The Angular PNG icon set

Handling the offline status

Option 1 – the window's ononline/onoffline event

Option 2 – the Navigator.onLine property

Downsides of the JavaScript approaches

Option 3 – the ng-connection-service npm package

Installing ng-connection-service

Updating the app.component.ts file

Removing the isOnline.txt static file from the cache

Installing the ng-connection-service via npm (alternate route)

Updating the app.component.html file

Cross-Origin Resource Sharing

Testing the PWA capabilities

Compiling the app with the Angular CLI

Updating the Startup.cs file

Compiling the app with Visual Studio

Creating a publish profile

Copying the CLI-generated files

Updating the Startup.cs file

Testing out our PWAs

Installing the PWA

Alternative testing methods

Serving our PWA using http-server

Summary

Suggested topics

References

Windows, Linux, and Azure Deployment

Technical requirements

Getting ready for production

ASP.NET Core deployment tips

The launchSettings.json file

Development, staging, and production environments

Rule(s) of thumb

Setting the environment in production

.NET 5 deployment modes

Angular deployment tips

ng serve, ng build, and the package.json file

Differential loading

The angular.json configuration file

Automatic deployment

CORS policy

Windows deployment

Creating a Windows Server VM on MS Azure

Accessing the MS Azure portal

Adding and configuring a new VM

Configuring a DNS name label

Setting the inbound security rules

Configuring the VM

Adding the IIS web server

Installing the ASP.NET Core Windows hosting bundle

Publishing and deploying the HealthCheck app

Folder publish profile

FTP publish profile

Azure Virtual Machine publish profile

Alternative method using the IIS Web Deploy Publishing feature

Configuring IIS

Adding an SSL certificate

Adding a new IIS website entry

Configuring the IIS application pool

Testing the HealthCheck web application

Updating the testing machine's HOSTS files

Testing the app

Linux deployment

Creating a Linux CentOS VM on MS Azure

Add and configure the Linux CentOS VM

Configuring a DNS name label

Setting the inbound security rules

Configuring the Linux VM

Connecting to the VM

Installing the ASP.NET Core runtime

Installing Nginx

Opening the 80 and 443 TCP ports

Adapting the WorldCities app

Adding the forwarded headers middleware

Checking the database connection string

Creating the appsettings.Production.json file

Publishing and deploying the WorldCities app

Creating the /var/www folder

Adding permissions

Copying the WorldCities publish folder

Configuring Kestrel and Nginx

Creating the self-signed SSL certificate

Configuring the Kestrel service

Configuring the Nginx reverse proxy

Testing the WorldCities application

Update the testing machine's HOSTS files

Testing the app

Troubleshooting

Azure App Service deployment

Creating the Web App instance

Publishing the Web App

Summary

Suggested topics

References

Other Books You May Enjoy

Index

Landmarks

Cover

Index

1

Getting Ready

In this chapter, we'll build the basics of our ASP.NET and Angular journey by mixing theoretical coverage of their most relevant features with a practical approach. More specifically, in the first part of this chapter, we'll briefly review the recent history of ASP.NET/.NET Core and Angular frameworks, while in the latter part, we'll learn how to configure our local development environment so we can assemble, build, and test a sample web application boilerplate.

By the end of this chapter, you'll have gained knowledge of the path taken by ASP.NET and Angular to improve web development in the last few years and learned how to properly set up an ASP.NET and Angular web application.

Here are the main topics that we are going to cover:

The ASP.NET Core revolution: A brief history of ASP.NET Core and Angular's most recent achievementsA full-stack approach: The importance of being able to learn how to design, assemble, and deliver a complete productMulti-Page Applications (MPAs), Single-Page Applications (SPAs), Native Web Applications (NWAs), and Progressive Web Applications (PWAs): Key features of and the most important differences between the various types of web applications, as well as how well ASP.NET and Angular could relate to each one of themA sample SPA project: What we're going to do throughout this bookPreparing the workspace: How to set up our workstation to achieve our first goal – implementing a simple Hello World boilerplate that will be further extended in the following chapters

Technical requirements

These are the software packages (and relevant version numbers) used to write this book and test the source code:

Visual Studio 2019 Community edition 16.8.2 with the optional ASP.NET and web development workload (it can be selected from the Workloads section within the Visual Studio installer app)Microsoft .NET 5 SDK 5.0.100TypeScript 4.0.5NuGet package manager 5.7.0Node.js 14.15.0 (we strongly suggest installing it using Node Version Manager, also known as nvm)Angular 11.0.1

If you're on Windows, we strongly suggest installing Node.js using nvm for Windows – a neat Node.js version manager for the Windows system. You can download it from the following URL: https://github.com/coreybutler/nvm-windows/releases

We strongly suggest using the same version used within this book – or newer, but at your own risk! Jokes aside, if you prefer to use a different version, that's perfectly fine, as long as you are aware that, in that case, you may need to make some manual changes and adjustments to the source code.

The code files for this chapter can be found here: https://github.com/PacktPublishing/ASP.NET-Core-5-and-Angular

Two players, one goal

From the perspective of a fully functional web-based application, we can say that the Web API interface provided with the ASP.NET framework is a programmatic set of server-side handlers used by the server to expose a number of hooks and/or endpoints to a defined request-response message system. This is typically expressed in structured markup languages (XML), language-independent data formats (JSON), or query languages for APIs (GraphQL). As we've already said, this is achieved by exposing application programming interfaces (APIs) through HTTP and/or HTTPS protocols via a publicly available web server such as IIS, Node.js, Apache, NGINX, and so on.

Similarly, Angular can be described as a modern, feature-rich, client-side framework that pushes the HTML and ECMAScript's most advanced features, along with the modern browser's capabilities, to their full extent by binding the input and/or output parts of an HTML web page into a flexible, reusable, and easily testable model.

Can we combine the back-end strengths of ASP.NET and the front-end capabilities of Angular in order to build a modern, feature-rich, and highly versatile web application?

The answer, in short, is yes. In the following chapters, we'll see how we can do that by analyzing all the fundamental aspects of a well-written, properly designed, web-based product, and how the latest versions of ASP.NET and/or Angular can be used to handle each one of them. However, before doing all that, it might be very useful to backtrack a bit and spend some valuable time recollecting what's happened in the last 6 years in the development history of the two frameworks we're going to use. It will be very useful to understand the main reasons why we're still giving them full credit, despite the valuable efforts of their ever-growing competitors.

The ASP.NET Core revolution

To summarize what has happened in the ASP.NET world within the last 6 years is not an easy task; in short, we can say that we've undoubtedly witnessed the most important series of changes in .NET Framework since the year it came to life. This was a revolution that changed the whole Microsoft approach to software development in almost every way. To properly understand what happened in those years, it would be useful to identify some distinctive key frames within a slow, yet constant, journey that allowed a company known (and somewhat loathed) for its proprietary software, licenses, and patents to become a driving force for open source development worldwide.

The first relevant step, at least in my humble opinion, was taken on April 3, 2014 at the annual Microsoft Build conference, which took place at the Moscone Center (West) in San Francisco. It was there, during a memorable keynote speech, that Anders Hejlsberg – father of Delphi and lead architect of C# – publicly released the first version of the .NET Compiler Platform, known as Roslyn, as an open source project. It was also there that Scott Guthrie, executive vice president of the Microsoft Cloud and AI group, announced the official launch of the .NET Foundation, a non-profit organization aimed at improving open source software development and collaborative work within the .NET ecosystem.

From that pivotal day, the .NET development team published a constant flow of Microsoft open source projects on the GitHub platform, including Entity Framework Core (May 2014), TypeScript (October 2014), .NET Core (October 2014), CoreFX (November 2014), CoreCLR and RyuJIT (January 2015), MSBuild (March 2015), the .NET Core CLI (October 2015), Visual Studio Code (November 2015), .NET Standard (September 2016), and so on.

ASP.NET Core 1.x

The most important achievement brought by these efforts toward open source development was the public release of ASP.NET Core 1.0, which came out in Q3 2016. It was a complete reimplementation of the ASP.NET framework that we had known since January 2002 and that had evolved, without significant changes in its core architecture, up to version 4.6.2 (August 2016). The brand new framework united all the previous web application technologies, such as MVC, Web API, and web pages, into a single programming module, formerly known as MVC6. The new framework introduced a fully featured, cross-platform component, also known as .NET Core, shipped with the whole set of open source tools mentioned previously, namely, a compiler platform (Roslyn), a cross-platform runtime (CoreCLR), and an improved x64 Just-In-Time compiler (RyuJIT).

Some of you might remember that ASP.NET Core was originally called ASP.NET 5. As a matter of fact, ASP.NET 5 was no less than the original name of ASP.NET Core until mid-2016, when the Microsoft developer team chose to rename it to emphasize the fact that it was a complete rewrite. The reasons for that, along with the Microsoft vision about the new product, are further explained in the following Scott Hanselman blog post that anticipated the changes on January 16, 2016: http://www.hanselman.com/blog/ASPNET5IsDeadIntroducingASPNETCore10AndNETCore10.aspx

Scott's 2016 words might sound a bit ironic nowadays, as Microsoft recently decided to bring the ASP.NET 5 name back to the fore and ditch the "Core" term: we'll talk more about that in a while.

For those who don't know, Scott Hanselman has been the outreach and community manager for .NET/ASP.NET/IIS/Azure and Visual Studio since 2007. Additional information regarding the perspective switch is also available in the following article by Jeffrey T. Fritz, program manager for Microsoft and a NuGet team leader: https://blogs.msdn.microsoft.com/webdev/2016/02/01/an-update-on-asp-net-core-and-net-core/

As for Web API 2, it was a dedicated framework for building HTTP services that returned pure JSON or XML data instead of web pages. Initially born as an alternative to the MVC platform, it has been merged with the latter into the new, general-purpose web application framework known as MVC6, which is now shipped as a separate module of ASP.NET Core.

The 1.0 final release was shortly followed by ASP.NET Core 1.1 (Q4 2016), which brought some new features and performance enhancements, and also addressed many bugs and compatibility issues affecting the earlier release. These new features include the ability to configure middleware as filters (by adding them to the MVC pipeline rather than the HTTP request pipeline); a built-in, host-independent URL rewrite module, made available through the dedicated Microsoft.AspNetCore.Rewrite NuGet package; view components as tag helpers; view compilation at runtime instead of on demand; .NET native compression and caching middleware modules; and so on.

For a detailed list of all the new features, improvements, and bug fixes of ASP.NET Core 1.1, check out the following links.

Release notes: https://github.com/aspnet/AspNetCore/releases/1.1.0

Commits list: https://github.com/dotnet/core/blob/master/release-notes/1.1/1.1-commits.md

ASP.NET Core 2.x

Another major step was taken with ASP.NET Core 2.0, which came out in Q2 2017 as a preview and then in Q3 2017 for the final release. The new version featured a wide number of significant interface improvements, mostly aimed at standardizing the shared APIs among .NET Framework, .NET Core, and .NET Standard to make them backward-compatible with .NET Framework.

Thanks to these efforts, moving existing .NET Framework projects to .NET Core and/or .NET Standard became a lot easier than before, giving many traditional developers a chance to try and adapt to the new paradigm without losing their existing know-how.

Again, the major version was shortly followed by an improved and refined one: ASP.NET Core 2.1. This was officially released on May 30, 2018 and introduced a series of additional security and performance improvements, as well as a bunch of new features, including SignalR, an open source library that simplifies adding real-time web functionality to .NET Core apps; Razor class libraries; a significant improvement in the Razor SDK that allows developers to build views and pages into reusable class libraries, and/or library projects that could be shipped as NuGet packages; the Identity UI library and scaffolding, to add identity to any app and customize it to meet your needs; HTTPS support enabled by default; built-in General Data Protection Regulation (GDPR) support using privacy-oriented APIs and templates that give users control over their personal data and cookie consent; updated SPA templates for Angular and ReactJS client-side frameworks; and much more.

For a detailed list of all the new features, improvements, and bug fixes of ASP.NET Core 2.1, check out the following links.

Release notes: https://docs.microsoft.com/en-US/aspnet/core/release-notes/aspnetcore-2.1

Commits list: https://github.com/dotnet/core/blob/master/release-notes/2.1/2.1.0-commit.md

Wait a minute: did we just say Angular? Yeah, that's right. As a matter of fact, since its initial release, ASP.NET Core has been specifically designed to seamlessly integrate with popular client-side frameworks such as ReactJS and Angular. It is precisely for this reason that books such as this exist. The major difference introduced in ASP.NET Core 2.1 is that the default Angular and ReactJS templates have been updated to use the standard project structures and build systems for each framework (the Angular CLI and NPX's create-react-app command) instead of relying on task runners such as Grunt or Gulp, module builders such as webpack, or toolchains such as Babel, which were widely used in the past, although they were quite difficult to install and configure.

Being able to eliminate the need for these tools was a major achievement, which has played a decisive role in revamping the .NET Core usage and growth rate among the developer communities since 2017. If you take a look at the two previous installments of this book – ASP.NET Core and Angular 2, published in mid-2016, and ASP.NET Core 2 and Angular 5, out in late 2017 – and compare their first chapter with this one, you will see the huge difference between having to manually use Gulp, Grunt, or webpack and relying on the integrated framework-native tools. This is a substantial reduction in complexity that would greatly benefit any developer, especially those less accustomed to working with those tools.

Six months after the release of the 2.1 version, the .NET Foundation came out with a further improvement: ASP.NET Core 2.2 was released on December 4, 2018 with several fixes and new features, such as an improved endpoint routing system for better dispatching of requests, updated templates featuring Bootstrap 4 and Angular 6 support, a new health checks service to monitor the status of deployment environments and their underlying infrastructures, including container orchestration systems such as Kubernetes, built-in HTTP/2 support in Kestrel, a new SignalR Java client to ease the usage of SignalR within Android apps, and so on.

For a detailed list of all the new features, improvements, and bug fixes of ASP.NET Core 2.2, check out the following links.

Release notes: https://docs.microsoft.com/en-US/aspnet/core/release-notes/aspnetcore-2.2

Commits list: https://github.com/dotnet/core/blob/master/release-notes/2.2/2.2.0/2.2.0-commits.md

ASP.NET Core 3.x

ASP.NET Core 3 was released in September 2019 and came with another bunch of performance and security improvements and new features, such as Windows desktop application support (Windows only) with advanced importing capabilities for Windows Forms and Windows Presentation Foundation (WPF) applications; C# 8 support; .NET Platform-Dependent Intrinsic access through a new set of built-in APIs that could bring significant performance improvements in certain scenarios; single-file executables support via the dotnet publish command using the <PublishSingleFile> XML element in project configuration or through the /p:PublishSingleFile command-line parameter; new built-in JSON support featuring high performance and low allocation that's arguably two to three times faster than the JSON.NET third-party library (which became a de facto standard in most ASP.NET web projects); TLS 1.3 and OpenSSL 1.1.1 support in Linux; some important security improvements in the System.Security.Cryptography namespace, including AES-GCM and AES-CCM ciphers support; and so on.

A lot of work has also been done to improve the performance and reliability of the framework when used in a containerized environment. The ASP.NET Core development team put a lot of effort into improving the .NET Core Docker experience on .NET Core 3.0. More specifically, this is the first release featuring substantive runtime changes to make CoreCLR more efficient, honor Docker resource limits better (such as memory and CPU) by default, and offer more configuration tweaks. Among the various improvements, we could mention improved memory and GC heap usage by default, and PowerShell Core, a cross-platform version of the famous automation and configuration tool, which is now shipped with the .NET Core SDK Docker container images.

.NET Core 3 also introduced Blazor, a free and open source web framework that enables developers to create web apps using C# and HTML.

Last but not least, it's worth noting that the new .NET Core SDK is much smaller than the previous installments, mostly thanks to the fact that the development team removed a huge set of unnecessary artifacts included in the various NuGet packages that were used to assemble the previous SDKs (including ASP.NET Core 2.2) from the final build. The size improvements are huge for Linux and macOS versions, while less noticeable on Windows because that SDK also contains the new WPF and Windows Forms set of platform-specific libraries.

For a detailed list of all the new features, improvements, and bug fixes of ASP.NET Core 3.0, check out the following links.

Release notes: https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0

ASP.NET Core 3.0 releases page: https://github.com/dotnet/core/tree/master/release-notes/3.0

ASP.NET Core 3.1, which is the most recent stable version at the time of writing, was released on December 3, 2019. The changes in the latest version are mostly focused on Windows desktop development, with the definitive removal of a number of legacy Windows Forms controls (DataGrid, ToolBar, ContextMenu, Menu, MainMenu, and MenuItem) and added support for creating C++/CLI components (on Windows only).

Most of the ASP.NET Core updates were fixes related to Blazor, such as preventing default actions for events and stopping event propagation in Blazor apps, partial class support for Razor components, additional Tag Helper Component features, and so on; however, much like the other .1 releases, the primary goal of .NET Core 3.1 was to refine and improve the features already delivered in the previous version, with more than 150 performance and stability issues fixed.

A detailed list of the new features, improvements, and bug fixes introduced with ASP.NET Core 3.1 is available at the following URL.

Release notes: https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-1

.NET 5

Just when everyone thought that Microsoft had finally taken a clear path with the naming convention of its upcoming frameworks, the MS developer community was shaken again on May 6, 2019 by the following post by Richard Lander, Program Manager of the .NET team, which appeared on the Microsoft Developer Blog: https://devblogs.microsoft.com/dotnet/introducing-net-5/

The post got an immediate backup from another article that came out the same day written by Scott Hunter, Program Management Director of the .NET ecosystem: https://devblogs.microsoft.com/dotnet/net-core-is-the-future-of-net/

The two posts were meant to share the same big news to the readers: .NET Framework 4.x and .NET Core 3.x would converge in the next major installment of .NET Core, which would skip a major version number to properly encapsulate both installments.

The new unified platform would be called .NET 5 and would include everything that had been released so far with uniform capabilities and behaviors: .NET Runtime, JIT, AOT, GC, BCL (Base Class Library), C#, VB.NET, F#, ASP.NET, Entity Framework, ML.NET, WinForms, WPF, and Xamarin.

Microsoft said they wanted to eventually drop the term "Core" from the framework name because .NET 5 would be the main implementation of .NET going forward, thus replacing .NET Framework and .NET Core; however, for the time being, the ASP.NET Core ecosystem is still retaining the name "Core" to avoid confusing it with ASP.NET MVC 5; Entity Framework Core will also keep the name "Core" to avoid confusing it with Entity Framework 5 and 6. For all of these reasons, in this book, we'll keep using "ASP.NET Core" (or .NET Core) and "Entity Framework Core" (or "EF Core") as well.

From Microsoft's point of view, the reasons behind this bold choice are rather obvious:

Produce a single .NET runtime and framework that can be used everywhere and that has uniform runtime behaviors and developer experiencesExpand the capabilities of .NET by taking the best of .NET Core, .NET Framework, Xamarin, and MonoBuild that product out of a single code base that internal (Microsoft) and external (community) developers can work on and expand together and that improves all scenarios

The new name could reasonably generate some confusion among those developers who still remember the short timeframe (early to mid 2016) in which ASP.NET Core v1 was still called ASP.NET 5 before its final release. Luckily enough, that "working title" was ditched by the MS developer team and the .NET community before it could leave noticeable traces on the web.

.NET 5 was released on General Availability in November 2020, a couple of months after its first Release Candidate, thus respecting the updated .NET schedule that aims to ship a new major version of .NET once a year, every November:

Figure 1.1: .NET schedule

In addition to the new name, the latest version of .NET brings a lot of interesting changes, such as:

Performance improvements and measurement tools, summarized in this great analysis performed by Stephen Toub (.NET Partner Software Engineer) using the new Benchmark.NET tools: https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-5/Half Type, a binary floating-point that occupies only 16 bits and that can help to save a good amount of storage space where the computed result does not need to be stored with full precision. For additional info, take a look at this post by Prashanth Govindarajan (Senior Engineering Manager at LinkedIn): https://devblogs.microsoft.com/dotnet/introducing-the-half-type/Assembly trimming, a compiler-level option to trim unused assemblies as part of publishing self-contained applications when using the self-contained deployment option, as explained by Sam Spencer (.NET Core team Program Manager) in this post: https://devblogs.microsoft.com/dotnet/app-trimming-in-net-5/Various improvements to the new System.Text.Json API, including the ability to ignore default values for value-type properties when serializing (for better serialization performance) and to better deal with circular references.C# 9 and F# 5 language support, with a bunch of new features such as Init Only Setters (that allows the creation of immutable objects), function pointers, static anonymous functions, target-typed conditional expressions, covariant return types, module initializers, and so on.

And a lot of other new features and improvements.

A detailed list of the new features and improvements and a comprehensive explanation of the reasons behind the release of ASP.NET 5 is available at the following URL.

Release notes: https://docs.microsoft.com/en-us/dotnet/core/dotnet-five

For additional info about the C# 9.0 new features, take a look at the following URL: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9

This concludes our journey through the recent history of ASP.NET. In the next section, we'll move our focus to the Angular ecosystem, which experienced a rather similar turn of events.

What's new in Angular?

If following in the footsteps of Microsoft and the .NET Foundation in recent years has not been an easy task, things were not going to get any better when we turned our eyes to the client-side web framework known as Angular. In order to understand what happened there, we have to go back 10 years, to when JavaScript libraries such as jQuery and MooTools were dominating the client-side scene; the first client-side frameworks, such as Dojo, Backbone.js, and Knockout.js, were struggling to gain popularity and reach wide adoption; and stuff such as React and Vue.js didn't even exist.

Truth be told, jQuery is still dominating the scene to a huge extent, at least according to BuiltWith (https://trends.builtwith.com/javascript/javascript-library) and w3Techs (https://w3techs.com/technologies/overview/javascript_library/all). However, despite being used by 74.1% of all websites, it's definitely an option chosen less often by web developers than it was 10 years ago.

GetAngular

The story of AngularJS started in 2009 when Miško Hevery (now senior computer scientist and Agile coach at Google) and Adam Abrons (now director of engineering at Grand Rounds) were working on their side project, an end-to-end (E2E) web development tool that would have offered an online JSON storage service and also a client-side library to build web applications depending on it. To publish their project, they took the GetAngular.com hostname.

During that time, Hevery, who was already working at Google, was assigned to the Google Feedback project with two other developers. Together, they wrote more than 17,000 lines of code in 6 months, slowly sinking into a frustrating scenario of code bloat and testing issues. Given the situation, Hevery asked his manager to rewrite the application using GetAngular (the side project mentioned previously), betting that he could do that alone within 2 weeks. His manager accepted and Hevery lost the bet shortly thereafter, as the whole thing took him 3 weeks instead of 2; however, the new application had only 1,500 lines of code instead of 17,000. This was more than enough to get Google's interest in the new framework, which was given the name AngularJS shortly thereafter.

To listen to the full story, take a look at the following Miško Hevery keynote speech at ng-conf 2014: https://www.youtube.com/watch?v=r1A1VR0ibIQ

AngularJS

The first stable release of AngularJS (version 0.9.0, also known as dragon-breath) was released on GitHub in October 2010 under an MIT license; when AngularJS 1.0.0 (also known as temporal domination) came out in June 2012, the framework had already achieved huge popularity within the web development communities worldwide.

The reasons for such extraordinary success can hardly be summarized in a few words, but I'll try to do that nonetheless by emphasizing some key selling points:

Dependency injection: AngularJS was the first client-side framework to implement it. This was undeniably a huge advantage over the competitors, including DOM-manipulating libraries such as jQuery. With AngularJS, developers could write loosely coupled and easily testable components, leaving the framework with the task of creating them, resolving their dependencies, and passing them to other components when requested.Directives: These can be described as markers on specific DOM items such as elements, attributes, styles, and so on: a powerful feature that could be used to specify custom and reusable HTML-like elements and attributes that define data bindings and/or other specific behaviors of presentation components.Two-way data binding: The automatic synchronization of data between model and view components. When data in a model changes, the view reflects the change; when data in the view changes, the model is updated as well. This happens immediately and automatically, which makes sure that the model and the view are updated at all times.Single-page approach: AngularJS was the first framework to completely remove the need for page reloads. This provided great benefits at both the server-side (fewer and smaller network requests) and client-side level (smoother transitions, a more responsive experience), and paved the way for the Single-Page Application pattern that would be also adopted by React, Vue.js, and the other runner-up frameworks later on.Cache-friendly: All the AngularJS magic was meant to happen on the client side, without any server-side effort to generate the UI/UX parts. For this very reason, all AngularJS websites could be cached anywhere and/or made available through a CDN.

For a detailed list of AngularJS features, improvements, and bug fixes from 0.9.0 through 1.7.8, check out the following link.

AngularJS 1.x Changelog: https://github.com/angular/angular.js/blob/master/CHANGELOG.md

Angular 2

The new release of AngularJS, released on September 14, 2016 and known as Angular 2, was a complete rewrite of the previous one, entirely based upon the new ECMAScript version 6 (officially ECMAScript 2015) specifications. Just like the ASP.NET Core rewrite, the revolution brought such a number of breaking changes at the architectural level and for HTTP pipeline handling, app life cycle, and state management that porting the old code to the new one was nearly impossible. Despite keeping its former name, the new Angular version was a brand new framework with little or nothing in common with the previous one.

The choice to not make Angular 2 backward-compatible with AngularJS clearly demonstrated the intention of the author's team to adopt a completely new approach: not only in the code syntax but also in their way of thinking and designing the client app. The new Angular was highly modular, component-based, and came with a new and improved dependency injection model and a whole lot of programming patterns its older cousin had never heard of.

Here's a brief list of the most important improvements introduced with Angular 2:

Semantic versioning: Angular 2 is the first release to use semantic versioning, also known as SemVer: a universal way of versioning the various software releases to help developers track down what's going on without having to dig into the changelog details. SemVer is based on three numbers – X.Y.Z – where X stands for a major version, Y stands for a minor version, and Z stands for a patch release. More specifically, the X number, representing the major version, gets incremented when incompatible API changes are made to stable APIs; the Y number, representing the minor version, gets incremented when backward-compatible functionality is added; and the Z number, representing a patch release, gets incremented when a backward-compatible bug is fixed. Such improvements can be easily underestimated, yet it's a must-have for most modern software development scenarios where Continuous Delivery (CD) is paramount and new versions are released with great frequency.TypeScript: Seasoned developers will probably already know what TypeScript is. Those who don't won't need to worry, since we're going to use it a lot during the Angular-related chapters of this book. For now, let's just say that TypeScript is a Microsoft-made superset of JavaScript that allows the use of all ES2015 features (such as Default-Rest-Spread Parameters, Template Literals, Arrow Functions, Promises, and more) and adds powerful type-checking and object-oriented features during development (such as class and type declarations). The TypeScript source code can be transpiled into standard JavaScript code that all browsers can understand.Server-side rendering (SSR): Angular 2 comes with Angular Universal, an open source technology that allows a back-end server to run Angular applications and serve only the resulting static HTML files to the client. In a nutshell, the server will render a first pass of the page for faster delivery to the client, then immediately refresh it with client code. SSR has its caveats, such as requiring Node.js to be installed on the host machine to execute the necessary pre-rendering steps, as well as having the whole node_modules folder there, but can greatly increase the app's response time for a typical internet browser, thus mitigating a known AngularJS performance issue.Angular Mobile Toolkit (AMT): A set of tools specifically designed for building high-performance mobile apps.Command-line interface (CLI): The new CLI introduced with Angular 2 can be used by developers to generate components, routes, services, and pipes via console/Terminal commands, together with simple test shells.Components: These are the main building blocks of Angular 2, entirely replacing the controllers and scopes of AngularJS, and also taking on most of the tasks previously covered by the former directives. Application data, business logic, templating, and the styling of an Angular 2 app can all be done using components.

I did my best to explore most of these features in my first book, ASP.NET Core and Angular 2, which was published in October 2016, right after the final release of the two frameworks: https://www.packtpub.com/product/asp-net-core-and-angular-2/9781786465689

Angular 4

On March 23, 2017, Google released Angular 4: the number 3 version was skipped entirely in order to unify all the major versions of the many Angular components that had been developed separately before that date, such as Angular Router, which already was at version 3.x at the time. Starting with Angular 4, the entire Angular framework was then unified into the same MAJOR.MINOR.PATCH SemVer pattern.

The new major version brought a limited number of breaking changes, such as a new and improved routing system, TypeScript 2.1+ support (and a requirement), and some deprecated interfaces and tags. There were also a good number of improvements, including:

Ahead-of-time (AOT) compilation: Angular 4 compiles the templates during the build phase and generates JavaScript code accordingly. That's a huge architectural improvement over the JIT mode used by AngularJS and Angular 2 where the app was compiled at runtime. For example, when the application starts, not only is the app faster since the client doesn't have to compile anything, but it throws/breaks at build time instead of during runtime for most component errors, thus leading to more secure and stable deployments.Animations npm package: All the existing UI animations and effects – as well as new ones – were moved to the @angular/animations dedicated package instead of being part of @angular/core. This was a smart move to give non-animated apps the chance to drop that part of code, thus being much smaller and arguably faster.

Other notable improvements included: a new form validator to check for valid email addresses, a new paramMap interface for URL parameters in the HTTP routing module, better internalization support, and so on.

Angular 5

Released on November 1, 2017, Angular 5 featured TypeScript 2.3 support, another small set of breaking changes, many performance and stability improvements, and a few new features, such as the following:

New HTTP Client API: Starting from Angular 4.3, the @angular/http module was put aside in favor of a new @angular/common/http package with better JSON support, interceptors, and immutable request/response objects, and other stuff. The switch was completed in Angular 5 with the previous module being deprecated and the new one recommended for use in all apps.State Transfer API: A new feature that gives the developer the ability to transfer the state of the application between the server and the client.