41,99 €
Develop a simple, yet fully-functional modern web application using ASP.NET Core MVC, Entity Framework and Angular 5.
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.
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.
More than just a technical manual, this guide takes you through the most important technical facets of developing with these two hugely popular frameworks and then demonstrates how to put those skills into practice. It's a book that recognizes that what's really important is the end product.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 555
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: November 2017
Production reference: 1221117
ISBN 978-1-78829-360-0
www.packtpub.com
Author
Valerio De Sanctis
Copy Editor
Shaila Kusanale
Reviewers
Ramchandra Vellanki
Juergen Gutsch
Project Coordinator
Devanshi Doshi
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Reshma Raman
Indexer
Rekha Nair
ContentDevelopmentEditor
Onkar Wani
Graphics
Jason Monteiro
Technical Editor
Akhil Nair
Production Coordinator
Aparna Bhagat
Valerio De Sanctis is a skilled IT professional with over 12 years of experience in lead programming, web-based development, and project management using ASP.NET, PHP, and Java. He previously held senior positions at a range of financial and insurance companies, most recently serving as Chief Technology Officer and Chief Operating Officer at a leading after-sales and IT service provider for many top-tier life and non-life insurance groups.
In the course of his career, Valerio De Sanctis helped many private organizations to implement and maintain .NET-based solutions, working side-by-side with many IT industry experts and leading several frontend, backend, and UX development teams. He designed the architecture and actively oversaw the development of a wide number of corporate-level web application projects for high-profile clients, customers, and partners, including London Stock Exchange Group, Zurich Insurance Group, Allianz, Generali, Harmonie Mutuelle, AIG, QBE, Marsh & McLennan, Lloyd's, Honda Motor, FCA Group, Luxottica, ANSA, Saipem, ENI, Enel, Terna, Banzai Media, Virgilio.it, Repubblica.it, and Corriere.it.
He is an active member of the Stack Exchange Network, providing advice and tips for .NET, JavaScript, HTML5, and other web-related topics on the StackOverflow, ServerFault, and SuperUser communities. Most of his projects and code samples are available under open source licenses on GitHub, BitBucket, NPM, CocoaPods, JQuery Plugin Registry, and WordPress Plugin Repository.
Starting from 2015, he also runs an IT-oriented, web-focused blog at www.ryadel.com featuring news, reviews, code samples and guides to help developers and enthusiasts worldwide. Between 2016 and 2017, he wrote two books on web development: ASP.NET Core and Angular 2, and ASP.NET Core: Cloud-ready, Enterprise Web Application Development, with over 5,000 copies sold worldwide.
Ramchandra Vellanki is a passionate programmer. He has 13 years of programming experience, has worked in different roles, and has experience in building and maintaining large-scale products/applications. He started his career with IBM iSeries, and then worked on C++, MFC, .NET, and JavaScript. Currently, he is working on .NET and JavaScript technologies. He enjoys exploring and learning new technologies.
Juergen Gutsch is a .NET-addicted web developer. He has been working with .NET and ASP.NET since the early versions in 2002. Before that, he wrote server-side web applications using classic ASP. Juergen is also an active person in the German speaking .NET developer community. He is leading the .NET user group in Basel (Switzerland) and the INETA Germany Association. Due to that, Microsoft awarded him to be a Microsoft Most Valuable Professional in the Visual Studio and Development Technologies category several times.
Jurgen writes for the dotnetpro magazine, one of the most popular German-speaking developer magazines, and he also publishes articles in English on his blog at https://asp.net-hacker.rocks. The best way to contact him and to stay in touch with him is using Twitter--https://twitter.com/sharpcms.
He is working as a developer, consultant, and trainer for the digital agency YooApplications Inc. (http://yooapps.com), located in Basel, Switzerland. YooApplications serves national as well as international clients and specializes in creating custom digital solution for distinct business needs.
For support files and downloads related to your book, please visit www.PacktPub.com. 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.PacktPub.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.PacktPub.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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788293606.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Getting Ready
Two players, one goal
The ASP.NET core revolution
What's new in Angular?
A full-stack approach
Single-Page Application
Common features of a competitive SPA
Product Owner expectations
A sample Single-Page Application project
The vision
Not your usual "Hello World!"
Introducing TestMakerFree
Core features and requirements
Preparing the workspace
Disclaimer-Do (not) try this at home
The broken code myth
Stay hungry, stay foolish, yet be responsible as well
Versions and builds
Setting up the project
Alternative setup using the command line
Test run
Looking around
The configuration files
Program.cs
Startup.cs
The appsettings.json file
The package.json file
Upgrading (or downgrading) Angular
Upgrading (or downgrading) the other packages
The tsconfig.json file
The webpack configuration files
Updating the webpack.config.js file
Patching the webpack.config.vendor.js file
Why use a dynamic module bundler?
Refreshing the Webpack-generated files
The server-side code
Controllers/HomeController.cs
Controllers/SampleDataController.cs
The /Views/ folder
The client-side code
The /ClientApp/app/ folder
Getting to work
Static file caching
A blast from the past
Back to the future
Testing it up
The strongly-typed approach(es)
Client app cleanup
Trimming down the component list
The AppModule class(es)
Updating the NavMenu
References
Suggested topics
Summary
Backend with .NET Core
The data flow
The role of ViewModel
Our first ViewModel
QuizViewModel
QuizController
Adding more action methods
ByTitle()
Random()
Testing it up
Adding other controllers
QuestionViewModel
QuestionController
AnswerViewModel
AnswerController
ResultViewModel
ResultController
Understanding routes
Defining routing
Routing through the ages
Handling routes in .NET Core
Three choices to route them all
Adding more routes
The Dummy Data Provider
Dealing with single entries
Suggested topics
Summary
Frontend with Angular
Navigation pattern
Master/detail binding
The Quiz client-side interface
The QuizList component
The new Angular HttpClient
A match against the old standard
How to install it
How to use it
Dependency Injection
Get and subscribe
The onSelect() method
The template file
The Stylesheet file
Adding the component
The AppModule file(s)
The HomeComponent template
Testing it up
The QuizComponent class
Adding the Component files
Adding the component
Testing it up
Adding additional lists
Multiple components instances
Testing and debugging
The OnInit interface and lifecycle hooks
Implementing ngOnInit
Testing it up
Two-way data binding
Disabling two-way data binding
Client-side routing
PathLocationStrategy versus HashLocationStrategy
Refactoring our app
Registering a new Route
Upgrading the QuizComponent
Getting the ID parameter
Adding the HttpClient
Fetching the data
Updating the QuizListComponent
Master/Detail Routing test
Adding new components
AboutComponent
LoginComponent
PageNotFoundComponent
Updating the AppModule
Full-Scale test
Suggested topics
Summary
Data Model with Entity Framework Core
Getting ready
Installing Entity Framework Core
Data Modeling approaches
Model-First
Database-First
Code-First
Pros
Cons
Taking a choice
Creating Entities
ApplicationUser
Quiz
Question
Answer
Result
Defining relationships
The one-to-many EF Lazy-Load pattern
Setting up the DbContext
Database initialization strategies
Choosing the Database Engine
Updating the appsettings.json file
Creating the Database
Updating Startup.cs
Adding the Initial Migration
The "No executable found matching command dotnet-ef" error
Understanding Migrations
Implementing a Data Seed strategy
Creating a DbSeeder class
Adding the DbSeeder to Startup.cs
Seeding the Database
Updating the QuizController
Introducing Mapster
Installation
Basic usage
Updating the QuizController
Testing the Data Provider
Suggested topics
Summary
Client-Server Interactions
Add, update, and delete quizzes
Updating QuizController
Adapting the client
Adding QuizEditComponent
Activating the Edit mode
Event handlers versus router links
Adding the Edit route
Implementing the Delete feature
A word on Observables
First client-server test
The client-server workflow
Questions, answers, and results
Server-side tasks
QuestionController
AnswerController
ResultController
BaseApiController
Implementing BaseApiController
Client-side tasks
Adding the interfaces
QuestionListComponent
Introducing ngOnChanges()
Why bother?
The template file
Adding the references
QuestionEditComponent
References and routes
AnswerListComponent
AnswerEditComponent
The template file
References and routes
ResultListComponent
Reference and routes
ResultEditComponent
Full-scale test
Suggested topics
Summary
Style Sheets and UI Layout
How bad is it, doc?
Introducing LESS
Style sheet languages
CSS
CSS code sample
What is LESS and why use it?
Variables
Import directives
Nested selectors
Mixins
Extend pseudo-class
LESS docs and support
SASS, Stylus, and other alternatives
Implementing LESS
Installing LESS compiler
Compiling LESS files with Webpack
DIY versus framework-based styling
Do-it-yourself approach
Pros
Cons
Framework-based approach
Pros
Cons
Conclusions
Working with Bootstrap
Changing the theme
Rebuild the Webpack vendor config file
Delete the /wwwroot/dist/ folder
Update the .csproj file
Create the update-webpack.bat file
Testing the new theme
Revising the UI structure
AppComponent
NavMenuComponent
QuizSearchComponent
Registering QuizSearchComponent
The logo SVG file
A quick test
Styling the components
CSS encapsulation
Native encapsulation using Shadow DOM
Disable encapsulation
HomeComponent
QuizListComponent
Another UI test
QuizComponent
Testing it up
QuizEditComponent
Question, answer, and result components
Buttons and icons
Tables and DIVs
Forms and inputs
Full-scale layout test
Suggested topics
Summary
Forms and Data Validation
Data validation
Forms in Angular
Template-Driven forms
The pros
The cons
Model-Driven/Reactive forms
Our first Reactive form
Adding ReactiveFormsModule
Updating QuizEditComponent
Adding validators
Adding shortcuts
Upgrading components
QuestionEditComponent
AnswerEditComponent
ResultEditComponent
Debugging and testing
A look at the Form Model
The pipe operator
Reacting to changes
Observing the Observable
Extending the activity log
Client-side debugging
Forms unit testing
Suggested topics
Summary
Authentication and Authorization
To auth, or not to auth
Authentication
Third-party authentication
The rise and fall of OpenID
OpenID Connect
Authorization
Third-party authorization
Proprietary versus third-party
Proprietary auth with .NET Core
Setting up the .NET Core Identity
Configuring the Identity service
Extending the ApplicationUser
Upgrading the DbContext
Revising the DbSeeder
A word on async tasks, awaits, and deadlocks
Updating the database
Adding the identity migration
Applying the migration
Option #1 - update
Option #2 - drop and recreate
Seeding the data
Authentication methods
Sessions
Tokens
Signatures
Two-factor
Conclusions
Implementing JWT authentication
Add the auth service to the .NET Core Startup class
Updating the AppSettings files
The TokenController
Upgrading the BaseApiController
Reflecting the upgrade on the affected controllers
Adding the TokenController
The TokenRequestViewModel
The TokenResponseViewModel
Testing with Postman
Angular login form
The TokenResponse interface
The AuthService class
Updating the AppModule
The new LoginComponent
First login test
Adding the token to the HTTP request header
The AuthInterceptor class
Adding the HttpInterceptor in the AppModule
Enforcing authorization
Adapting the client
NavMenuComponent
QuizComponent
Shielding the server
Retrieving the current user ID
Client-server auth test
Suggested topics
Summary
Advanced Topics
Token expiration and refresh tokens
What's a refresh token?
Server-side tasks
Adding the token entity
Upgrading the user entity
Upgrading ApplicationDbContext
Applying the EF core migration
Implementing the refresh token
Upgrading TokenResponseViewModel
Upgrading TokenRequestViewModel
Upgrading TokenController
Client-side tasks
Updating the TokenResponse interface
Upgrading AuthService
Adding AuthResponseInterceptor
Add the AuthResponseInterceptor in the AppModule
Testing it up
New user registration
Server-side tasks
UserController
UserViewModel
Client-side tasks
The user interface
RegisterComponent
Custom validator
Template and style sheet files
AppModule
LoginComponent
NavMenu
Testing it up
Third-party authentication
OAuth2 authorization flow
Implicit flow versus explicit flow
Implicit flow pros and cons
Explicit flow pros and cons
Conclusions
Logging in with Facebook
Creating the Facebook app
Implicit flow
Updating TokenController
Adding the GenerateRandomPassword() method
Adding LoginFacebookComponent
Understanding zones
Adding the template file
Updating AppModule
Linking LoginFacebookComponent
Testing it up
Explicit flow
Installing the Authentication.Facebook package
Setting up the Facebook Authentication service
Updating the appsettings.json file
Upgrading TokenController
The ExternalLogin method
Adding SignInManager
The ExternalLoginCallback method
The LoginExternalProvider component
Updating AppModule
Linking LoginFacebookComponent
Testing it up
Suggested topics
Summary
Finalization and Deployment
Switching to SQL Server
Installing SQL Server 2017 Express
Installing SQL Server Management Studio
Configuring the database
Changing the authentication mode
Adding the TestMakerFree database
Adding the TestMakerFree login
Mapping the login to the database
Adding a SQL Server connection string
Working with the Connection Strings
Adding production URL to External Providers
Updating the launchSettings.json file
Publishing our native web application
Creating a Publish profile
FTP Publish Profile
Folder Publish Profile
Publishing our web app
Configuring the web server and IIS
Installing the ASP.NET Core module for IIS
Adding the website
Configuring the Application Pool
Firing up the engine
Troubleshooting
Browser output message
The Web.Config file
Event Viewer
ASP.NET Core Module logging
The Kestrel test
Kestrel Test from Visual Studio
Disable server-side rendering
Suggested topics
Summary
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 8million 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 asHapi, 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 theclient 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 thisbecause 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.
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 themby 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.
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.
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.
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.
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.
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:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
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!
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 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.
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.
ASP.NET Core MVC is a framework that runs on top of the full .NET framework (Windows) or .NET Core (cross-platform), specifically made for building efficient HTTP services that will be able to be reached by a massive range of clients, including web browsers, mobile devices, smart TVs, web-based home automation tools, and more.
Angular is the successor of AngularJS, a world-renowned development framework born with the idea of providing the coder with the toolbox needed to build reactive and cross-platform web-based apps optimized for desktop and mobile. It features a structure-rich template approach based upon a natural, easy-to-write, and readable syntax.
Technically, these two frameworks have little or nothing in common: ASP.NET Core is mostly focused on the server-side part of the web development stack, while Angular is dedicated to cover all the client-side aspects of web applications such as UI and UX. However, they were put together here because they share a common vision--the HTTP protocol is not limited to serving web pages; it can also be used as a viable platform to build web-based APIs to effectively send and receive data. A thought that slowly made its way through the first 20 years of the World Wide Web and is now an undeniable, widely acknowledged statement and also a fundamental pillar of almost every modern web development approach.
As for the reasons behind this perspective switch, there are plenty of good reasons for that, the most important of them being related to the intrinsic characteristics of the HTTP protocol: rather simple to use, and flexible enough to match most development needs of the always-changing environment that the World Wide Web happens to be in. Not to mention how universal it has become nowadays--almost any platform that we can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
From the perspective of a fully-functional web-based application, we can say that the web API interface provided with the ASP.NET Core 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, typically expressed in structured markup languages, such as JSON or XML. As we already said, this is achieved by making good use of the HTTP protocol handled by a publicly-available web server (typically IIS). Similarly, Angular can be described as a modern, feature-rich client-side library that pushes the HTML5 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 JavaScript model.
These assumptions allow us to answer to a simple, yet inevitable question "can we combine the backend strengths of ASP.NET Core's web API with the frontend capabilities of the Angular framework in order to build a modern, feature-rich, and highly versatile web application?
The answer, in short terms, 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 ASP.NET Core and/or Angular can be used to handle each one of them.
To summarize what happened in the ASP.NET world within the last two years is not an easy task; in short words, we can say that we're undoubtedly facing the most important series of changes in the .NET Framework since the year it came to life. ASP.NET Core 1.0, which came out in Q3 2016, was a complete re-implementation of the ASP.NET we knew; the brand new framework unites 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 introduces a fully-featured cross-platform component, also known as .NET Core, shipped with a brand new open source .NET Compiler Platform (currently known as Roslyn), a cross-platform runtime (known as CoreCLR), and an improved x64 Just-In-Time compiler (RyuJIT).
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 former one.
The third and, at the time of writing, the latest 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 newer version features among a number of significant improvements with a huge effort to standardize the shared APIs among the .NET Framework, .NET Core, and Xamarin, making it easy for developers to share and reuse code across the whole .NET ecosystem.
The new release of AngularJS, simply known as Angular, is a complete rewrite of the previous one, entirely based upon TypeScript and ECMAScript 6 specifications.
The choice of not making Angular backward compatible with AngularJS clearly demonstrates the intention of the author's team to adopt a completely new approach--any developer who already knows AngularJS will undoubtedly face a huge number of breaking changes, not only in the code syntax, but also in the way of thinking and designing the client app. Angular is highly modular, component-based, comes with a new and improved dependency injection model and a whole lot of programming patterns its older cousin never heard of.
However, the most important reason we're picking Angular over other excellent JS libraries such as ReactJS and EmberJS is the fact that it already comes out with a huge pack of features out of the box, making it most suited, although maybe not as simple to use than the aforementioned competitors; if we combine that with the consistency given by the TypeScript language, we can say that despite being the youngster, Angular embraced the framework approach more convincingly than the others. This has been confirmed over the course of the past 9 to 12 months, where the project hit two major versions (Angular 2 in Q3 2016 and Angular 4 in Q1 2017), gaining a lot in terms of stability, performances, and features, without losing much in terms of backward compatibility, best practices, and overall approach. All these reasons are solid enough to invest in it, hoping it will continue to keep up with these compelling premises.
Learning to use ASP.NET Core and Angular together would mean being able to work to both the frontend (client side) and backend (server side) of a web application; to put it in other words, it means being able to design, assemble, and deliver a complete product.
Eventually, in order to do that, we'll need to dig through the following:
Backend programming
Frontend programming
UI styling and UX design
Database design, modeling, configuration, and administration
Web server configuration and administration
Web application deployment
At first glance, it can seem that this kind of approach goes against common sense; a single developer should not be allowed to do everything by himself. Every developer knows well that the backend and the frontend require entirely different skills and experiences, so why in the world should we do that?
Before answering the question, we should understand what we really meant when we said "being able to". We don't have to become experts on every single layer of the stack; no one expects us to do so. When we choose to embrace the full-stack approach, what we really need to do is to raise our awareness level throughout the whole stack we're working on; it means that we need to know how the backend works and how it can and will be connected to the frontend. We need to know how the data will be stored, retrieved, and then served through the client; we need to acknowledge the interactions we will need to layer out between the various components that our web application is made of, and we need to be aware of security concerns, authentication mechanisms, optimization strategies, load-balancing techniques, and so on.
This doesn't necessarily mean that we have to have strong skills in all these areas; as a matter of fact, we hardly ever will. Nonetheless, if we want to pursue a full-stack approach, we need to understand the meaning, role, and scope of any of them, and possibly, be able to work there whenever we need to.
In order to demonstrate how ASP.NET Core and Angular can work together to their full extent, we couldn't think of anything better than building a Single-Page Application(SPA) project. The reason for that is quite obvious--there is no better approach to show some of the best features they have to offer nowadays. We'll have the chance to work with modern interfaces and patterns such as HTML5 pushState API, webhooks, data transport-based requests, dynamic web components, UI data bindings, and a stateless, AJAX-driven architecture capable to flawlessly encompass all of these.
To put it briefly, a SPA is a web-based application that struggles to provide the same user experience as a desktop application. If we consider the fact that all SPAs are still served through a web server and thus accessed by web browsers just like any other standard website, we can easily understand how that desired outcome can only be achieved by changing some of the default patterns commonly used in web development, such as resource loading, DOM management, and UI navigation. In a good SPA, both contents and resources--HTML, JavaScript, CSS, and such–-are either retrieved within a single page load or dynamically fetched when needed; this also means that the page doesn't reload or refresh, it just changes and adapts in response to user actions, performing the required server-side calls behind the scenes.
These are some of the key features provided by a competitive SPA nowadays:
No server-side roundtrips
: A competitive SPA is able to redraw any part of the client UI without requiring a full server-side round trip to retrieve a full HTML page. This is mostly achieved by implementing a
Separation of Concerns
design principle, which means that the data will be separated from the presentation of data using a model layer that will handle the former, and a view layer that reads from the latter.
Efficient routing
: A competitive SPA is able to keep track of the user current state and location during its whole navigation experience using organized, JavaScript-based routers. This is usually accomplished in one of two ways: the
Hashbang
technique, or the HTML5
History API
usage. We'll talk about either one of them in
Chapter 2
,
Backend with .NET Core
.
Performance and flexibility
: A competitive SPA usually transfers all of its UI to the client, thanks to its JavaScript SDK of choice (Angular, JQuery, Bootstrap, or any such). This is often good for network performance, as increasing client-side rendering and offline processing reduces the UI impact over the network. However, the real deal brought by this approach is the flexibility granted to the UI, as the developer will be able to completely rewrite the application frontend with little-to-no impact on the server, aside from a few of the static resource files.
The list can easily grow, as these are only some of the major advantages of a properly-designed, competitive SPA. These aspects play a major role nowadays, as many business websites and services are switching from their traditional Multi-Page Application mindset (MPA) to full-committed or hybrid SPA-based approaches. The latter ones, which have been increasingly popular since 2015, are commonly called Native Web Applications (NWA), because they tend to implement a number of small-scale, single-page modules bound together upon a multipage skeleton rather than building a single, monolithic SPA.
Not to mention the fact that there are also a lot of enterprise-level SPAs and Native Web Applications flawlessly serving thousands of users every day, want to name a few? WhatsApp Web and Teleport Web, Flickr, plus a wide amount of Google web services, including Gmail, Contacts, Spreadsheet, Maps, and more. These services, along with their huge user base, are the ultimate proof that we're not talking about a silly trend that will fade away with time; conversely, we're witnessing the completion of a consolidated pattern that's definitely meant to stay.
One of the most interesting, yet underrated concepts brought out by many modern agile software development frameworks, such as SCRUM, is the importance given to the meanings and definitions of roles; among these, there's nothing as important as the Product Owner, also known as the customer in Extreme Programming methodology or customer representative elsewhere. They're the one who brings to the development table the expectations we'll struggle to satisfy. They will tell us what's most important to deliver and when they will prioritize our work based on its manifest business value rather than its underlying architectural value; they'll be entitled by the management to take decisions and make tough calls, which is sometimes great, sometimes not; this will often have a great impact on our development schedule. To cut it short, they're the one in charge of the project; that's why, in order to deliver a web application matching their expectancy, we'll need to understand their vision and feel it as if it were ours.
This is always true, even if the project's Product Owner is our dad, wife, or best friend: that's how it works.
Now that we made it clear, let's take a look at some of the most common Product Owner's expectations for a typical web-based SPA project. We ought to see if the choice of using ASP.NET Core and Angular will be good enough to fulfill each one of them.
Early release(s
): No matter if we're selling a bunch of salad or web-based services, the customer will always want to see what he's buying. If we're using
SCRUM
, we'll have to release a potentially-shippable product at the end of each sprint; we'll have Milestones
in a Waterfall-based approach
, and so on. One thing is for sure--the best thing we can do in order to efficiently organize our development efforts will be to adopt an iterative and/or modular-oriented approach. ASP.NET Core and Angular, along with the strong Separation of Concerns granted by their underlying
MVC
or
MVVM
based patterns, will gracefully push us into the mindset needed to do just that.
GUI over backend
: We'll often be asked to work to the GUI and frontend functionalities, because that will be the only real viewable and measurable thing for the customer. This basically means that we'll have to mock the data model and start working on the frontend as soon as possible, delaying everything that relies under the hood, even if that means leaving it empty; we can say that the hood is what we need the most. Note that this kind of approach is not necessarily bad; by all means, we're not tying up the donkey where the (product) owner wants. On the contrary, the choice of using ASP.NET Core along with Angular will grant us the chance to easily decouple the presentation layer and the data layer, implementing the first and mocking the latter, which is a great thing to do. We'll be able to see where we're going before wasting valuable time or being forced to make potentially wrong decisions. ASP.NET Core's Web API interface will provide the proper tools to do that by allowing us to create a sample web application skeleton in a matter of seconds using
Visual Studio
Controller templates and in-memory data contexts powered by
Entity Framework 6
, which we'll be able to access using entity models and code-first. As soon as we do that, we'll be able to switch to GUI design using the Angular presentation layer toolbox as much as we want until we reach the desired results; once we're satisfied, we'll just need to properly implement the Web API controller interfaces and hook up the actual data.
Fast completion
: None of the preceding will work unless we also manage to get everything done in a reasonable time span. This is one of the key reasons to choose to adopt a server-side framework and a client-side framework working together with ease. ASP.NET Core and Angular are the tools of choice not only because they're both built on solid, consistent ground, but also because they're meant to do precisely that--get the job done on their respective side and provide a usable interface to the other partner.
Adaptability
: As stated by the Agile manifesto, being able to respond to change requests is more important than following a plan. This is especially true in software development, where we can even claim that anything that cannot handle changes is a failed project. That's another great reason to embrace the Separation of Concerns enforced by our two frameworks of choice, as this grants the developer ability to manage--and even welcome, to some extent--most of the layout or structural changes that will be expected during the development phase.
That's about it. Note that we didn't cover everything here, as it will be impossible without knowing an actual assignment. We just tried to give an extensive answer to the following general questions: if we were to build a SPA, would ASP.NET Core and Angular be an appropriate choice? The answer is undoubtedly yes, especially when used together.
Does it mean that we're done already? Not a chance, as we have no intention of taking this assumption for granted. Conversely, it's time for us to demonstrate it by ceasing to speak in general terms and starting to put things in motion.
What we need now is to conceive a suitable test case scenario similar to the ones we will eventually have to deal with--a fully-featured, production-ready Single-Page Application project, complete with all the core aspects we would expect from a potentially shippable product.
In order to do this, the first thing we need to do is to become our own customer for a minute and come up with an idea, a vision to share with our own other self. We'll then be able to put our developer shoes back on and split our abstract plan into a list of items we'll need to implement; these will be the core requirements of our own project. Finally, we'll set up our workstation by getting the required packages, adding the resource files, and configuring both the ASP.NET Core and Angular frameworks into the Visual Studio IDE.
If we're going to demonstrate the key features of ASP.NET Core and Angular in a practical way such as committing ourselves into a full-stack SPA project and bringing it to life, we definitely need to go for a project where they can shine the most.
That's why we can't really take into consideration most presentation-oriented websites such as demos, product galleries, corporate or marketing showcases, photo/video/media reels, blogs, and the likes; we need something that can make better use of the asynchronous and parallel request processing capabilities of both frameworks, bringing them both toward their full extent; in order to fulfill these expectations, we would rather think about something similar to a CMS engine, a community-driven wiki, or even better, an interactive web application featuring some strong client-server interactions such as auth tokens, RESTful data transfer, and push notifications.
The latter seems to be the most appropriate, as it will mean going through a number of not-so-trivial implementation challenges while keeping the expected amount of source code small enough to fit into this book.
The application we will build won't be just a shallow demonstration, we won't throw some working code here and there and expect the reader to connect the dots. Our objective is to create a solid, realistic web application using the frameworks we've chosen while following the current development best practices.
Each chapter will be dedicated to a single core aspect; if you feel like you already know your way there, feel free to skip to the next one. Conversely, if you're willing to follow us through the whole loop, you'll have a great journey through the most useful aspects of ASP.NET Core and Angular and how they can work together to deliver the most common and useful web-development tasks, from the most trivial one to the more complex beasts. It's an investment that will pay dividends, as it will leave you with a maintainable, extensible, and well-structured project, plus the knowledge needed to build your own.
To avoid making things too boring, we'll try to pick an enjoyable theme that will also have some usefulness in the real world; do you know anything about personality tests? They are questionnaires designed to reveal aspects of an individual's nature, trace a psychological makeup, or identify similarities with other notable real or fictional characters. The web is nothing less than full of them, featuring the most popular themes from the movie and entertainment industry--which Game of Thrones character are you?Are you a Jedi or a Sith? and so on.
I hope you like these kinds of questionnaires because we will build a web application that will allow users from anywhere in the world to build their own test(s). In order to do so, we'll put together a wizard-like tool that can be used to add questions and answers, upload images, choose a scoring method, assign a score to each answer, and define the possible outcomes/results. At the end of the wizard, the user will receive a unique URL that can be used to take the test and/or share it via email, blog/forum posts, IMs, social networks, and so on.
Ultimately, they will have a small yet useful web application featuring a server-side engine powered by ASP.NET Core and a web client mostly built using Angular.
The chosen name? TestMakerFree, also known as www.testmakerfree.com; needless to say, the free word means that our application will be free of charge. Luckily enough, the domain was still available at the time of writing this book. If you go there now, you'll be able to see the final outcome of what we will build from scratch during the course of this book; don't do that if you don't like spoilers, as it can ruin some of your fun.
Let's try to visualize how our application should work.
Our users will definitely need to register, so we'll be able to grant them the ownership of their own tests; once done, they will be able to create a new test. Each test will have a name, a description, a list of questions, and a series of possible results; each question will have a descriptive text, a list of answers, and an optional image; each answer will have a descriptive text, an optional image, and a list of score points; and each result will have a descriptive text and a score value.
The score points and the score value will be extensively discussed later on. For now, we'll just state the obvious--whenever a user completes the test, the sum of score points among all the given answers will be matched with the score value given to each possible result in order to determine the final outcome. The numbers will be shown or hidden to the user as per the test owner's choice.
That's about it. It might sound easy or not, depending on our programming experience, but one thing is certain--we got a plan.
Now that we have identified the key features, let's break them down into a list of development topics:
Routing
: The application will have to properly respond to client requests, that is, routing them according to what they're up to.
Data model
: We'll definitely adopt a database engine to store our tests, questions, answers, and so on; hence, we'll also need to develop the proper tools to access it in a modern, fashionable way. In order do so, we need to define our data architecture by setting up data repositories and domain entities that will be handled by the server and hooked to Angular through the most suited ASP.NET Core interface to handle HTTP communications--the
Controller
class.
Controllers
: From an MVC-based architectural perspective, one of the main differences between multi-page and single-page applications is that the former's
Controllers
are designed to return views, while the latter ones, also known as
API Controllers
, mostly return serialized data. These are what we will need to implement to put Angular components in charge of the presentation layer.
Angular components
: Switching to the client side, we will need to define a set of components to handle UI elements and state changes. As we probably already know, components are the most fundamental elements in Angular, replacing the AngularJS controllers and scopes. We'll get to know more about them soon enough.
Authentication
: Soon enough, we'll have to deal with user login and registration. We'll take care of that by adding a membership context, so we'll be able to limit
CRUD
operations to authenticated users only, keeping track of each user action, requiring registration to access some pages/views, and so on.
UI styling
: We will take our time to come to that, as we will stick to the core topics first, but we'll definitely get there eventually; the initial ugliness of our web client will flourish into a responsive, good-looking, and mobile-friendly user interface.
These will be our main development challenges. As we said earlier, we definitely have to understand how to properly handle each one of them, or we won't be able to succeed. Hence, let's get to work without further ado!
The following chapters will guide us through the journey; we'll also cover other important aspects such as SEO, Security, Performance Issues, Best Coding Practices, and Deployment, as they will be very important later on.
