Book Image

ASP.NET Core and Angular 2

By : Valerio De Sanctis
Book Image

ASP.NET Core and Angular 2

By: Valerio De Sanctis

Overview of this book

<p>Writing code is about striking a balance between maintainability and productivity—how quickly you can write it against how much more you have to write in the future. This is a guide to doing just that by combining the impressive capabilities of ASP.NET Core and Angular 2. It shows you how to successfully manage an API and use it to support and power a dynamic single-page application.</p> <p>We'll show you how to construct your data model and manage routing and redirects before wrapping it up and styling it, all with the help of ASP.NET and Angular 2. You'll also learn how to optimize your application for SEO, check and secure any vulnerabilities, implement a viable authentication mechanism and, last but not least, use the proper tools and strategies for successful deployment. From readable URIs to OData retrieval and authentication patterns, we'll make sure you have all the technical knowledge you need and, more importantly, bring it all together so you can focus on what's important: a high-quality application that performs for users.</p>
Table of Contents (16 chapters)
ASP.NET Core and Angular 2
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Preface

It is common knowledge among many seasoned web developers that building a website from scratch 15 years ago was a rather simple task. To begin with, we didn’t have to deal with the insane amount of screen resolutions brought by big-size monitors, ultra-high resolutions, and mobile devices; we could avoid the urge of learning a lot of (back then) "experimental" stuff such as AJAX, JSON, and XMLHttpRequest, as the established DHTML-based techniques we already knew were more than enough to get the job done; our simple, quick 'n' dirty JavaScript hacks could easily shine among friends and colleagues without being embarrassed by cross-platform JS libraries such as jQuery (2006); we didn’t have to implement time-consuming and/or knowledge-demanding features such as login with Facebook, Sharing buttons, SEO meta tags, Twitter Cards and RSS feeds because they were either not there yet or not so important. On top of all that, there still weren’t that many fully-featured, great-looking, award-winning CMS solutions such as Drupal (2001), Wordpress (2003), and Joomla (2005) to compare our results with.

Sounds pretty reasonable, right? Except it’s not. The Web is always changing, just like the rest of the world: the complexity level of the average website is constantly increasing because the usage is more diversified, widespread and intense, however, such growing excitement was also a great thing for those who wanted to make a living out on building web applications, assuming they had the guts to keep studying, communicating, and living the blowing storm of new technologies behind these winds of change. As seasoned developers, we should be able to cope with such simple, yet inevitable truth, adapting ourselves before and better than our customers instead of being trampled by their increasing demands.

The main purpose of this book is to demonstrate that is still possible to develop great web applications from scratch, providing that we use the proper tools and have the patience to understand how we can blend them together to achieve what we want. Luckily enough, the insane amount of additional work required nowadays can be mitigated by a lot of powerful frameworks that make their way through the development scene: we’re talking of server-side runtime environments like ASP.NET and Node.js and also of many client-side frameworks such as Bootstrap, jQuery, React, AngularJS and Angular 2. We chose to focus on two of them – ASP.NET Core to cover the server-side aspects, Angular 2 to deal with the client-side not only for their stunning set of features and elegant design, but also because they happen to have something revolutionary in common: they are both a complete rewrite of their massively-popular previous installments, who played a leading role in their respective field.

Why a development team should do that? What’s the purpose of reinvent their own widely-acknowledged wheel despite it still rocks? The answer most likely lies in what we said earlier: in an ever-changing world such as the one we’re living in we need to be humble and wise enough to keep moving forward, embracing – sometimes even enforcing – the iterative processes required to forge better tools for building a more complex, yet also more enticing World Wide Web.

The guys behind ASP.NET and Angular were brave enough to accept the challenge: after a few months of unstable releases and breaking interface changes it definitely seems that their choice was worth the effort, as they’re about to hit a decisive score.

What about you?

What this book covers

Chapter 1, Getting Ready, introduces the ASP.NET Core and Angular 2 frameworks, explaining how they can effectively be used to build a feature-rich, modern SPA. 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, together with its required packages and components, up to a buildable and running app skeleton.

Chapter 2, ASP.NET Controllers and Server-Side Routes, explains how we can interchange Json data between a server-side .NET Controller and a client-side Angular 2 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, Angular 2 Components and Client-Side Routing, focuses about the client-side aspects of our SPA: the reader will learn how to fetch JSON objects with Angular 2 core classes and show the retrieved data on screen using the Angular 2 Template Syntax. We will also explain how the client-side routing works in a SPA and what we need do to implement a viable routing pattern for our project using the PathLocationStrategy.

Chapter 4, The Data Model, is dedicated to the building of a proper, DBMS-based Data Model using Entity Framework Core. The reader will learn how to install and properly configure the required EF Core packages: we will also explain how to properly implement them to build a list of Entities and persist them into a stable Database structure using the Code-First approach.

Chapter 5, Persisting Changes, will explain how to update the application code to make full usage of the EF Core entities defined in Chapter 4, The Data Model. The reader will learn how to fetch and persist the application data by using the Database instead of the sample mocking methods.

Chapter 6, Applying Styles, will introduce LESS, a powerful dynamic stylesheet 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 front-end UI.

Chapter 7, Authentication and Authorization, will guide the reader through the most relevant auth-related concepts for building a web application. The reader will learn how to implement a sample Token-based authentication provider and also how to properly add and configure it throughout the existing Entity Framework entities, .NET core services and HTTP middleware list.

Chapter 8, Third-Party Authentication and External Providers, further expands the authentication and authorization topics introducing OpenIddict, an open-source .NET library based upon the AspNet OpenID Connect Server (ASOS) that can be used to handle internal and external auth providers. The reader will learn how to install OpenIddict and configure it to support Facebook, Google and Twitter authentication.

Chapter 9, User Registration and Account Edit, is dedicated to account-related features such as user registration and edit account mechanism. The reader will learn how to properly handle such requests by implementing a dedicated .NET Core Controller together with a versatile Angular 2 Model-Driven form.

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 its 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; he 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 2015 with Update 3 (or newer): any version will work, including the freely available Community Edition.

  • Microsoft SQL Server 2014 (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.

  • All ASP.NET, Angular 2, JavaScript and CSS packages used throughout the book are open-source and freely available for download using Visual Studio package managers such as NuGet, MyGet, NPM and Bower.

Who this book is for

This book is for seasoned ASP.NET developers who already know about ASP.NET Core and Angular 2, but want 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: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

<%@ taglib prefix="c" 
      uri="http://java.sun.com/jsp/jstl/core"%> 
 
      <!DOCTYPE html> 
      <html lang="en"> 
           <head> 
                <meta charset="utf-8"> 
                <meta http-equiv="X-UA-Compatible" 
                 content="IE=edge"> 
                <meta name="viewport" content="width=device-width, 
                 initial-scale=1">

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

<dependency> 
   <groupId>org.springframework</groupId> 
   <artifactId>spring-webmvc</artifactId> 
   <version>4.2.2.RELEASE</version> 
</dependency>

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

Java(TM) SE Runtime Environment (build 1.8.0_91-b15)

 Java HotSpot(TM) 64-Bit Server VM (build 25.91-b15, mixed mode)

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: "Click on the Java Platform (JDK) 8u91/8u92 download link"

Note

Warnings or important notes appear in a box like this.

Tip

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 e-mail [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 e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

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/ASPdotNET-Core-and-Angular-2. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book 

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ASPdotNETCoreAndAngular2_ColorImages.pdf.

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.