Category Archives for Angular

Architecture Patterns for Angular and .NET Core

Modern web application development is fraught with choices. There are many ways to build a modern web application. Some of the choices include: front-end architecture style (SPA, MVC, Razor Pages), front-end framework (React, Angular, jQuery), front-end build tools, CSS pre-processor, JavaScript build tool (Webpack, System.js, Gulp), and back-end architecture. Each of those choices spawns other architectural choices. Depending on what you pick, there could be several dozen decision points in the process. 
 
One of the things I like about Angular is that you don’t need to make as many of these choices. If you use Angular, you don’t have to spend hours searching NPM and Github for the different pieces of your web app. There are still choices to make though. In this post, we’re going to focus on how to integrate your front end (Angular) with your back-end (ASP.NET Core).
 
We are going look at three ways to build a web application. We’ll begin with the time tested monolith. Then we’ll move onto the shiny new “serverless” architecture style. After that, we’ll explore microservices architecture. After this post, you’ll have a good grasp of each of these styles and know when to use each one for your own applications.

Monoliths

If you’ve been building web applications for any amount of time, you’ve probably worked on at least one monolith. In a monolith, the entire application’s workflow is in one code base. In the .NET world, that means everything can fit into one big solution file. Monolith doesn’t mean we can’t have a reasonable separation of code. You can create module boundaries and separate your code into projects. You can even implement an n-teir architecture and separate your application into layers. The key to the monolith is that the whole process is in one self-contained code base.
 
Monolith architecture gets bashed on, but it’s the default for a reason. There’s several advantages to the monolith style. For one, everything is in one place. If you need to refactor, you don’t have to worry about moving across service boundaries. Tools like ReSharper make this even easier. Monoliths are also easy to deploy. If you are building a small or medium sized application, monolith architecture is a good choice.
While monoliths are fine much of the time, there are situations where they tend to fall down. The first problem with monoliths is that they are hard to scale. If you have one piece of an application that’s experiencing a heavier load, you still have to scale out your whole application. Monoliths also deter code reuse. In many corporate environments, there are resources that are used by more than one application. With a monolith, you end up copying the code to access those resources. Because there’s so much code in one place, larger monoliths can be hard to understand. This can make it harder to on-board new team members. Once your application gets to a certain size, you should peel microservices off of your monolith.
 

There are a few ways to implement a monolithic Angular application. The easiest way is to use the built in template. Visual Studio comes with an Angular template that includes some nice features. I prefer to use the Angular CLI, so I don’t use the included template. If you also want to use the Angular CLI, I have a post on how to use Angular CLI with a .NET Core project.

Angular CLI with .NET Core

As I learn more about Angular, I’m beginning to favor another approach. The truth is that .NET doesn’t add much to the Angular front end party. Given a clean slate, I’d run the Angular half of the code as it’s own project and use .NET Core for the API. Angular CLI is perfectly happy self hosting or you can deploy the static assets to an IIS site. 

Serverless

The serverless architecture is the most recent pattern on the list. It’s also the worst named pattern on the list. The servers [obviously] exist, but you don’t have to care about them. It’s “serverless” to you.
 
Serverless architectures rely on services that host and run your code for you. Instead of managing VMs or physical servers, the service abstracts that away. If 500,000 users come knocking on the door to your site, you don’t even need to push up a slider bar. The service scales for you.
 
When people think of serverless, they’re usually thinking about Functions as a Service (FAAS). FAAS platforms allow you to host small bits of code in the cloud. This means a single endpoint. FAAS is not the only way to be serverless though. Services like Firebase can encapsulate the your whole back-end.
 
Here’s a list of serverless platforms: https://github.com/anaibol/awesome-serverless
 
To integrate this with Angular, you compile your Angular application into a static web site. Then you call the APIs you create in whatever serverless service you’re using. This post has details on how to build a serverless Angular application using Azure Functions and an Angular site hosted in an Azure web site. You should be able to adapt these instructions for your favorite cloud provider.
 
