Essential Angular for ASP.NET Core MVC 1st Edition Adam Freeman - Download the ebook and start exploring right away
Essential Angular for ASP.NET Core MVC 1st Edition Adam Freeman - Download the ebook and start exploring right away
com
https://ebookmeta.com/product/essential-angular-for-asp-net-
core-mvc-1st-edition-adam-freeman/
OR CLICK HERE
DOWLOAD EBOOK
https://ebookmeta.com/product/pro-entity-framework-core-2-for-asp-net-
core-mvc-1st-edition-adam-freeman/
ebookmeta.com
https://ebookmeta.com/product/pro-asp-net-core-7-tenth-edition-
meap-v03-adam-freeman/
ebookmeta.com
https://ebookmeta.com/product/pro-asp-net-core-7-meap-v03-10th-
edition-adam-freeman/
ebookmeta.com
https://ebookmeta.com/product/iranian-women-in-the-memoir-comparing-
reading-lolita-in-tehran-and-persepolis-1-and-2-1st-edition-emira-
derbel/
ebookmeta.com
Given 1st Edition Amy Pennza
https://ebookmeta.com/product/given-1st-edition-amy-pennza/
ebookmeta.com
https://ebookmeta.com/product/mountain-daddy-s-milk-honey-spice-in-
the-mountains-book-1-1st-edition-elena-dawne/
ebookmeta.com
https://ebookmeta.com/product/property-investing-essentials-for-
dummies-australian-edition-nicola-mcdougall/
ebookmeta.com
https://ebookmeta.com/product/the-artist-1st-edition-sheri-lewis-wohl/
ebookmeta.com
https://ebookmeta.com/product/digital-imaging-of-artefacts-
developments-in-methods-and-aims-1st-edition-kate-kelley/
ebookmeta.com
Pietro Monte s Collectanea The Arms Armour and Fighting
Techniques of a Fifteenth Century Soldier 6 Armour and
Weapons Jeffrey L Forgeng
https://ebookmeta.com/product/pietro-monte-s-collectanea-the-arms-
armour-and-fighting-techniques-of-a-fifteenth-century-
soldier-6-armour-and-weapons-jeffrey-l-forgeng/
ebookmeta.com
Essential
Angular for
ASP.NET Core MVC
—
Adam Freeman
www.allitebooks.com
Essential Angular for
ASP.NET Core MVC
Adam Freeman
www.allitebooks.com
Essential Angular for ASP.NET Core MVC
Adam Freeman
London, UK
ISBN-13 (pbk): 978-1-4842-2915-6 ISBN-13 (electronic): 978-1-4842-2916-3
DOI 10.1007/978-1-4842-2916-3
Library of Congress Control Number: 2017949481
Copyright © 2017 by Adam Freeman
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material
contained herein.
Cover image by Freepik (www.freepik.com)
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Gwenan Spearing
Development Editor: Laura Berendson
Technical Reviewer: Fabio Claudio Ferracchiati
Coordinating Editor: Mark Powers
Copy Editor: Kim Wimpsett
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484229156. For more
detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
www.allitebooks.com
Dedicated to my lovely wife, Jacqui Griffyth.
(And also to Peanut.)
www.allitebooks.com
Contents at a Glance
■
■Chapter 1: Understanding Angular and ASP.NET Core MVC����������������������������������� 1
■
■Chapter 2: Getting Ready��������������������������������������������������������������������������������������� 5
■
■Chapter 3: Creating the Project��������������������������������������������������������������������������� 21
■
■Chapter 4: Creating the Data Model�������������������������������������������������������������������� 43
■
■Chapter 5: Creating a Web Service���������������������������������������������������������������������� 69
■
■Chapter 6: Completing the Web Service������������������������������������������������������������ 103
■
■Chapter 7: Structuring an Angular Application������������������������������������������������� 135
■
■Chapter 8: Creating the Store���������������������������������������������������������������������������� 159
■
■Chapter 9: Completing the Angular Store���������������������������������������������������������� 187
■
■Chapter 10: Creating Administration Features�������������������������������������������������� 227
■
■Chapter 11: Securing the Application���������������������������������������������������������������� 251
■
■Chapter 12: Preparing for Deployment�������������������������������������������������������������� 279
Index��������������������������������������������������������������������������������������������������������������������� 295
www.allitebooks.com
Contents
■
■Chapter 1: Understanding Angular and ASP.NET Core MVC����������������������������������� 1
Who Is This Book For?������������������������������������������������������������������������������������������������������ 1
What Does This Book Cover?�������������������������������������������������������������������������������������������� 1
What Doesn’t This Book Cover?��������������������������������������������������������������������������������������� 1
What Do You Need to Know?�������������������������������������������������������������������������������������������� 2
Are There Lots of Examples?�������������������������������������������������������������������������������������������� 2
Where Can You Get the Example Code?��������������������������������������������������������������������������� 4
Where Can You Get Corrections for This Book?���������������������������������������������������������������� 4
Contacting the Author������������������������������������������������������������������������������������������������������� 4
Summary�������������������������������������������������������������������������������������������������������������������������� 4
■
■Chapter 2: Getting Ready��������������������������������������������������������������������������������������� 5
Getting Ready on Windows����������������������������������������������������������������������������������������������� 5
Installing .NET Core�������������������������������������������������������������������������������������������������������������������������������� 6
Installing Node.js������������������������������������������������������������������������������������������������������������������������������������ 6
Installing Git�������������������������������������������������������������������������������������������������������������������������������������������� 8
Installing Docker������������������������������������������������������������������������������������������������������������������������������������� 8
Installing Visual Studio 2017���������������������������������������������������������������������������������������������������������������� 10
Installing Visual Studio Code���������������������������������������������������������������������������������������������������������������� 11
vii
www.allitebooks.com
■ Contents
Installing Git������������������������������������������������������������������������������������������������������������������������������������������ 13
Installing Docker����������������������������������������������������������������������������������������������������������������������������������� 14
Installing Visual Studio Code���������������������������������������������������������������������������������������������������������������� 15
Summary������������������������������������������������������������������������������������������������������������������������ 19
■
■Chapter 3: Creating the Project��������������������������������������������������������������������������� 21
Preparing to Create a Project����������������������������������������������������������������������������������������� 21
Creating the Project�������������������������������������������������������������������������������������������������������� 22
Creating the Angular Part of the Project����������������������������������������������������������������������������������������������� 22
Creating the ASP.NET Core MVC Part of the Project������������������������������������������������������������������������������ 24
Configuring the Project������������������������������������������������������������������������������������������������������������������������� 25
Removing Files������������������������������������������������������������������������������������������������������������������������������������� 30
Updating the Controller, Layout, and View�������������������������������������������������������������������������������������������� 30
Summary������������������������������������������������������������������������������������������������������������������������ 41
■
■Chapter 4: Creating the Data Model�������������������������������������������������������������������� 43
Preparing for This Chapter��������������������������������������������������������������������������������������������� 43
Starting the Data Model������������������������������������������������������������������������������������������������� 44
Preparing the Database Server������������������������������������������������������������������������������������������������������������ 44
Creating the ASP.NET Core MVC Data Model���������������������������������������������������������������������������������������� 46
Starting the Angular Data Model���������������������������������������������������������������������������������������������������������� 54
viii
www.allitebooks.com
■ Contents
Summary������������������������������������������������������������������������������������������������������������������������ 68
■
■Chapter 5: Creating a Web Service���������������������������������������������������������������������� 69
Preparing for This Chapter��������������������������������������������������������������������������������������������� 70
Introducing a Web Service��������������������������������������������������������������������������������������������� 71
Understanding RESTful Web Services�������������������������������������������������������������������������������������������������� 71
Creating the Web Service��������������������������������������������������������������������������������������������������������������������� 72
Using the Web Service in the Angular Application�������������������������������������������������������������������������������� 74
Loading Related Data��������������������������������������������������������������������������������������������������������������������������� 81
ix
www.allitebooks.com
■ Contents
Summary���������������������������������������������������������������������������������������������������������������������� 134
■
■Chapter 7: Structuring an Angular Application������������������������������������������������� 135
Preparing for This Chapter������������������������������������������������������������������������������������������� 136
Using the Data Model for Component Cooperation������������������������������������������������������ 137
Creating the Display Component�������������������������������������������������������������������������������������������������������� 137
Creating the Filter Component������������������������������������������������������������������������������������������������������������ 140
Applying the New Components���������������������������������������������������������������������������������������������������������� 141
Understanding the Application Structure�������������������������������������������������������������������������������������������� 143
Adding Another Component���������������������������������������������������������������������������������������������������������������� 143
Summary���������������������������������������������������������������������������������������������������������������������� 158
■
■Chapter 8: Creating the Store���������������������������������������������������������������������������� 159
Preparing for This Chapter������������������������������������������������������������������������������������������� 160
Starting the Product Selection Feature������������������������������������������������������������������������ 161
Blocking Out the Feature Components����������������������������������������������������������������������������������������������� 161
Configuring the Angular URL Routes�������������������������������������������������������������������������������������������������� 167
Removing the Layout Header������������������������������������������������������������������������������������������������������������� 167
x
www.allitebooks.com
■ Contents
Summary���������������������������������������������������������������������������������������������������������������������� 186
■
■Chapter 9: Completing the Angular Store���������������������������������������������������������� 187
Preparing for This Chapter������������������������������������������������������������������������������������������� 187
Creating the Shopping Cart������������������������������������������������������������������������������������������ 188
Extending the Angular Data Model����������������������������������������������������������������������������������������������������� 188
Registering the Cart as a Service������������������������������������������������������������������������������������������������������� 190
Wiring Up the Buttons������������������������������������������������������������������������������������������������������������������������� 191
Creating the Cart Summary Component��������������������������������������������������������������������������������������������� 191
Displaying the Cart Detail������������������������������������������������������������������������������������������������������������������� 193
www.allitebooks.com
■ Contents
Summary���������������������������������������������������������������������������������������������������������������������� 226
■
■Chapter 10: Creating Administration Features�������������������������������������������������� 227
Preparing for This Chapter������������������������������������������������������������������������������������������� 227
Adding Administration Features����������������������������������������������������������������������������������� 229
Creating the Administration Components������������������������������������������������������������������������������������������� 230
Summary���������������������������������������������������������������������������������������������������������������������� 249
■
■Chapter 11: Securing the Application���������������������������������������������������������������� 251
Preparing for This Chapter������������������������������������������������������������������������������������������� 251
Restricting Access to Action Methods�������������������������������������������������������������������������� 253
Restricting Access to Suppliers���������������������������������������������������������������������������������������������������������� 253
Restricting Access to Orders�������������������������������������������������������������������������������������������������������������� 253
Restricting Access to Products����������������������������������������������������������������������������������������������������������� 254
Testing the Restrictions���������������������������������������������������������������������������������������������������������������������� 257
xii
■ Contents
Summary���������������������������������������������������������������������������������������������������������������������� 278
■
■Chapter 12: Preparing for Deployment�������������������������������������������������������������� 279
Preparing for This Chapter������������������������������������������������������������������������������������������� 279
Preventing Cross-Site Request Forgery Attacks���������������������������������������������������������� 280
Enabling Anti-CSRF Tokens����������������������������������������������������������������������������������������������������������������� 281
Sending and Receiving Anti-CSRF Tokens������������������������������������������������������������������������������������������ 283
Summary���������������������������������������������������������������������������������������������������������������������� 294
Index��������������������������������������������������������������������������������������������������������������������� 295
xiii
About the Author
xv
About the Technical Reviewer
Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft
technologies. He works for BluArancio (www.bluarancio.com). He is a Microsoft Certified Solution
Developer for .NET, a Microsoft Certified Application Developer for .NET, a Microsoft Certified Professional,
and a prolific author and technical reviewer. Over the past ten years, he’s written articles for Italian and
international magazines and coauthored more than ten books on a variety of computer topics.
xvii
CHAPTER 1
Understanding Angular
and ASP.NET Core MVC
This book is about using Angular and ASP.NET Core MVC together to build rich applications. Individually,
each of these frameworks is powerful and feature-rich, but using them together combines the dynamic
flexibility of Angular with the solid infrastructure of ASP.NET Core MVC.
I have written other books that provide the deep-dive for each framework. If you are unfamiliar with
ASP.NET Core MVC development, then you should read Pro ASP.NET Core MVC before this book. Once
you have mastered the basics of Angular development, then Pro Angular provides a comprehensive tour of
Angular features.
Listing 1-1. The Contents of the CheckoutState.cs File in the Models/BindingTargets Folder
namespace SportsStore.Models.BindingTargets {
This is a listing from Chapter 9, and the caption tells you that it refers to a file called CheckoutState.cs,
which can be found in the Models/BindingTargets folder. A project that combines Angular and ASP.NET
Core MVC can have a lot of files, and it is important to change the right one. (Don’t worry about the code in
this listing or the folder structure for the moment.)
When I make changes to a file, I show the altered statements in bold, like in Listing 1-2.
Listing 1-2. Adding Methods in the SessionValuesController.cs File in the Controllers Folder
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SportsStore.Models;
using SportsStore.Models.BindingTargets;
namespace SportsStore.Controllers {
[Route("/api/session")]
public class SessionValuesController : Controller {
2
Chapter 1 ■ Understanding Angular and ASP.NET Core MVC
[HttpGet("cart")]
public IActionResult GetCart() {
return Ok(HttpContext.Session.GetString("cart"));
}
[HttpPost("cart")]
public void StoreCart([FromBody] ProductSelection[] products) {
var jsonData = JsonConvert.SerializeObject(products);
HttpContext.Session.SetString("cart", jsonData);
}
[HttpGet("checkout")]
public IActionResult GetCheckout() {
return Ok(HttpContext.Session.GetString("checkout"));
}
[HttpPost("checkout")]
public void StoreCheckout([FromBody] CheckoutState data) {
HttpContext.Session.SetString("checkout",
JsonConvert.SerializeObject(data));
}
}
}
This is another listing from Chapter 9, and the bold statements indicate the changes that you should
make if you are following the example.
I use two different conventions to avoid repeating code in long files. For long class files, I omit methods
and properties, like in Listing 1-3.
Listing 1-3. Restricting Access in the SupplierValuesController.cs File in the Controllers Folder
using Microsoft.AspNetCore.Mvc;
using SportsStore.Models;
using SportsStore.Models.BindingTargets;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
namespace SportsStore.Controllers {
[Route("api/suppliers")]
[Authorize(Roles = "Administrator")]
public class SupplierValuesController : Controller {
private DataContext context;
This listing from Chapter 11 shows you that a new attribute must be applied to the
SupplierValuesController class but doesn’t list the constructor or other methods, which remain
unchanged.
3
Chapter 1 ■ Understanding Angular and ASP.NET Core MVC
This is the convention that I follow to highlight changes to a region within a file, such as when new
statements are required in a single method in a long file, like in Listing 1-4.
Listing 1-4. Configuring the JSON Serializer in the Startup.cs File in the SportsStore Folder
...
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration
["Data:Products:ConnectionString"]));
services.AddMvc().AddJsonOptions(opts => {
opts.SerializerSettings.ReferenceLoopHandling
= ReferenceLoopHandling.Serialize;
opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
}
...
This is a listing from Chapter 5 that requires a new statement in the ConfigureServices method of the
Startup class, which is defined in the Startup.cs file in the SportsStore folder, while the rest of the file
remains unchanged.
Summary
In this chapter, I described the purpose and content of this book, explained how you can download the
project used for each chapter of the book, and described the conventions I use in the code listings.
In the next chapter, I show you how to set up your development environment in preparation for creating a
combined Angular and ASP.NET Core MVC project in Chapter 3.
4
CHAPTER 2
Getting Ready
In this chapter, I explain how to set up the tools and packages required for Angular and ASP.NET Core MVC
development. There are instructions for Windows, Linux, and macOS, which are the three operating systems
that can be used for .NET Core projects. For quick reference, Table 2-1 lists the packages and explains their
purpose. Follow the instructions for your preferred operating system to install the tools that are required for
the rest of this book.
Name Description
Visual Studio Visual Studio is the Windows-only IDE that provides the full-featured development
experience for .NET.
Visual Studio Code Visual Studio Code is a lightweight IDE that can be used on Windows, macOS,
and Linux. It doesn’t provide the full range of features of the Windows-only Visual
Studio product but is well-suited to Angular and ASP.NET Core MVC development.
.NET SDK The .NET Core Software Development Kit includes the .NET runtime for
executing .NET applications and the development tools required to build and test
applications.
Node.js Node.js is used for many client-side development tools, delivered through its
package manager, NPM. It is used to prepare the Angular code for the browser.
Git Git is a revision control system. It is used by some of the NPM packages commonly
used for client-side development.
Docker The Docker package includes the tools required to run applications in containers.
The databases in this book are run inside Docker containers, which makes them
easy to install and manage.
dotnet --version
The output from this command will display the latest version of the .NET Core runtime that is installed.
If you have installed only the version specified, this will be 1.0.4.
Installing Node.js
Node.js is a runtime for server-side JavaScript applications and has become a popular platform for
development tools. In this book, Node.js is used by the Angular build tools to compile and prepare the code
that ASP.NET Core MVC will send to the browser.
It is important that you download the same version of Node.js that I use throughout this book. Although
Node.js is relatively stable, there are still breaking API changes from time to time, and they may stop the
examples from working. To install Node.js, download and run the installer from https://nodejs.org/dist/
v6.10.3/node-v6.10.3-x64.msi. This is the installer for version 6.10.3. You may prefer more recent releases
for your projects, but you should stick with the 6.10.3 release for the rest of this book. Run the installer and
ensure that the npm package manager and Add to PATH options are selected, as shown in Figure 2-1.
6
Chapter 2 ■ Getting Ready
The NPM package manager is used to download and install Node packages. Adding Node.js to the PATH
ensures that you can use the Node.js runtime at the command prompt just by typing node. Once you have
completed the installation, open a new command prompt and run the command shown in Listing 2-2.
node -v
You should see the following version number displayed: v6.9.2. If the installation has been successful,
then proceed to the “Installing NPM Packages” section.
Installing Bower
Once you have installed Node, run the command shown in Listing 2-3 to install the Bower package, which
is used to manage client-side packages.
7
Chapter 2 ■ Getting Ready
Installing Git
The Git revision control tool is required to download the client-side packages used by the Bower package
installed in the previous section. Download and run the installer from https://git-scm.com/downloads.
When the installation is complete, open a new command prompt and run the command in Listing 2-4 to
check that Git is installed and working properly.
git --version
This command prints out the version of the Git package that has been installed. At the time of writing,
the latest version of Git for Windows is 2.13.0.
Installing Docker
Docker is available in Community and Enterprise editions, the difference being the support and
certifications offered for the Enterprise edition. Both editions provide the same set of core features, and I use
the free Docker Community edition throughout this book.
Go to https://store.docker.com/editions/community/docker-ce-desktop-windows, click the
Get Docker CE for Windows (stable) link, and run the installer that is downloaded. Docker will start
automatically when the installation is complete. You may be prompted to enable Hyper-V, as shown in
Figure 2-2. Click the Ok button.
Once the installation has completed, right-click the Docker icon in the taskbar and select Settings from
the pop-up menu. Navigate to the Advanced section and increase the memory allocated to Docker so that
it is at least 3500MB, which is the minimum required to run SQL Server, as shown in Figure 2-3. Click the
Apply button to save the configuration change and restart Docker with the new configuration.
8
Chapter 2 ■ Getting Ready
Once Docker has restarted, open a new PowerShell command prompt and run the command shown in
Listing 2-5 to check that the installation was successful.
Docker will download the files it needs to run a simple Hello World application. Docker will write out
messages like these, indicating that everything is working as expected (the command produces more output
than is shown here, but this is the important part):
...
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
9
Chapter 2 ■ Getting Ready
Click the Install button to begin the process of downloading and installing the Visual Studio features.
10
Chapter 2 ■ Getting Ready
Click the Close button to dismiss the list of extensions and then close Visual Studio, which will trigger
the installation process for the extensions you downloaded. You will be prompted to accept the changes that
will be made and the license terms, as shown in Figure 2-6. Click the Modify button to install the extensions.
Once the process has completed, you can start Visual Studio and begin development.
11
Chapter 2 ■ Getting Ready
I find myself increasingly using Visual Studio Code, in part because it means I can use the same IDE on
different platforms and in part because it is more responsive and less resource hungry than Visual Studio 2017.
To install Visual Studio code, visit http://code.visualstudio.com and click the download link for
Windows. Run the installer and then start Visual Studio Code.
Once the installation is complete, start Visual Studio Code, click the Extensions button in the sidebar,
and locate and install the C# package, which provides support for working with C# code files.
Run the command shown in Listing 2-7 to download and install the .NET Core SDK package. It is
important that you use the version number shown in the listing so that you get the expected results from the
examples in this book.
Once the package has been downloaded and installed, run the command shown in Listing 2-8 to check
that .NET Core is installed and working.
dotnet --version
The output from this command will display the latest version of the .NET Core runtime that is installed.
If you have installed only the version specified, this will be 1.0.4.
12
Chapter 2 ■ Getting Ready
Installing Node.js
N The easiest way to install Node.js is through a package manager, using the procedures described at
https://nodejs.org/en/download/package-manager. For Ubuntu, I ran the commands shown in
Listing 2-9 to download and install Node.js.
Once you have installed Node.js, run the command shown in Listing 2-10 to check that the installation
was successful and that you have the right version.
node -v
You should see that version 6.x.x is installed. Version 6.10.3 is the latest at the time of writing, but there
may be updates pushed into the package manager feed for version 6.x by the time you read this.
Installing Bower
Once you have installed Node, run the command shown in Listing 2-11 to install the Bower package, which
is used to manage client-side packages.
Installing Git
Git is already installed on most Linux distributions. If you want to install the latest version, then consult the
installation instructions for your distribution at https://git-scm.com/download/linux. For Ubuntu, I used
the command in Listing 2-12.
Once you have completed the installation, open a new command prompt and run the command in
Listing 2-13 to check that Git is installed and available.
git --version
13
Chapter 2 ■ Getting Ready
This command prints out the version of the Git package that was installed. At the time of writing, the
latest version of Git for Linux is 2.7.4.
Installing Docker
To install Docker on Linux, visit https://www.docker.com/community-edition, select the distribution that
you are using from the list, and follow the installation instructions, copying and pasting the commands to
avoid typos.
For Ubuntu 16.04, open a new command prompt and enter the commands in Listing 2-14 to configure
the package manager and install the prerequisite packages that Docker relies on.
Listing 2-14. Preparing the Package Manger and Installing Prerequisite Packages
Once Docker is installed, run the commands shown in Listing 2-16 so that you can use Docker without
sudo.
Log out of your current session and log back in again for the commands in Listing 2-16 to take effect.
Once you have logged back in, run the command shown in Listing 2-17 to check that the installation has
been successful.
14
Chapter 2 ■ Getting Ready
Docker will download the files it needs to run a simple Hello World application. Docker will write out
messages like these, indicating that everything is working as expected (the command produces more output
than is shown here, but this is the important part):
...
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
Once you have confirmed that Docker is installed and working properly, then run the command shown
in Listing 2-18 to install Docker Compose, which is required for the examples in this book.
Once the installation is complete, run the command shown in Listing 2-19 to check that Docker
Compose works as expected.
docker-compose --version
If the installation has been successful, you will see this response: docker-compose version 1.13.0,
build 1719ceb.
15
Chapter 2 ■ Getting Ready
/usr/bin/ruby -e \
"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Once installation is complete, run the commands shown in Listing 2-21 to install the OpenSSL library,
which is a prerequisite for some .NET Core features.
To install .NET Core on macOS, download the SDK installer from https://go.microsoft.com/
fwlink/?linkid=848823. This URL is for the .NET Core SDK version I use throughout this book and that you
should install to ensure you get the expected results from the examples.
Run the installer. Once the process is complete, open a Terminal window and run the command shown
in Listing 2-22 at the prompt to check that .NET Core is working.
dotnet --version
The output from this command will display the latest version of the .NET Core runtime that is installed.
If you have installed only the version specified, this will be 1.0.4.
Installing Node.js
To install Node.js on macOS, download and run the installer available from https://nodejs.org/dist/
v6.10.3/node-v6.10.3.pkg. Once the installation is complete, open a new Terminal window and run the
command shown in Listing 2-23 at the command prompt once the installer has completed.
node -v
You should will see the following version number displayed: v6.10.3.
16
www.allitebooks.com
Chapter 2 ■ Getting Ready
Installing Bower
Once you have installed Node, run the command shown in Listing 2-24 to install the Bower package, which
is used to manage client-side packages.
Installing Git
The Git revision control tool is required to download the client-side packages used by the Bower package
installed in the previous section. Download and run the installer from https://git-scm.com/downloads.
When the installation is complete, open a new command prompt and run the command in Listing 2-25 to
check that Git is installed and working properly.
git --version
This command prints out the version of the Git package that has been installed. At the time of writing,
the latest version of Git for macOS is 2.13.0.
Installing Docker
Go to https://store.docker.com/editions/community/docker-ce-desktop-mac, click the Get Docker for
CE Mac (stable) link, and run the installer that is downloaded. Drag the whale to the Applications folder, as
shown in Figure 2-7.
17
Chapter 2 ■ Getting Ready
Open Launchpad and click the Docker icon to perform the setup process. Once Docker has started,
click the Docker menu bar icon and select Preferences from the pop-up menu.
Navigate to the Advanced section and increase the memory allocated to Docker so that it is at least
3500MB, which is the minimum required to run SQL Server, as shown in Figure 2-8. Click the Apply button
to save the configuration change and restart Docker with the new configuration.
Click Apply & Restart to change the memory and restart the Docker process. When Docker is running
again, dismiss the Preferences window, open a new Terminal window, and run the command shown in
Listing 2-26 to check that the installation was successful.
18
Chapter 2 ■ Getting Ready
Docker will download the files it needs to run a simple Hello World application. Docker will write out
messages like these, indicating that everything is working as expected (the command produces more output
than is shown here, but this is the important part):
...
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
Summary
In this chapter, I explained how to install the tools and packages that are required to use Angular and ASP.
NET Core MVC, and in the next chapter, I show you how to create a project that combines them.
19
CHAPTER 3
In this chapter, I show you how to create a project that contains ASP.NET Core MVC and Angular
applications, which means both parts of the project can be developed using Visual Studio or Visual Studio
Code. This project forms the foundation for the rest of this book, as I explain how to use Angular and
ASP.NET Core MVC to create a rich web application. Table 3-1 puts the combined project in context.
Question Answer
What is it? A combined project includes Angular and ASP.NET Core MVC in a single
folder structure.
Why is it useful? A combined project makes it easy to develop both parts of an application
using a single IDE, such as Visual Studio, as well as simplifying the process
of using an ASP.NET Core MVC web service to provide data to Angular.
How is it used? The Angular application is created first, followed by ASP.NET Core MVC.
Additional NuGet packages are used to allow both parts of the project to
work together at runtime.
Are there any pitfalls or A combined project makes managing the development process easier, but
limitations? you still need a good working knowledge of both Angular and ASP.NET Core
MVC to create an effective application.
Are there any alternatives? You can develop the Angular and ASP.NET Core MVC parts of the
application separately, although this tends to complicate the development
process.
■■Tip You can download the complete project for this chapter from https://github.com/apress/esntl-
angular-for-asp.net-core-mvc. This is also where you will find updates and corrections for this book.
Microsoft provides a template that can be used to create a similar project structure (which you can
use by running dotnet new angular at the command line). The process I use in this chapter is more
manual, but it means you will understand how the different building blocks fit together and have a
better idea of where to look when you don’t get the results you expect. Once you are familiar with how
Angular and ASP.NET Core MVC can work together, using this template is perfectly reasonable, with the
caveat that you are unable to specify the versions of ASP.NET Core MVC and Angular that are used in
the project.
The @angular/cli package provides a command-line interface that simplifies the process of creating
and working with a new Angular project. During development, the Angular code is compiled, packaged, and
delivered to the browser using webpack, a popular tool for creating JavaScript bundles that contain only the
code required to run a project.
To create a project that combines Angular and ASP.NET Core MVC, I start with @angular/cli and access
he underlying webpack configuration, which can then be used to integrate the Angular tools and libraries
into the ASP.NET Core project.
To start this process, open a new command prompt and run the command in Listing 3-1 to install the
@angular/cli package. If you are using Linux or macOS, you may need to use sudo to run this command.
This command takes a while to run because the package has a lot of dependencies, all of which have to
be downloaded and installed.
■■Tip You must follow each step exactly as shown, without missing a step or changing the order. If you get
stuck, then you can download a ready-made project from the source code repository, which is linked from the
Apress.com page for this book.
22
Chapter 3 ■ Creating the Project
The ng command is provided by the @angular/cli package, and ng new creates a new Angular project.
The arguments that start with --skip tell @angular/cli not to perform some of the standard setup steps that
are usually included in projects, and the --source-dir argument specifies the name of the folder that will
contain the source code for the Angular application. The Angular code lives in a folder called ClientApp in
projects that combine Angular and ASP.NET Core MVC.
The command in Listing 3-2 creates a folder called SportsStore that contains the tools and
configuration files for an Angular project, along with some placeholder code so that the tools and project
structure can be tested. The ng new command downloads a large number of packages, which can take a long
time to complete.
The rest of the setup is performed inside the project folder, so run the command shown in Listing 3-3 to
change the working directory.
cd SportsStore
Getting the Angular tools to work with the .NET tools requires additional NPM packages. Run the
command shown in Listing 3-4 to install these packages.
Microsoft provides some of these NPM packages, and they are used to set up and run the Angular
development tools inside the ASP.NET Core runtime. These packages work directly with webpack, which is
usually hidden when working with projects created using @angular/cli. Run the command shown in
Listing 3-5 in the SportsStore folder to create a webpack configuration file that can be used to build and
run the project, a process known as ejecting the project from @angular/cli.
ng eject
The ejection process updates the package.json file, which NPM uses to keep track of the packages used
by the project. In some cases, the ejection process will add additional NPM packages to the project.json file,
so run the command shown in Listing 3-6 to ensure that any new packages are downloaded and installed.
npm install
23
Chapter 3 ■ Creating the Project
Run the command shown in Listing 3-8 in the SportsStore folder to add a Microsoft package to the
project. This NuGet package is the .NET counterpart to the NPM packages installed earlier and is used to
integrate the Angular tools into Visual Studio.
The application will be stored using Microsoft SQL Server and accessed using Entity Framework Core.
Run the commands shown in Listing 3-9 in the SportsStore folder to add the NuGet packages required to
add these features to the application.
Not all the required packages can be added using the command-line tools. Open the project using
Visual Studio or Visual Studio Code. If you are using Visual Studio, then select File ➤ Open ➤ Project/Solution,
navigate to the SportsStore folder, and select the SportsStore.csproj file. To edit the NuGet packages,
right-click the SportsStore project item in the Solution Explorer, select Edit SportsStore.csproj from the pop-
up menu, and make the changes shown in Listing 3-10.
If you are using Visual Studio Code, open the SportsStore project, click SportsStore.csproj in the file
list to open the file for editing, and make the changes shown in Listing 3-10.
Listing 3-10. Adding NuGet Packages in the SportsStore.csproj File in the SportsStore Folder
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design"
Version="1.1.1" />
24
Chapter 3 ■ Creating the Project
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer"
Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink"
Version="1.1.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools"
Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version="1.0.0" />
</ItemGroup>
</Project>
If you are using Visual Studio, the new packages will be downloaded when you save the SportsStore.
csproj file. If you are using Visual Studio Code, use a command prompt to run the command shown in
Listing 3-11 in the SportsStore folder.
dotnet restore
25
Chapter 3 ■ Creating the Project
Ensure that the Launch URL button is selected and enter http://localhost:5000 in the App URL field,
as shown in Figure 3-1. Finally, click the Add button to create an environment variable called ASPNETCORE_
ENVIRONMENT, if it doesn’t already exist, with a value of Development. Save the changes and close the
properties window.
Listing 3-12. The Contents of the boot.ts File in the ClientApp Folder
import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { AppModule } from "./app/app.module";
26
Chapter 3 ■ Creating the Project
if (module["hot"]) {
module["hot"].accept();
module["hot"].dispose(() => {
const oldRootElem = document.querySelector("app-root");
const newRootElem = document.createElement("app-root");
oldRootElem.parentNode.insertBefore(newRootElem, oldRootElem);
platformBrowserDynamic().destroy();
});
}
This file is responsible for loading the Angular application and responding to changes to the client-side
code. Next, edit the Startup.cs file to change the code in the Configure method, as shown in Listing 3-13.
The additions enable the integration between the ASP.NET Core and Angular development tools.
Listing 3-13. Enabling Middleware in the Startup.cs File in the SportsStore Folder
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SpaServices.Webpack;
namespace SportsStore {
public class Startup {
public Startup(IHostingEnvironment env) {
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
27
Discovering Diverse Content Through
Random Scribd Documents
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
1.F.
1.F.1. Project Gutenberg volunteers and employees expend
considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.