ASP.NET Core 5 and Angular - Fourth Edition

Book description

Build robust modern web applications using .NET 5, Entity Framework Core, and Angular 11

Key Features

  • Updated with the latest features and additions in ASP.NET Core 5 and Angular 11
  • Design, build, and deploy a Single Page Application or Progressive Web App
  • Adopt a full stack approach to handle data management, Web APIs, application design, testing, SEO, security, and deployment

Book Description

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.

What you will learn

  • Implement a web API interface with ASP.NET Core and consume it with Angular using RxJS observables
  • Set up an SQL database server using a local instance or a cloud data store
  • Perform C# and TypeScript debugging using Visual Studio 2019
  • Create TDD and BDD unit tests using xUnit, Jasmine, and Karma
  • Perform DBMS structured logging using third-party providers such as SeriLog
  • Deploy web apps to Windows and Linux web servers, or Azure App Service, using IIS, Kestrel, and nginx

Who this book is for

This book is for experienced ASP.NET developers who already possess some familiarity with ASP.NET Core and Angular and are looking to learn how to use them effectively together.

The fully documented code samples (also available on GitHub) and the step-by-step implementation tutorials make this book easy to follow.

Table of contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. Getting Ready
    1. Technical requirements
    2. Two players, one goal
      1. The ASP.NET Core revolution
        1. ASP.NET Core 1.x
        2. ASP.NET Core 2.x
        3. ASP.NET Core 3.x
        4. .NET 5
      2. What's new in Angular?
        1. GetAngular
        2. AngularJS
        3. Angular 2
        4. Angular 4
        5. Angular 5
        6. Angular 6
        7. Angular 7
        8. Angular 8
        9. Angular 9
        10. Angular 10
        11. Angular 11
      3. Reasons for choosing .NET and Angular
    3. A full-stack approach
    4. MPAs, SPAs, PWAs, and NWAs
      1. Multi-page applications
      2. Single-page applications
      3. Progressive web applications
      4. Native web applications
      5. Product owner expectations
    5. A sample SPA project
      1. Not your usual Hello World!
    6. Preparing the workspace
      1. Disclaimer – do (not) try this at home
        1. The broken code myth
        2. Stay hungry, stay foolish, yet be responsible as well
      2. Setting up the project
        1. Installing the .NET 5 SDK
        2. Checking the SDK version
        3. Creating the .NET and Angular project
        4. Opening the new project in Visual Studio
        5. Performing a test run
    7. Summary
    8. Suggested topics
    9. References
  3. Looking Around
    1. Technical requirements
    2. Solution overview
    3. The ASP.NET back-end
      1. Razor Pages
        1. Advantages of using Razor Pages
      2. Controllers
        1. Advantages of using Controllers
        2. WeatherForecastController
      3. Configuration files
        1. Program.cs
        2. Startup.cs
        3. appsettings.json
    4. The Angular front-end
      1. Workspace
        1. angular.json
        2. package.json
        3. tsconfig.json
        4. Other workspace-level files
      2. The /ClientApp/src/ folder
        1. The /app/ folder
      3. Testing the app
        1. HomeComponent
        2. NavMenuComponent
        3. CounterComponent
        4. Our first app test
    5. Creating a new app with the Angular CLI
      1. Installing the Angular CLI
      2. Creating a new Angular app
      3. Comparing the Angular apps
      4. Updating the Startup.cs file
      5. Testing the NG Angular app
    6. Getting to work
      1. Static file caching
        1. How the HTTP cache works
        2. Improving our caching strategy
      2. Client app cleanup
        1. Trimming down the component list
        2. The AppModule source code
        3. Adding the AppRoutingModule
        4. Updating the NavMenu
    7. Summary
    8. Suggested topics
    9. References
  4. Front-End and Back-End Interactions
    1. Technical requirements
    2. Introducing ASP.NET Core health checks
      1. Adding the HealthChecks middleware
      2. Adding an Internet Control Message Protocol (ICMP) check
        1. Possible outcomes
        2. Creating an ICMPHealthCheck class
        3. Adding the ICMPHealthCheck to the pipeline
      3. Improving the ICMPHealthCheck class
        1. Adding parameters and response messages
        2. Updating the middleware setup
        3. Implementing a custom output message
        4. Configuring the output message
    3. Health checks in Angular
      1. Creating the Angular component
        1. Creating components using the Angular CLI
        2. health-check.component.ts
        3. health-check.component.html
        4. health-check.component.css
      2. Adding the component to the Angular app
        1. AppModule
        2. AppRoutingModule
        3. NavMenuComponent
        4. Testing it out
    4. Summary
    5. Suggested topics
    6. References
  5. Data Model with Entity Framework Core
    1. Technical requirements
    2. The WorldCities web app
      1. Styling and CSS basics
      2. Reasons to use a data server
    3. The data source
    4. The data model
      1. Introducing Entity Framework Core
      2. Installing Entity Framework Core
      3. The SQL Server Data Provider
        1. DBMS licensing models
        2. What about Linux?
        3. SQL Server alternatives
      4. Data modeling approaches
        1. Code-First
        2. Database-First
        3. Making a choice
    5. Creating the entities
      1. Defining the entities
        1. The City entity
        2. The Country entity
      2. Defining relationships
        1. Adding the Country property to the City entity class
        2. Adding the Cities property to the Country entity class
      3. Defining the database table names
    6. Getting a SQL Server instance
      1. Installing SQL Server 2019
      2. Creating a SQL Database on Azure
        1. Setting up a SQL Database
        2. Configuring the instance
      3. Configuring the database
        1. Creating the WorldCities database
        2. Adding the WorldCities login
        3. Mapping the login to the database
    7. Creating the database using Code-First
      1. Setting up the DbContext
      2. Entity type configuration methods
        1. Data Annotations
        2. Fluent API
        3. EntityTypeConfiguration classes
        4. Making a choice
      3. Database initialization strategies
      4. Updating the appsettings.json file
      5. Securing the connection string
        1. Introducing Secrets Storage
        2. Adding the secrets.json file
        3. Working with the secrets.json file
      6. Creating the database
        1. Updating Startup.cs
      7. Adding the initial migration
        1. Using the dotnet CLI
        2. Using the Package Manager Console
        3. Understanding migrations
    8. Populating the database
      1. Implementing SeedController
        1. Importing the Excel file
    9. Entity controllers
      1. CitiesController
      2. CountriesController
      3. Testing it out
    10. Summary
    11. Suggested topics
    12. References
  6. Fetching and Displaying Data
    1. Technical requirements
    2. Fetching data
      1. Requests and responses
        1. JSON conventions and defaults
      2. A (very) long list
        1. city.ts
        2. cities.component.ts
        3. cities.component.html
        4. cities.component.css
        5. app.module.ts
        6. app-routing.module.ts
        7. nav-menu-component.html
    3. Serving data with Angular Material
      1. MatTableModule
      2. Adding pagination with MatPaginatorModule
        1. Client-side paging
        2. Server-side paging
      3. Adding sorting with MatSortModule
        1. Extending ApiResult
        2. Installing System.Linq.Dynamic.Core
        3. Updating CitiesController
        4. Updating the Angular app
      4. Adding filtering
        1. Extending ApiResult (again)
        2. CitiesController
        3. CitiesComponent
        4. CitiesComponent template (HTML) file
        5. CitiesComponent style (CSS) file
        6. AngularMaterialModule
        7. Performance considerations
    4. Adding the countries to the loop
      1. ASP.NET
        1. CountriesController
      2. Angular
        1. country.ts
        2. countries.component.ts
        3. countries.component.html
        4. countries.component.css
        5. AppModule
        6. AppRoutingModule
        7. NavComponent
        8. Testing CountriesComponent
    5. Summary
    6. Suggested topics
      1. ASP.NET
      2. Angular
    7. References
  7. Forms and Data Validation
    1. Technical requirements
    2. Exploring Angular forms
      1. Forms in Angular
      2. Reasons to use forms
      3. Template-Driven Forms
        1. The pros
        2. The cons
      4. Model-Driven/Reactive Forms
    3. Building our first Reactive Form
      1. ReactiveFormsModule
      2. CityEditComponent
        1. city-edit.component.ts
        2. city-edit.component.html
        3. city-edit.component.css
      3. Adding the navigation link
        1. app.module.ts
        2. app-routing.module.ts
        3. cities.component.html
    4. Adding a new city
      1. Extending the CityEditComponent
      2. Adding the "Add a new City" button
        1. Adding a new route
      3. HTML select
      4. Angular Material select (MatSelectModule)
    5. Understanding data validation
      1. Template-driven validation
        1. The Safe Navigation Operator
      2. Model-driven validation
        1. Our first validators
      3. Server-side validation
        1. DupeCityValidator
    6. Introducing the FormBuilder
      1. Creating the CountryEditComponent
        1. country-edit.component.ts
        2. The IsDupeField server-side API
        3. country-edit.component.html
        4. country-edit.component.css
        5. AppModule
        6. AppRoutingModule
        7. countries.component.html
      2. Testing the CountryEditComponent
    7. Improving the filter behavior
      1. Throttling and debouncing
        1. Definitions
      2. Why would we want to throttle or debounce our code?
      3. Debouncing calls to the back-end
        1. Updating the CitiesComponent
        2. Updating the CountriesComponent
      4. What about throttling?
    8. Summary
    9. Suggested topics
    10. References
  8. Code Tweaks and Data Services
    1. Technical requirements
    2. Optimizations and tweaks
      1. Template improvements
        1. Form validation shortcuts
      2. Class inheritance
        1. Implementing a BaseFormComponent
        2. Extending CityEditComponent
        3. Extending CountryEditComponent
    3. Bug fixes and improvements
      1. Validating lat and lon
        1. city-edit.component.ts
        2. city-edit.component.html
      2. Adding the number of cities
        1. CountriesController
        2. Creating the CountryDTO class
        3. Angular front-end updates
      3. DTO classes – should we really use them?
        1. Separation of concerns
        2. Security considerations
        3. DTO classes versus anonymous types
        4. Securing entities
        5. Final thoughts
      4. Adding the country name
        1. CitiesController
        2. Angular front-end updates
    4. Data services
      1. XMLHttpRequest versus Fetch (versus HttpClient)
        1. XMLHttpRequest
        2. Fetch
        3. HttpClient
      2. Building a data service
        1. Creating the BaseService
        2. Adding the common interface methods
        3. Creating the CityService
        4. Implementing the CityService
        5. Creating the CountryService
    5. Summary
    6. Suggested topics
    7. References
  9. Back-End and Front-End Debugging
    1. Technical requirements
    2. Back-end debugging
      1. Windows or Linux?
      2. The basics
      3. Conditional breakpoints
        1. Conditions
        2. Actions
        3. Testing the conditional breakpoint
      4. The Output window
        1. Configuring the Output window
      5. Debugging EF Core
        1. The GetCountries() SQL query
    3. Front-end debugging
      1. Visual Studio JavaScript debugging
        1. JavaScript source maps
      2. Browser developer tools
      3. Angular form debugging
        1. A look at the Form Model
        2. The pipe operator
        3. Reacting to changes
        4. The activity log
      4. Client-side debugging
      5. Unsubscribing the Observables
        1. The unsubscribe() method
        2. The takeUntil() operator
        3. Other viable alternatives
        4. Should we always unsubscribe?
    4. Application logging
      1. Introducing ASP.NET Core logging
      2. DBMS structured logging with Serilog
        1. Installing the NuGet packages
        2. Configuring Serilog
        3. Logging HTTP requests
        4. Accessing the logs
    5. Summary
    6. Suggested topics
    7. References
  10. ASP.NET Core and Angular Unit Testing
    1. Technical requirements
    2. ASP.NET Core unit tests
      1. Creating the WorldCities.Test project
        1. Moq
        2. Microsoft.EntityFramework.InMemory
        3. Adding the WorldCities dependency reference
      2. Our first test
        1. Arrange
        2. Act
        3. Assert
        4. Executing the test
        5. Debugging tests
      3. Test-driven development
      4. Behavior-driven development
    3. Angular unit tests
      1. General concepts
        1. Introducing the TestBed interface
        2. Testing with Jasmine
      2. Our first Angular test suite
        1. The import section
        2. The describe and beforeEach sections
        3. Adding a mock CityService
        4. Implementing the mock CityService
        5. Configuring the fixture and the component
        6. Creating the title test
        7. Creating the cities tests
        8. Running the test suite
    4. Summary
    5. Suggested topics
    6. References
  11. Authentication and Authorization
    1. Technical requirements
    2. To auth, or not to auth
      1. Authentication
        1. Third-party authentication
      2. Authorization
        1. Third-party authorization
      3. Proprietary versus third-party
    3. Proprietary auth with .NET Core
      1. The ASP.NET Core Identity model
        1. Entity types
      2. Setting up ASP.NET Core Identity
        1. Adding the NuGet packages
        2. Creating ApplicationUser
        3. Extending ApplicationDbContext
        4. Adjusting our unit tests
        5. Configuring the ASP.NET Core Identity middleware
        6. Configuring IdentityServer
        7. Revising SeedController
        8. A word on async tasks, awaits, and deadlocks
    4. Updating the database
      1. Adding identity migration
      2. Applying the migration
        1. Updating the existing data model
        2. Dropping and recreating the data model from scratch
      3. Seeding the data
    5. Authentication methods
      1. Sessions
      2. Tokens
      3. Signatures
      4. Two-factor
      5. Conclusions
    6. Implementing authentication in Angular
      1. Creating the AuthSample project
        1. Troubleshooting the AuthSample project
      2. Exploring the Angular authorization APIs
        1. Route Guards
        2. HttpInterceptor
        3. The authorization components
        4. Testing registration and login
    7. Implementing the auth API in the WorldCities app
      1. Importing the front-end authorization APIs
        1. api-authorization.constants
        2. AppModule
        3. AppRoutingModule
        4. NavMenuComponent
      2. Adjusting the back-end code
        1. Installing the ASP.NET Core Identity UI package
        2. Mapping Razor Pages to EndpointMiddleware
        3. Securing the back-end action methods
      3. Testing login and registration
    8. Adding an email sending service
      1. Transactional email API using SendGrid
        1. Create a SendGrid account
        2. Get the Web API key
        3. Install the SendGrid NuGet package
        4. Verify the integration
        5. Implement the IEmailSender interface
        6. Scaffold the Identity pages
        7. Disable link-based account verification
        8. Test the email-based account verification
      2. External SMTP server using MailKit
        1. Install the MailKit NuGet package
        2. Set up the SMTP settings
        3. Implement the IEmailSender interface
        4. Startup class
    9. Summary
    10. Suggested topics
    11. References
  12. Progressive Web Apps
    1. Technical requirements
    2. PWA – distinctive features
      1. Secure origin
      2. Offline loading and Web App Manifest
        1. Service workers versus HttpInterceptors
        2. Introducing @angular/service-worker
        3. The ASP.NET Core PWA middleware alternative
    3. Implementing the PWA requirements
      1. Manual installation
        1. Adding the @angular/service-worker npm package
        2. Updating the angular.json file
        3. Importing ServiceWorkerModule
        4. Updating the index.html file
        5. Adding the Web App Manifest file
        6. Adding the favicon
        7. Adding the ngsw-config.json file
      2. Automatic installation
        1. The Angular PNG icon set
    4. Handling the offline status
      1. Option 1 – the window's ononline/onoffline event
      2. Option 2 – the Navigator.onLine property
        1. Downsides of the JavaScript approaches
      3. Option 3 – the ng-connection-service npm package
        1. Installing ng-connection-service
        2. Updating the app.component.ts file
        3. Removing the isOnline.txt static file from the cache
        4. Installing the ng-connection-service via npm (alternate route)
        5. Updating the app.component.html file
      4. Cross-Origin Resource Sharing
    5. Testing the PWA capabilities
      1. Compiling the app with the Angular CLI
        1. Updating the Startup.cs file
      2. Compiling the app with Visual Studio
        1. Creating a publish profile
        2. Copying the CLI-generated files
        3. Updating the Startup.cs file
      3. Testing out our PWAs
        1. Installing the PWA
      4. Alternative testing methods
        1. Serving our PWA using http-server
    6. Summary
    7. Suggested topics
    8. References
  13. Windows, Linux, and Azure Deployment
    1. Technical requirements
    2. Getting ready for production
      1. ASP.NET Core deployment tips
        1. The launchSettings.json file
        2. Development, staging, and production environments
        3. Rule(s) of thumb
        4. Setting the environment in production
        5. .NET 5 deployment modes
      2. Angular deployment tips
        1. ng serve, ng build, and the package.json file
        2. Differential loading
        3. The angular.json configuration file
        4. Automatic deployment
        5. CORS policy
    3. Windows deployment
      1. Creating a Windows Server VM on MS Azure
        1. Accessing the MS Azure portal
        2. Adding and configuring a new VM
        3. Configuring a DNS name label
        4. Setting the inbound security rules
      2. Configuring the VM
        1. Adding the IIS web server
        2. Installing the ASP.NET Core Windows hosting bundle
      3. Publishing and deploying the HealthCheck app
        1. Folder publish profile
        2. FTP publish profile
        3. Azure Virtual Machine publish profile
        4. Alternative method using the IIS Web Deploy Publishing feature
      4. Configuring IIS
        1. Adding an SSL certificate
        2. Adding a new IIS website entry
        3. Configuring the IIS application pool
      5. Testing the HealthCheck web application
        1. Updating the testing machine's HOSTS files
        2. Testing the app
    4. Linux deployment
      1. Creating a Linux CentOS VM on MS Azure
        1. Add and configure the Linux CentOS VM
        2. Configuring a DNS name label
        3. Setting the inbound security rules
      2. Configuring the Linux VM
        1. Connecting to the VM
        2. Installing the ASP.NET Core runtime
        3. Installing Nginx
        4. Opening the 80 and 443 TCP ports
      3. Adapting the WorldCities app
        1. Adding the forwarded headers middleware
        2. Checking the database connection string
        3. Creating the appsettings.Production.json file
      4. Publishing and deploying the WorldCities app
        1. Creating the /var/www folder
        2. Adding permissions
        3. Copying the WorldCities publish folder
      5. Configuring Kestrel and Nginx
        1. Creating the self-signed SSL certificate
        2. Configuring the Kestrel service
        3. Configuring the Nginx reverse proxy
      6. Testing the WorldCities application
        1. Update the testing machine's HOSTS files
        2. Testing the app
        3. Troubleshooting
    5. Azure App Service deployment
      1. Creating the Web App instance
      2. Publishing the Web App
    6. Summary
    7. Suggested topics
    8. References
  14. Other Books You May Enjoy
  15. Index

Product information

  • Title: ASP.NET Core 5 and Angular - Fourth Edition
  • Author(s): Valerio De Sanctis
  • Release date: January 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781800560338