Serverless isn’t for every situation, but there’s some definite advantages. The biggest advantage is that you can quickly get your code into production. You don’t need to configure servers or set anything up. You just drop your code into the cloud and go. Server level concerns like scalability and server management are gone. Serverless architectures are also very cheap to start with. FAAS platforms charge you by usage, so low traffic apps are dirt cheap. Static websites are also fast and cheap. Since most static assets are cached, you can serve a ton of users with very little impact.
 
There are a few problems with serverless. The big one for me is complexity. Once you have a certain number of functions, they become hard to manage. I’d rather have a web service or series of web services over a suite of cloud functions. Functions also have somewhat unpredictable pricing. A misconfiguration in your service or a bug can leave you with a huge cloud bill. The serverless pattern really shines when building prototypes and minimum viable products (MVP). You can get code into production and start iterating. Later on, you can refactor your functions into services if your application takes off.

Microservices

The microservices architectural pattern addresses some of the issues found on larger products. Microservices divide the functionality into tightly scoped services. These services are loosely coupled, so you can work on them independently. You can even build them using separate technology stacks.
 
Microservices architecture has several advantages. First, it’s easy to scale microservices. If you have one part of your application that’s receiving lots of traffic, you can scale only that part. Microservices are also easy to understand. Because they are small, it’s easy to drop into a new service and find your way around. Each service is easy to reason about. This is my favorite feature of the microservies architecture. Getting up to speed is much easier than on a big monolith application. Microservices also encourage reuse. In enterprise environments, you often have several applications hitting the same data. With microservices, you can make one service that serves many applications.
 
While microservices are great, there are some drawbacks. The biggest drawback I’ve seen is performance. Because the services are loosely coupled, you use JSON as a commnication mechanism between services. This means you end up doing a lot of serialization and deserialization. Each service boundary you cross incurs an overhead cost. On larger requests, those costs are significant. These service boundaries also make it harder to troubleshoot problems. Tracking down which service in a chain of calls is breaking down can be frustrating.
 
Another pitfall of microservice development is deployment complexity. Even though services are loosely coupled, you still need to manage the dependencies between them when deploying larger features. If you don’t have a good continuous deployment and integration pipeline, you are going to have a bad time.
 
If you want to see a sample microservices and Angular application, I have one here.

Conclusion

Each of the architectures in this post shines in a particular set of circumstances. Monoliths are great for small to medium sized projects, but are not ideal for larger applications. Serverless architecture is great for small apps, but not for large enterprise applications. Microservices architecture works well for large applications, but isn’t worth the overhead on small ones. Figure out the application you want to build and choose wisely. 

How to Build a Serverless Angular App on Azure

Building web applications is hard work. Not only do you have to build the application, you need to figure out where to host it. Ever want to skip all the frustrating server provisioning and focus on your code? If so, then serverless architecture is worth a look. In this article, you will learn how to build setup a serverless Angular app using Azure.

What exactly do you mean by “serverless”?

The term “serverless” is somewhat misleading. There are still servers, but you don’t have to care about them.

Serverless architecture runs on managed services that host your code. Server level concerns like figuring out how much memory you need, fault tolerance, and scalability are abstracted away. You don’t need to pick out a VM or service tier. The service scales automatically. You upload your code and go. The service takes care of the rest.

Serverless platforms come in several different flavors including APIs like Firebase and functions as a service (FAAS). FAAS is where you host small bits of code in the cloud. Think micro-services to the nth degree. All of the major cloud providers have some flavor of FAAS. Examples include: Amazon Lambda, Google Cloud Functions, and Azure Functions. You can even host your own FAAS using OpenFAAS, though that kinda defeats the point. (comprehensive list of serverless platforms)

For the purposes of this application, we are going to use Azure Functions for our backend API.

Where do we put the web site?

