Book Image

ASP.NET Core 2 and Angular 5

By : Valerio De Sanctis
Book Image

ASP.NET Core 2 and Angular 5

By: Valerio De Sanctis

Overview of this book

Become fluent in both frontend and backend web development by combining the impressive capabilities of ASP.NET Core 2 and Angular 5 from project setup right through the deployment phase. Full-stack web development means being able to work on both the frontend and backend portions of an application. The frontend is the part that users will see or interact with, while the backend is the underlying engine, that handles the logical flow: server configuration, data storage and retrieval, database interactions, user authentication, and more. Use the ASP.NET Core MVC framework to implement the backend with API calls and server-side routing. Learn how to put the frontend together using top-notch Angular 5 features such as two-way binding, Observables, and Dependency Injection, build the Data Model with Entity Framework Core, style the frontend with CSS/LESS for a responsive and mobile-friendly UI, handle user input with Forms and Validators, explore different authentication techniques, including the support for third-party OAuth2 providers such as Facebook, and deploy the application using Windows Server, SQL Server, and the IIS/Kestrel reverse proxy.
Table of Contents (17 chapters)
Title Page
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Preface

It's only been a year since I wrote ASP.NET Core and Angular 2, but it definitely feels a lot more, at least from a web developer's perspective. Modern web technologies are still improving at lightning-fast speed, with an increasing, perceptible, and measurable interest being in the client-side aspects of the game. Angular, React, and VueJS collected no less than 150,000 StackOverflow questions in the latest 18 months, which is more than 250 per day--and the trend is still growing.

That's to be expected, since most of the major conceptual changes that occurred between 2015 and 2017 have been hitting the clients way more than the servers; we switched from a reactive approach of doing stuff--that led us to build responsive, resilient, elastic, and message-driven Single-Page Apps (SPAs)--to a progressive way of seeing things--which materialized into Progressive Web Apps (PWAs). The change of perspective is slight, yet prominent; far from being a different paradigm, what we've seen was nothing less than the natural and inevitable evolution of the same original concepts.

Compared to the SPA revolution that took place in 2015-2016, the rise of Progressive Web Apps is not a game-breaking event; we can say that PWAs inherit all the major concepts that were already part of the Reactive Manifesto and bring them further on with brand new features--such as Service Workers--that would not have been possible without some relevant client-side accomplishments such as HTML5, modern browsers, and ECMAScript 6. PWAs are a much expected improvement in the present that also emphasizes its increasing distance from the past. At the same time, PWAs are not meant to be the future, not because they won't become a standard--they definitely will--but because they will also improve and, eventually, collapse into something else. This is how the client side of the moon always worked and--hopefully--always will.

What happened to the other side, then? We can't possibly say that 2017 wasn't an intense year for server-side technologies; Node.js is still dominating the scene, with more than 8 million confirmed instances online at the moment and trustable surveys telling us that three developers out of four will deal with it even more than they did. As well as the raw and naked usage, there is also a crowded galaxy of modern web frameworks based on Node, boosting its popularity even more, such as Hapi, Express, Restify, Koa, Sails, and Adonis, just to mention some of them. Django continues to focus on stability, with the 1.11 LTS bringing a lot of minor and major fixes; the next major release, expected for December, will also bring some neat improvements such as simplified URL routing syntax, window expressions, and improved Phyton 3.x support. The whole PHP ecosystem, which seemed to be slowly but steadily doomed to lose ground, regained some breath thanks to the great performance achievements reached by PHP 7.1 (in late 2016) and the huge number of available frameworks--Symfony, Laravel, Zend, Yii, Expressive, Silex, Slim, and more--each of which is best suited for a distinctive set of patterns, use cases, and scenarios. Last but definitely not least, comes ASP.NET; the .NET Core 2.0 release features some major improvements that make it easier to use and also more capable as a platform: major performance boosts in both framework and runtime, six new supported platforms--including Debian, SUSE, and macOS--and even ARM32-native builds for running apps on Raspberry Pi.

If we try to connect all these dots, we can easily see how most of the innovative, experimental, and rule-changing aspects of web development are nowadays skewed toward the client side, while the server-side race is more focused on performance and stability. Nonetheless, both sides of the coin share a strong common ground built upon the concepts of readability, maintainability, and overall simplicity of the source code.

Back in 2016, among all those different and yet kindred environments, we chose to focus on two of them: ASP.NET Core to cover the server-side aspects, and Angular to deal with the client side. Apart from the technical reasons, we also did this because these two frameworks had something in common that we did like: both of them were a reboot of a massively popular previous installment that played a leading role in their respective field. That was a bold, revolutionary move that we liked a lot. Should we do the same in 2017 as well? Are ASP.NET Core 2 and Angular 5 still a viable choices to deal with Progressive Web Apps, lightning-speed performance, and code simplicity?

In short, the answer is yes, and the book you're about to read will do its very best to prove it.

What this book covers

