Book Image

ASP.NET Core 5 and Angular - Fourth Edition

By : Valerio De Sanctis
Book Image

ASP.NET Core 5 and Angular - Fourth Edition

By: Valerio De Sanctis

Overview of this book

Learning full-stack development calls for knowledge of both front-end and back-end web development. ASP.NET Core 5 and Angular, Fourth Edition will enhance your ability to create, debug, and deploy efficient web applications using ASP.NET Core and Angular. This revised edition includes coverage of the Angular routing module, expanded discussion on the Angular CLI, and detailed instructions for deploying apps on Azure, as well as both Windows and Linux. Taking care to explain and challenge design choices made throughout the text, Valerio teaches you how to build a data model with Entity Framework Core, alongside utilizing the Entity Core Fluent API and EntityTypeConfiguration class. You’ll learn how to fetch and display data and handle user input with Angular reactive forms and front-end and back-end validators for maximum effect. Later, you will perform advanced debugging and explore the unit testing features provided by xUnit.net (.NET 5) and Jasmine, as well as Karma for Angular. After adding authentication and authorization to your apps, you will explore progressive web applications (PWAs), learning about their technical requirements, testing, and converting SWAs to PWAs. By the end of this book, you will understand how to tie together the front end and back end to build and deploy secure and robust web applications.
Table of Contents (15 chapters)
13
Other Books You May Enjoy
14
Index

MPAs, SPAs, PWAs, and NWAs

In order to demonstrate how ASP.NET and Angular can work together to their full extent, we couldn't think of anything better than building some small SPA projects with most, if not all, Progressive Web Application features. The reason for such a choice is quite obvious: there is no better approach to demonstrate some of the best features they have to offer nowadays. We'll have the chance to work with modern interfaces and patterns such as the HTML5 pushState API, webhooks, data transport-based requests, dynamic web components, UI data bindings, and a stateless, AJAX-driven architecture capable of flawlessly encompassing all of these. We'll also make good use of some distinctive PWA features such as service workers, web manifest files, and so on.

If you don't know the meaning of these definitions and acronyms, don't worry, we are going to explore these concepts in the next couple of sections, which are dedicated to enumerating the most relevant features of the following types of web applications: MPAs, SPAs, PWAs, and NWAs. While we're there, we'll also try to figure out the most common product owner's expectations for a typical web-based project.

Multi-page applications

Multi-Page Applications, also known as MPAs, are those web applications that work in a traditional way: each time the user asks for (or submits) data to the server, they render a new page that is sent back to the browser.

This is how all websites used to work during the first 20 years of the World Wide Web, and is still the most used approach nowadays due to a number of advantages that MPAs can still provide: excellent SEO performance, a fast and steady learning curve to serve, the ability to manage and customize static and dynamic content, and a lot of great content management systems (CMSes), frameworks, and UI themes – such as WordPress, Joomla, and the like – that can be used to build them from the ground up in a few minutes.

However, MPAs also come with some significant cons: the required server-side roundtrips tend to make them quite expensive in terms of bandwidth; moreover, front-end and back-end development are often tightly coupled, thus making them harder to maintain and update. Luckily enough, most of these issues have been mitigated throughout the years, thanks to various browser features and technology improvements such as CDN, server-side caching, AJAX requests, and so on. At the same time, such techniques add more complexity to the development and deployment phases; that is, unless we choose to rely upon one of the CMS platforms that we talked about early on, thus giving up on most of the coding aspects – with all that that implies.

Single-page applications

To put it briefly, an SPA is a web-based application that tries 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 content and resources – HTML, JavaScript, CSS, and so on – are either retrieved within a single page load or are 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 round trips: A competitive SPA can 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 (SOC) design principle, which means that the data source, the business logic, and the presentation layer will be separated.
  • Efficient routing: A competitive SPA is able to keep track of the user's current state and location during its whole navigation experience using organized, JavaScript-based routers. We'll talk more about that in the upcoming chapters when we introduce the concepts of server-side and client-side routing.
  • 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, and so on). 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 front-end with little or no impact on the server, aside from a few of the static resource files.

This 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 (MPA) mindset to fully committed or hybrid SPA-based approaches.

Progressive web applications

In 2015, another web development pattern pushed its way into the light when Frances Berriman (a British freelance designer) and Alex Russel (a Google Chrome engineer) used the term PWAs for the first time to refer to those web applications that could take advantage of a couple of new important features supported by modern browsers: service workers and web manifest files. These two important improvements could be successfully used to deliver some functionalities usually only available on mobile apps – push notifications, offline mode, permission-based hardware access, and so on – using standard web-based development tools such as HTML, CSS, and JavaScript.

The rise of Progressive Web Apps began in March 19, 2018, when Apple implemented support for service workers in Safari 11.1. Since that date, PWAs have been widely adopted throughout the industry thanks to their undeniable advantages over their "non-progressive" counterparts: faster load times, smaller application sizes, higher audience engagement, and so on.

Here are the main technical features of a Progressive Web App (according to Google):

  • Progressive: Works for every user, regardless of browser choice, using progressive enhancement principles
  • Responsive: Fits any form factor: desktop, mobile, tablet, or forms yet to emerge
  • Connectivity independent: Service workers allow offline use, or on low-quality networks
  • App-like: Feels like an app to the user with app-style interactions and navigation
  • Fresh: Always up to date due to the service worker update process
  • Safe: Served via HTTPS to prevent snooping and ensure content hasn't been tampered with
  • Discoverable: Identifiable as an application by a web manifest (manifest.json) file, and a registered service worker, and discoverable by search engines
  • Re-engageable: The ability to use push notifications to maintain engagement with the user
  • Installable: Provides home screen icons without the use of an app store
  • Linkable: Can easily be shared via a URL and does not require complex installation