While Angular application are complex to develop, they compile into a handful of static files. There’s no reason you can’t throw these files up on any commodity static host. In this case, we’re going to use Azure Web Sites. While this solution isn’t 100% serverless, (you have to pick a hosting tier) hosting a handful of files on the free tier is close enough for me. To add another layer of performance, we’re also going to use Azure CDN to cache the files so they load quickly.

Roadmap

Here’s what we’re going to do:

  • Build an API using Azure Functions
  • Setup an Azure Web App to host our Angular application
  • Setup Azure CDN to serve those files more quickly
  • Add CORS headers on our function app so we can use it with our Angular app
  • Setup a SPA redirect to prevent unintended 404 errors

Building an API with Azure Functions

We start off by creating a new Azure Function app. Starting from the Azure Portal, click “New” search for “function” and click Function App. This will bring you to the new function app blade. Type in your app name (it has to be unique), add the rest of your info and click Create.

Now we’re going to make a function. Either hit the plus sign or click “New Function”. This brings you to the function template screen before. Functions can be activated by a variety of triggers including DB requests, files, and manual activation. We’re going to use the HTTP Trigger. HTTP triggers are activated by an HTTP request. Select “HttpTrigger – C#”.

You should now have this lovely boilerplate. This code can handle any http request and sends back a response.

Let’s ditch that boilerplate and drop in our API code. This is just going to be a simple GET request. Feel free to pretend we’re calling a database here instead of just returning a list.

If you’d like to test your shiny new function, click the “get function url” link and drop that into Postman. As you can see here, things are working splendidly.

You can also test using the built-in testing utility on the right side of the function window.

Setting up an Azure Web Site

Now that we have our backend setup, let’s put together our front end. In this case, we’re going to set up an Angular application built with the Angular CLI. Since this post is about setting up the architecture, I’m not going to go into great detail about the application itself, which can be found in this github repo. If you’re using another front-end library like React or Vue.js, this setup should be mostly the same.

To begin, create an Azure Web App. (New -> Web App). The free tier should be adequate for our needs. We’re just hosting a few files. If you want to use your own custom domain, you’ll need to use a higher tier.

Now we need to get the static files to host. If you’re using Angular CLI (and you should be…), the command to do this is:

ng build --prod --aot

After that command runs, head over to the dist folder of your angular app. It should look something like this:

The next step is to get your static files into the web app. I used FTP, though you can download a publish profile if you want. Drop your static files into the wwwroot folder. At this point, you should be able go to the URL and your app will load.

The next step is to set up a CDN. Since these are just static files, we can use a CDN to serve them. Azure CDN also allow us to serve the site over https without having to pay for a plan that supports SSL. To set one up, go to New, search “CDN”, click “CDN”, and click “Create”.

This brings up the CDN profile blade. Type in your name, select “Standard” for your pricing tier, and select your web site from the dropdown. Then click “Create”. Now you have a CDN for your static files.

Setting up CORS

Now that we have our web app in place, we need to set up the CORS (cross origin resource sharing) headers on our function. Browsers, by default, prevent your website from accessing APIs that don’t match the url of your web application (CORS error pictured below). This feature helps to prevent Cross Site Request Forgery (CSRF) attacks, but is sometimes kind of annoying. If you want to use your function API from your web application, you’ll need to add a CORS header to your API.

To begin, go back to your function app and go to the “Platform features” tab and click “CORS”.

This brings you to the CORS screen. Add the url/s of your web app. You can use “*”, which is the wildcard route, but you shouldn’t because it’s rather insecure. It’s best to use your web app’s URL here.

Setting up a SPA Redirect

At this point, we have a functioning web application, but there’s still one more issue to resolve. Like most SPA applications, Angular supports client side urls that don’t correspond to server-side resources. All of our application code is served from index.html on the root url, but we use the Angular router to map urls to parts of the application. For example, in our sample app, if we navigate from the home page to the Products page it works great, but if we hit refresh we get a 404. (error below) This is because there’s no page on the server for that URL. To fix this we need to add a URL re-write rule to redirect anything that’s not a static asset back to the index page.