Chapter 1, Getting Ready, introduces the ASP.NET Core and Angular frameworks, explaining how they can effectively be used to build a feature-rich, modern web application. It then enumerates the core aspects of a common SPA project, which will be addressed throughout the following chapters. The last part covers the required steps for setting up a .NET Core web application project, along with its required packages and components, up to a buildable and running app skeleton.

Chapter 2,Backend with .NET Core, explains how we can build our very own set of APIs to exchange JSON data between a server-side ASP.NET Core Controller and a client-side Angular Component. The reader will learn how to handle the HTTP request-response cycle and also how to configure the improved routing logic built upon the .NET Core pipeline.

Chapter 3, Frontend with Angular, focuses on the client-side aspects; the reader will learn how to fetch JSON objects with Angular and show the retrieved data onscreen using the Angular Template Syntax. They will also understand how to deal with client-side routing in Angular and how to implement a viable routing pattern using the PathLocationStrategy approach.

Chapter 4, Data Model with Entity Framework Core, guides the reader through implementing a proper, DBMS-based Data Model using Entity Framework (EF) Core. They will learn how to install and properly configure the required EF Core packages, then use them to build a lightweight set of entities and persist them into a database structure using the Code-First approach.

Chapter 5, Client-Server Interactions, shows how the existing code can be upgraded to make full use of the EF Core Entities defined in the last chapter. The reader will learn how to fetch and persist the application data using the database instead of the sample objects mocked by the previous data-retrieval methods.

Chapter 6, Style Sheets and UI Layout, introduces LESS, a powerful dynamic style sheet language that can be compiled into CSS. After a brief overview of the LESS language syntax, the reader will learn how to add, implement, and compile LESS scripts within the application project to greatly improve the frontend UI.

Chapter 7, Forms and Data Validation, is mostly dedicated to passing data from the client to the server, from account-related features--such as user registration--to more complex interactions with the whole range of existing Entities. The reader will learn how to send PUT- and POST-based requests using the versatile Angular Model-Driven approach, and how to properly respond to them by extending the existing .NET Core Controllers accordingly.

Chapter 8, Authentication and Authorization, starts as a recap of the most relevant auth-related concepts for building a web application and then shows how to turn these concepts into practice. The reader will learn how to implement a sample token-based auth provider and also how to properly add and configure it throughout the existing Entity Framework entities, .NET core services, and HTTP middleware list.

Chapter 9, Advanced Topics, shows how to implement a specific set of features required to finalize a production-ready web application, such as token expiration, refresh tokens, new user registration, and third-party authentication.

Chapter 10, Finalization and Deployment, describes the most common tasks to publish a potentially shippable web application onto a production server. The reader will learn how to replace the localDb instance with an external SQL Server, create FTP and FileSystem publishing profiles, upload their compiled application to an external server, and configure it to run under IIS using the .NET Core Windows Server Hosting bundle; they will also learn how to deal with the most common issues with the help of some .NET Core-specific troubleshooting techniques.

What you need for this book

  • Windows 7 SP1 or newer, up to and including Windows 10
  • Visual Studio 2017 15.4.2 (or newer): any version will work, including the freely available Community Edition
  • Microsoft SQL Server 2017 (o newer) for Chapter 10, Finalization and Deployment only: any version will work, including the freely available Express Edition
  • Windows Server 2008 R2 (or newer) for Chapter 10, Finalization and Deployment only
  • Microsoft .NET Core SDK 2.0.1, freely available as an official Microsoft download
  • TypeScript 2.1.5.0 (or newer), freely available
  • NodeJS 6.11.2 (or newer), freely available
  • Angular 5.0.0 final release (or newer), freely available

All ASP.NET, Angular, JavaScript, and CSS packages used throughout the book are also open source and freely available for download using Visual Studio package managers such as NuGet and npm.

Who this book is for

This book is for seasoned ASP.NET developers who already know about ASP.NET Core and Angular in general, but want to know more about them and/or understand how to blend them together to craft a production-ready SPA.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:

"Fill it with its corresponding pagenotfound.component.html template file."

A block of code is set as follows:

import { Component } from "@angular/core";

@Component({
    selector: "pagenotfound",
    templateUrl: "./pagenotfound.component.html"
})

export class PageNotFoundComponent {
    title = "Page not Found";
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<h1>Welcome to TestMakerFree</h1>
<p>A sample SPA project made with .NET Core and Angular.</p>
<quiz-list class="latest"></quiz-list>
<quiz-list class="byTitle"></quiz-list>
<quiz-list class="random"></quiz-list>

Any command-line input or output is written as follows:

dotnet ef database update

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this:

"Open a PowerShell Command Prompt and navigate through the project's root folder."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:

  1. Log in or register to our website using your email address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  1. Enter the name of the book in the Search box.
  2. Select the book for which you're looking to download the code files.
  3. Choose from the drop-down menu where you purchased this book from.
  4. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/ASP.NET-Core-2-and-Angular-5. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

 

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.