However, their technical baseline criteria can be restricted to the following subset:

  • HTTPS: They must be served from a secure origin, which means over TLS with green padlock displays (no active mixed content)
  • Minimal offline mode: They must be able to start even if the device is not connected to the web, with limited functions or at least displaying a custom offline page
  • Service workers: They have to register a service worker with a fetch event handler (which is required for minimal offline support, as explained previously)
  • Web manifest file: They need to reference a valid manifest.json file with at least four key properties (name, short_name, start_url, and display) and a minimum set of required icons

For those interested in reading about this directly from the source, here's the original link from the Google Developers website: https://developers.google.com/web/progressive-web-apps/

In addition, here are two follow-up posts from Alex Russell's Infrequently Noted blog: https://infrequently.org/2015/06/progressive-apps-escaping-tabs-without-losing-our-soul/

https://infrequently.org/2016/09/what-exactly-makes-something-a-progressive-web-app/

For those who don't know, Alex Russell has worked as a senior staff software engineer at Google since December 2008.

Although they have some similarities, PWAs and SPAs are two different concepts, have different requirements, and differ in many important aspects. As we can see, none of the PWA requirements mentioned previously refer to Single-Page Applications or server-side round trips. A Progressive Web App can work within a single HTML page and AJAX-based requests (thus also being an SPA), but it could also request other server-rendered (or static) pages and/or perform standard HTTP GET or POST requests, much like an MPA. It's also the opposite: any SPA can implement any single PWA technical criteria, depending on the product owner's requirements (more on that later), the server-side and client-side frameworks adopted, and the developer's ultimate goal.

Native web applications

The first good definition of Native Web Applications (also known as NWAs) available on the web can arguably be found in Sam Johnston's blog post written on January 16, 2009, which went like this:

A Native Web Application (NWA) is a web application which is 100% supported out of the box by recent standards-compliant web browsers.

A similar approach was used 6 years later (January 22, 2015) by Henrik Joreteg to describe the defining feature of NWAs:

The thing these apps all have in common is that they all depend on the native web technologies: HTML, CSS, and JavaScript (arguably, you could add WebGL to that list).

These definitions help us to understand that we're dealing with a rather generic term that encompasses SPAs, MPAs, and even PWAs – since they all depend on native web technologies that are supported out of the box by all recent browsers; however, due to the emphasis given to the recent keyword and the existence of the more specific web application types, the NWA term is mostly used to identify those web applications that, although being built using modern web-based technologies, cannot be classified as MPA, SPA or PWA because they tend to adopt a hybrid approach.

Since we're going to use Angular, which is all about developing Single-Page Applications, and has also shipped with a strong and steady service worker implementation since version 5, we are fully entitled to take advantage of the best of both worlds. For this very reason, we're going to use service workers – along with the benefits of increased reliability and performance they provide – whenever we need to, all while keeping a solid SPA approach. Furthermore, we're definitely going to implement some strategic HTTP round trips (and/or other redirect-based techniques) whenever we can profitably use a microservice to lift off some workload from our app, just like any good Native Web Application is meant to do.

Are all these features able to respond to modern market needs? Let's try to find it out.

Product owner expectations

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 ones who bring 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 management to make decisions and make tough calls, which is sometimes great, sometimes not; this will often have a big impact on our development schedule. To cut it short, they're the ones in charge of the project; that's why, in order to deliver a web application matching their expectations, we'll need to understand their vision and feel it as if it were our own.

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 have made that 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 whether the choice of using ASP.NET and Angular will be good enough to fulfill each one of them, as follows:

  • Early release(s): No matter what we're selling, the customer will always want to see what they're buying. For example, if we plan to use an Agile development framework such as Scrum, we'll have to release a potentially shippable product at the end of each sprint. If we are looking to adopt a Waterfall-based approach, we're going to have milestones, 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 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 back-end: We'll often be asked to work on the GUI and front-end functionalities because that will be the only really viewable and measurable thing for the customer. This basically means that we'll have to mock the data model and start working on the front-end as soon as possible, delaying the back-end implementation as much (and as long) as we can. Note that this kind of approach is not necessarily bad; we just won't do that just to satisfy the product owner's expectations.

    On the contrary, the choice of using ASP.NET 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'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 the controller templates available within Visual Studio and in-memory data contexts powered by Entity Framework Core, 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 things 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 that work together with ease. ASP.NET 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 sides 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 change 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 the ability to manage—and even welcome, to some extent—most of the layout or structural changes that will be expected during the development phase.

A few lines ago, we mentioned Scrum, which is one of the most popular Agile software development frameworks out there. Those who don't know it yet should definitely take a look at what it can offer to any results-driven team leader and/or project manager. Here's a good place to start: https://en.wikipedia.org/wiki/Scrum_(software_development)

For those who are curious about the Waterfall model, here's a good place to learn more about it: https://en.wikipedia.org/wiki/Waterfall_model

That's about it. Note that we didn't cover everything here as it would be impossible without the context of an actual assignment. We just tried to give an extensive answer to the following general question: if we were to build an SPA and/or a PWA, would ASP.NET and Angular be an appropriate choice? The answer is undoubtedly yes, especially when used together.

Does this 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 this by ceasing to speak in general terms and starting to put things in motion. That's precisely what we're going to do in the next section: prepare, build, and test a sample Single-Page Application project.