To do this, we’re going to create a web.config file with our rewrite rule.

Here’s our rule (finished product):

This rule takes anything that isn’t a file, directory, or an asset (*.html, *.js, *.css) and redirects it to the index page. If you have fonts or images in your application, you should probably add rules for those file extensions as well.

Then, take that web.config file and drop it into the wwwroot folder of our web app. App urls should now redirect appropriately.

Conclusion

If you’d like to build an Angular application and host it for cheap in the cloud, this is a great way to do it. The serverless architecture is great for MVPs, simple applications, and proof of concept applications. It’s an easy way to get code into the world with minimum fuss.

References / Additional Information

If you’d like additional information or access to the code referenced in this post, check out the links below.

Demo Code

Cloud hosting for a static website

Azure Functions Docs

URL Rewrites in an Azure Web App

URL Rewrite Docs

Angular CLI With .NET Core

Angular is a fantastic platform for building rich client side apps, but let’s not forget about the back end. My choice for the back end is ASP.NET Core. If you’re not shy about spending a bunch of time setting up Webpack, Angular and ASP.NET Core is a fantastic combination.

However, I prefer to spend my time building applications, not configuring build tools. Angular CLI takes a lot of the pain out of using Angular, but it’s a self contained command line tool. Fortunately, Angular CLI and ASP.NET Core can happily co-exist. In this post, we’re going to build an application using these two technologies together. By the end, you’ll be ready to have all the goodness of Angular and ASP.NET Core without spending a week setting up Webpack.

Prerequisites

Make sure you have .NET Core, Node.js and Angular CLI installed.

https://www.microsoft.com/net/core#windowsvs2017

https://nodejs.org/en/

npm install -g @angular/cli 

Getting Started: ASP.NET Core App Setup

Fire up Visual Studio (I’m using VS 2017) and create a new ASP.NET Core Web Application. Select the Web API Starter. This doesn’t bring in any web stuff, which is ideal. We’re going to use Angular CLI to generate the client files.

Then go ahead and disable automatic Typescript compilation. We want CLI to compile our Typescript, not Visual Studio. Do this by adding the “TypeScriptCompilerBlocked” line to your csproj file.

Head on over to the Startup.cs and add in the static files middleware. You’ll have to install the “Microsoft.AspNetCore.StaticFiles” NuGet package. After that, add app.UseDefaultFiles() and app.UseStaticFiles() to your Configure() method.

After you get those setup, you’ll want to add some middleware to redirect those pesky 404s to the root file. This will allow you to navigate the application without having to start at the root each time you hit refresh. For this app, api routes are prefixed with “api”, so we’re excluding those routes from the check. We’re also excluding routes with a file extension since those are likely static assets.

To prevent the app from loading up the api/values endpoint by default, go to properties/launchSettings.json and change the “launchUrl” keys from “api/values” to “”.

At this point, our .NET Core app should be ready to go. Let’s move on to the Angular code.

Setting Up Angular CLI

We’re going generate our Angular app on top of our ASP.NET core app. To do this, go to the command line and navigate to the directory of your solution file. Then run “ng new <your app name>”.

You want the <app name> part to be the same as your .NET Core source folder. This will drop all of the CLI files into your ASP.NET Core root folder. It should look like this:

Gluing It All Together

Angular has a default file structure, but it’s not ideal for the existing ASP.NET Core application. Fortunately, Angular CLI has some options that will allow us to change this structure. We want the client side code to be in a folder called “client-src” and the client side build artifacts to go to the wwwroot folder. To do this, rename the “src” folder to “client-src”. Then go to go to .angular-cli.json. This is the primary configuration file for Angular CLI. First, change “src” to “client-src”. Then change the “outDir” attribute from “dist” to “wwwroot”. This will drop all of the compiled assets into the wwwroot folder.

At this point, we can build the Angular application using Angular CLI. Navigate a command prompt into the main application folder and run “ng build”. This command will build the client side part of the application, dropping the build artifacts into wwwroot. The wwwroot folder should look like this:

  

At this point we should be able to run the app by hitting the Run button in Visual Studio. Unfortunately, we still have a two stage build pipeline. The first step being “ng build” to generate the client side files and then running the .NET Core app. To fix this, we can drop in a post build script: “ng build — aot”. This will compile the client side files (with ahead of time compiling) after the app builds.

Bonus Points

If you’re using git, you’ll want to add the wwwroot folder to your .gitignore file. These files are generated, so you probably don’t want to check them in.

Example Code

All of the demo code used in this post is available here:

https://github.com/DustinEwers/shiny-angular-demos/tree/master/ninjas-quest-cli-core/ninjas-quest

This demo includes a full Angular application on top of ASP.NET core. Feel free to use this as a template or something to look at while building your own. You now have everything you need to get started building shiny applications using Angular CLI and ASP.NET Core.

Debugging Angular Apps with Augury

I recently went on a hunt for Angular (formerly known as Angular 2)  profiling tools.  Angular is a fantastic framework, but the component hierarchies can get a little crazy. Fortunately, there’s a way to tame the complexity. After some Google searching, I came across Augury. Augury is a debugging and profiling tool created by Google and Rangle.io.

Augury is simple to install. First, install the Augury Chrome Extension (Sorry Firefox lovers, no soup for you.) There is no step 2.

Once installed, Augury shows up as a new tab in your Chrome Developer Tools. If you have an Angular app running in debug mode (it doesn’t work on prod mode), the tab will show several visualizations of your application. The first one is the component tree, which lays out the components for whatever page you are on. Click a component to see the properties and events for it. You can also manipulate the underlying models and trigger events. Additionally, each component is has a link to its source code. If you want to set a breakpoint, just click and you’ll be right there.

 

You can also get a visualization of injected services by clicking on the Injector Graph. It’ll help you figure out where your dependencies come from.

 

If your application is using routing, click on the routing tree tab to get a visualization of the routing structure.You can click into the routes to see what url triggers them, along with other route information. If you happen to use lazy loading, those routes are marked as “lazy loaded” until you access them.

If you want to see a breakdown of your application’s module structure, click the NgModules tab. This is a good way to get a high level overview of your application.

 

Overall, Augury makes it easier to reason about your Angular applications. By visualizing the component trees, routing, and module structures, you get a high level overview of your application’s structure. Additionally, the extra debugging features add a layer of easy to the already fantastic Chrome Developer tools. I’ve added this to my day-to-day Angular tool belt and urge you to do the same.

More Information

Augury Home

Augury Guide

Cutting Through The JavaScript Toolchain Thicket with Angular CLI

If there is a developer hell, one of the circles will involve the JavaScript toolchain. The JavaScript ecosystem is awash in tools, choices, and configuration options. Combine that with spurious documentation and constant change and you have a jungle of pain awaiting any brave soul who dares build a modern JS application.

Much has been done to ease JavaScript toolchain fatigue. There are templates and starter packs for most of the popular JS stacks. If you’re using Angular 2, the Angular team has created a tool called Angular CLI. It encapsulates all the best practices into one handy command line tool. Angular CLI shortcuts most of the Angular 2 setup. Just run a few commands and you have a working application. In addition to the build tools, you also get a set of scaffolding tools. If you’re familiar with the Ruby on Rails scaffolding tools, Angular CLI will feel right at home. In the interest of trying new things, I decided to kick the tires on Angular CLI and see if it lives up to the hype. I took my demo Angular 2/TypeScript/Webpack application (repo here) and ported it over to Angular CLI.

Installing Angular CLI

npm install -g angular-cli

Install the Angular CLI tool using NPM. Make sure to run the npm install as an administrator. Easy peasy.

Scaffolding an Application

npm install -g angular-cli
ng new <my app name>
cd <my app name>
ng serve

These commands will spin up a basic app structure for you to use. This app structure has a lot of goodies included. Testing, linting, hot module loading, and a decent starter app all come with the basic template. CLI abstracts away the webpack setup, so you don’t have to figure that out. It even includes a basic demo server for you to serve your application from. The only thing that the angular cli doesn’t include is a style library. I’d love to see Angular Material or Bootstrap included with the CLI, but I’ll live.

Here’s what comes out of the box with a new Angular CLI Project:

I was curious about how up to date the basic setup is, so I ran “npm outdated”. NPM packages change often. It looks like most of the packages are close to their most recent version, but the CLI used Angular 2.3 instead of Angular 2.4.

Generators

Boilerplate code sucks and Angular 2 has a bunch of it. There are lots of small files that need be built when you add a new component. Angular CLI has generators to help with that. I tried out a few of the generators. I found the component generator to be particularly useful. It builds out the template, code, and spec files. It also adds the component to its root module. This is a great time saver. The route generator was far less useful, however, as it didn’t do anything. It looks like they’re going to add it back in later.

Styles

The default template doesn’t include any style libraries, so I pulled in Angular Material (currently in beta).

To install:

npm install --save @angular/material

Then you need to pull it into your app module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { CharacterBuilderComponent } from './character-builder/character-builder.component';
import { EncounterComponent } from './encounter/encounter.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { StatsComponent } from './stats/stats.component';
import { HomeComponent } from './home/home.component';
import { MaterialModule } from '@angular/material';
@NgModule({
declarations: [
AppComponent,
CharacterBuilderComponent,
EncounterComponent,
NavMenuComponent,
StatsComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Finally, add a theme file to your site.css. There are several pre-built themes, but you can make your own if you want.

@import '~@angular/material/core/theming/prebuilt/deeppurple-amber.css';

After importing the styles I ported all of my demo code over into the angular cli project. This process was surprisingly easy. Unfortunately, the Material styles are not as robust as the Bootstrap styles. I’m sure I made a mistake somewhere, but I wasn’t really going for maximum style, so I let it go. I’m looking forward to Material UI being ready for primetime, but I don’t think it’s quite there yet.

Final Verdict

I wouldn’t use Angular CLI in production (yet), but I think it’s a fantastic tool for playing with and learning Angular 2. It takes the most painful part of setting up an Angular 2 project and makes it a breeze. You can get up and going faster than building an environment from scratch. I’m going to keep an eye on this project and see how it develops. If you build Angular 2 apps, I recommend you do the same.

Here’s the final result:

https://github.com/DustinEwers/typescript-demos/tree/master/ts-demo-node/ninjas-quest

Lazy Loading Modules With Angular 2 And Webpack

I’m sure this is obvious to some people, but this issue threw me for a loop.

When building applications in Angular 2, it’s best practice to divide up your application into feature modules. This keeps your code simple and easy to work with. You can lazy load these child modules to improve initial load times and keep people from downloading code for areas they don’t have access to.

The Angular 2 website has excellent tutorials on how to set this up, but if you’re using Webpack, those instructions (link) don’t quite work.

Here’s the code from the Angular 2 website.

export const routes: Routes = [
  { path: '', redirectTo: 'contact', pathMatch: 'full'},
  { path: 'crisis', loadChildren: 'app/crisis/crisis.module#CrisisModule' },
  { path: 'heroes', loadChildren: 'app/hero/hero.module#HeroModule' }
];

You could assume that this code isn’t specific to using system.js as your module loader, but you’d be wrong. Webpack, by default, chokes on these lazy loaded modules. I spent more time than I’m willing to admit trying to figure out the arcane errors before I realized that the Webpack was the problem. Fortunately, this problem is easy to fix.

Like everything else in Webpack, there’s a loader for that. In this case, you want the Angular 2 Router Loader (more info here). Be attentive to the instructions, because the module strings work different than they do with system.js. For example, the Webpack loader supports relative paths. (The Angular 2 docs say otherwise) Once you setup the loader, lazy loading in Webpack works like a champ.