Yet Another Free JavaScript Book: Angular 5

As part of my unplanned and unasked for blog series – Free JavaScript books, here is another. So introducing ‘Angular 5: From Theory To Practice: Build the web applications of tomorrow using the new Angular web framework from Google’ by Asim Hussain. It’s not exactly vanilla JavaScript as such – it’s Angular 5 and TypeScript but we’re all friends here so I’m lumping it in with the other free JavaScripts books I’ve written about.

And it’s a good one. Pitched at the right level, good quick start chapter so you can see how it all fits together early on and a nice primer on TypeScript in chapter 2. So, how much for hundreds of pages of Angular goodness delivered to a Kindle device? Well to you Madam/Sir, it is zero pounds, shillings and pence or nada dollars if you prefer. Oddly, if you are trying to get this on Australian Amazon then you are out of luck – clearly the bits and bytes can’t travel that far (though a VPN connection might help in that circumstance).

But Amazon Australia not withstanding, this book is worth the money. I’d even go further – this book would be worth the money if Mr Hussain ever decides to charge for it. Thank you Asim.

Angular pipe to truncate text to the nearest whole word

The problem

I want to truncate text in Angular 5 using a pipe. I don’t just want to chop the text up inbetween words. I want to truncate to the nearest whole word. And I want a ellipses on. I want it all. So the following text as an example

Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with an impure mind a person speaks or acts suffering follows him like the wheel that follows the foot of the ox.

Truncated to a length of not more than 150 would be

Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with an impure mind a person speaks or acts suffering follows…

I want that – and as luck would have it is actually a nice quote. Purely coincidental of course.

Starting off

First let’s use angular cli scaffolding to get us the base pipe. So open the command line and run

Or if you prefer

And the following js file pops out

Nice start. The pipe metadata tells us that to use it in the html page we will be using the truncatetext tag. It’s pretty obvious where our implementation is going to be.

The Implementation

So filling out the implementation gives us

So a bit at a time. The signature has changed to

Value is the string that is to be truncated. Length is our target (maximum) length. It returns a string which is the truncated text. There is a bit of parameter checking then

I’ve taken the view that the biggest word I’m likely to deal with is


So it’s 45 letters plus 5 for any spelling mistakes for a 50 character margin. (I’m ignoring the 189,819 letter protein name that someone unearthed – I guess biochemists need to use this Angular filter with caution).

So I truncate at my desired length plus 50 then nibble backwards at each space

Until I get to my length then glue on the ellipse and return it out. The only other thing Is

A sprinkle of regex to nibble off any comma, question mark etc.. What I don’t want is a result like

Mind precedes all mental states. Mind is their chief;…

It just looks weird.; I want

Mind precedes all mental states. Mind is their chief…

Much better.

Using the pipe

So to actually use the pipe in the component we need to declare it in the app.module e.g.

If you’ve use the angular cli command then that would have been done for you. Then to use in the component it is simply

And then that is it – my text is truncated in my angular app and looks something like this

Lovely filter; lovely quote.

Variant for truncating to a small length

It’s an edge case for me but there is the case where the filter is set to a (stupidly) small value e.g.

Taking into account the ellipses, the logic would be that the entire string evaporates to just the ellipse or perhaps nothing. I don’t really want that so this filter will return the first word with an ellipse as the minimum return value i.e.

If you want the behaviour where the output strictly adheres to the length or less then it would be something like ..

So it will return the length or less in all cases – if you really want that.

Demo App

As ever the code is on my github site here. It’s part of a bigger app and associated API that generates Buddhist quotes from the Pail Canon. All work in progress but I quite like it.

Useful Links
Official documentation for angular pipes. Useful
Biggest words in English for edge cases and general marvelment
The example text is the first verse of the Dhammapada -original translations by Acharya Buddharakkhita. The first verses are all in pairs so the example text with its partner is ..

Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with an impure mind a person speaks or acts suffering follows him like the wheel that follows the foot of the ox.

Mind precedes all mental states. Mind is their chief; they are all mind-wrought. If with a pure mind a person speaks or acts happiness follows him like his never-departing shadow.

Tremendous – one of my favourites.

.Net Core 2.0: project.assets.json’ doesn’t have a target for ‘.NETStandard,Version=v2.0’

The Problem

Odd error when building a .net core project with Visual Studio Code. This built a few weeks ago – went back it it and I’m getting this

C:\Program Files\dotnet\sdk\2.0.0\Sdks\Microsoft.NET.Sdk\build\Microsoft.PackageDependencyResolution.targets(165,5): error : Assets file ‘myproject\obj\project.assets.json’ doesn’t have a target for ‘.NETStandard,Version=v2.0’. Ensure that restore has run and that you have included ‘netstandard2.0’ in the TargetFrameworks for your project. [myproject\MyProject.csproj]

.Net Core has been installed, it used to work and there is not much on the Internet. Bafflement.


Turns out the bin and obj folders for each of the project need to be manually deleted. Once done then the command

gave me the green light and normal service has been resumed. No idea what it going on but sorted now – so I thought I would take a minute and post the solution to my small corner of the Internet. Cheers.

Multiple Projects with .Net Core and Visual Studio Code

The challenge is to create a solution in VS Code with multiple projects. There are three projects

  1. A console application
  2. A web api application
  3. A library with data access code that is common to both.

It will look like this when we are finished

Expanded to show detail

We need a solution that can build out all these projects in one click. Since we using VS Code and enjoying it’s lightweightness we’ll be relying completely on the new .Net Core Command Line Interface. I enjoy a challenge so using the command line seems fun (to me). Let’s go.


In case you don’t want to read the detail – the commands used to set up all projects, solutions and references are

From project root


To do this you’ll need VS Code’s C# extension installed into visual studio. Go to extensions and search for C#.

Install and away you go.

Note on command line

All .Net Core CLI commands can be entered into the terminal window in VS Code or into the standard command prompt if you prefer. Navigate to the root folder and enter your first command

Create Console Application

This installs our console application project. Since we are on .Net Core 2.0 we get the csproj file rather than the json project file of earlier versions. This installs the console app in a new folder with the same name as it’s containing folder. If we want a different name to the folder we do that by

But we don’t want that. We are keeping it simple. What I like about .Net Core is that it’s had all the gubbins stripped out. So our proj file for the console app is simply …

Nice. I understand that.

Create Common Library

Next we want to create a C# dll to host some common code like data access.

Creates an empty project called Demo.Common with a nice simple proj file thus

Link Common Library to Console app

Change to the console app direct and run the add reference common

Inserts the following into the console proj file

So the console app can access code in the common project and the two will build out together.

Add Nuget package to Common Library

We commonly want to add some nuget packages to our projects. So lets add the HtmlAgility pack and a C# driver for MongoDB – no reason for them other than I often use them.

Change directories back to common library

Now add the packages

Look at the proj file and you can see the package references inserted

VS Code likes to tell me to restore the project I.e. run dotnet restore. You don’t need to. Dotnet build or dotnet run does it for you.

Build Console Application

Let’s check things are working as they should and build our console app.


  Demo.Common -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Common\bin\Debug\netstandard2.0\Demo.Common.dll

Demo.ConsoleApp -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.ConsoleApp\bin\Debug\netcoreapp2.0\Demo.ConsoleApp.dll

Build succeeded.

0 Warning(s)

0 Error(s)

Good – by building the project we get both common and the console application building.

Create API 

Return to root folder

Now add a web api project called Demo.Api

Change to the Api folder

Now add a reference to our common library

The Api proj file looks a bit more complex but I’ll still pretty minimal compared to Visual Studio proj files.

Now let’s build that project. Staying in the Api folder

And the output shows us two projects have been built.

  Demo.Common -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Common\bin\Debug\netstandard2.0\Demo.Common.dll

Demo.Api -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Api\bin\Debug\netcoreapp2.0\Demo.Api.dll

Build succeeded.

0 Warning(s)

0 Error(s)

Joining everything together

Ok , so we want all the projects to build in one click. Because we have two independent applications (an API and a console app) we aren’t going to be able to do the build by navigating to a folder and building the proj file. We need a solution file to bind them all together

(this shamefully baffled me for a while. I was trying all sorts with launch.json etc… The solution is obvious though – embarrassed for not getting it immediately)

Back to root

Now add the solution file. We don’t want it in it’s own directory so omit the -o parameter. Add in the -n otherwise it takes it’s name from the containing folder which we don’t want in this case.

Now include the API and Console app

The solution file now includes the project info

Staying in the solution directory run build

And now all three projects are built.

Demo.Common -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Common\bin\Debug\netstandard2.0\Demo.Common.dll

Demo.ConsoleApp -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.ConsoleApp\bin\Debug\netcoreapp2.0\Demo.ConsoleApp.dll

Demo.Api -> C:\development\Demo\ASP.NET Core\MultipleProjects\Demo.Api\bin\Debug\netcoreapp2.0\Demo.Api.dll

Build succeeded.

0 Warning(s)

0 Error(s)


Demo code

The rather uninspiring skeleton demo app is at

More interesting the same pattern is on a .Net Core API for some Buddhist texts I’ve been working on

Is the console app that parses HTML and populates a document database with the texts
Is the web api to access the texts
Is the model and repositories common to both.  It’s the same pattern as the simplified demo app and I’m using VS Code for that – just to try it out really.

Useful Links
Full documentation for .Net Core Command Line Interface
Visual Studio Code is freely available here.

Resharper Build and Run

Just a quick shout out for Resharper’s new build and run feature. I’ve become accustomed to Resharper slowing my machine up as it endlessly loads a variety of caches and processes. Speaking as a member of the slower development machine community it is a delight to see a new feature that actually speed things up and increases productivity even on less than optimal machines. Build and run uses some heuristics (i.e. clever workings out) to analyse which projects actually need to be built then only builds these. On first build you don’t notice much of a difference but on subsequent build it makes for dramatic increases of speed. It’s impressive and a real benefit.

I won’t bore too much with my current slow machined troubles but I currently a home based contractor working on a mid range laptop – I anticipated this laptop to be used for some lightweight home development projects. Inside it’s running 2 Visual Studio instances with 35 and 12 projects each respectively. Really it can’t cope – except it suddenly can using Build and Run. 5 minutes build times have become 10 second affairs. It’s not too much to say that it has been a bit of a life (job) saver.

Of course the real solution is to buy a better machine. But as I find myself in a new, more expensive country funds are a little short right now. So until I spring for a new laptop, Resharper Build and Run is keeping me afloat. Thanks guys.


I’ve actually now done the decent thing and upgraded my laptop to use a 500GB SSD disc and popped in some extra RAM while I was at it. It runs like a dream. I close down and reopen Visual Studio now just for the fun of it – takes seconds. I still like Resharper Build and Run though, but it’s now less critical to my health and well being.

Getting the Root Directory Path for .Net Core Applications

Quick one. Given any .Net app I want to know the root path of the application i.e. the top level directory. I was doing this with .Net Core but it puts in extra directories by default in the exe path i.e.


so my normal kuldgy methods weren’t working. This all works for any .Net app not just Core in fairness – it’s just that the extra stuffed in by .Net Core threw me a little. There are all kinds of ways to find this for particular applications web, windows etc.. but this should work generally. Well it worked with my little console app anyway.

The Code

Use reflection to targeting the executable and get the path

this will get you


which is the UNC path. Combine with Path.GetDirectoryName i.e.

this gets


which is a  file path now and it has got us the directory of the executable. It’s still not where we want to be so use some regex

This will chop up the path and gives you


which is correct.

The Function

So overall a useful function for this could be

Which does what we need or I quite like it as a (much abused) extension method

Which can be called like

Which gives


Job done.

The Regex

Not everyone likes Regex*. But for the aficionados here is what it is doing

For example matching this


Is my match – this will match a drive and a path up to

It’s a lookahead (zero length assertion). It will check for “bin” but not include it in the match

It’s a negative lookbehind (zero length assertion again). It will make sure that the letters fil don’t immediately proceed the match. This is to stop e:// being the match i.e. the e from file.

Clearly this assumes that the bin folder is directly under the root path as it normal is. If it isn’t in your app then break out your favourite Regex editor and write your own. It will make a man/woman/scared child of you.

(* Hardly anyone likes it – well I haven’t met many)

Useful Links
Full disclosure – the first bit of this is from this SO question. The extension I did with my very own coding fingers
Regex storm – C# regex tester. Very good. JavaScript based testers don’t work with this as they can’t do negative lookbehinds.
Look ahead, behind and all around with zero length assertions

From Classic ASP to React

Where it all began

I’ve been a software developer for over 16 years. It’s not that long but in terms of software development it’s pretty long time. Perhaps it’s like dog years – 1 development year equals 7 normal person years so actually I’ve been a developer for 112 software dev years. That seems more like it.

Over that time I’ve seen 4 major shifts in web development. Shifts up to new versions happen all the time – this is more where everything you know needs to be put in the bin and you start up again. Seems harsh but that’s the business and if you don’t like it then it’s perhaps time to move on. I’m shifting again to Node.js and React but as I do it’s kind of interesting to look back at the other shifts and how I felt about them at the time and how good they were in retrospect.

Classic ASP

It’s where it all began. Asp files with VBScript and <% %> to poke holes in the html to fit the programming stuff in

It’s all about the response.write. I loved it.


  1. Interpreted language – no compilation
  2. Written in scripting language like VBScript or JScript
  3. One file called *.asp. Everything is in there.
  4. One file per page
  5. Lots of use of Response and Request objects. Felt like you were working with the architecture of the web rather than against it
  6. Stateless

How excited was I to use it?

Ecstatically excited. I loved coding in it. Dynamic web pages that could squirt out content for each individual user. Amazing. It was all interpreted – no compilation here – no need for it. I did this for a Masters project and we all loved it. My supervisor was talking about PhDs in it.


It wasn’t perfect. The downsides were

  1. Terrible IDE. It was MS InterDev and it was unusable. We all used to code in EditPad Pro which at least had colours.
  2. No structure. You could put COM+ components in to force some structure into it but you would only do this if you really hated your coworkers.
  3. No debugging unless you count writing acres of Response.Writes all over your code
  4. No state management at all. You want to persist the state of a textbox then do it yourself …

which sets the stage for

ASP.Net Web Forms

A proper compiled language with a new framework and new languages to boot .To get a flavour here is the ubiquitous page load event

Felt radical at the time.


  1. A compiled language – Wow!
  2. Code behind – split files with markup and code in separate files combined with partial statements
  3. Highly abstracted – managed through page life cycle events
  4. Stateful – Automatic state management through View State

How excited was I to use it?

Passed myself with excitement. I got to build a new server first to host it and I had a big silver machine on my desk making a sound like an aircraft for months. And that was just the start – new language, new IDE that worked, proper code and architecture. Who wouldn’t like all this.


The world moved past webforms and while they were good initially, the advent of more client side techniques such as AJAX showed it’s limitations

  1. Worked very badly with JavaScript. WebForms mangled HTML element ids and made it difficult to work with
  2. It was really like windows programming for the web. While hiding the complexity of the web might seem good I’m convinced that webform programming led to a cohort of web developers who really didn’t understand the nature of the web.
  3. Inefficient – lots of postbacks and ViewState (stashing the state of the form to persist it) was massive and came over the wire every time.
  4. Very difficult to unit test. Too many tightly bound dependencies
  5. In the end I hated some of the components. Some were good like ListView and some were made for abuse and torture such as the UpdatePanel. Nest these babies and watch the bad times roll.

Things looked a lot brighter over at the Rails community so we got …..


Model, View Controllers in the Net world. It was a proper architectural pattern that was fully unit testable. It wasn’t pretending to be windows programming – it was the web and it was proud of it. Clearly still very much used today.

How excited was I to use it?

It wasn’t so much as excited – I was relieved. After fighting against webforms, here was something that worked with you. It was almost back to classic ASP in some ways so I felt like I was coming home.


  1. Skinny controllers, dumb Views and fat models
  2. Clever routing so it wasn’t one file per page any more. That more than anything amazed me
  3. Worked well with dependency injection so was testable
  4. Worked well with JavaScript. Generally felt like the web
  5. Stateless again


Honestly I just like MVC and always have done. If pushed I might say

  1. It still posts back so not as responsive as it could be
  2. It’s a different stack to front end so you would need to know C# and JavaScript
  3. It’s easy to write badly – massive Views full of logic aren’t good

But while we weren’t looking Node.js was discovered and we get….


Or I could have said Angular or Ember or fill in the blank with your favourite framework. For me, it’s the most radical shift yet because it’s not the Microsoft stack – we’re not in Kansas any more. It’s all in JavaScript, even the server. And while it’s not restricted to the client it’s focus is around ‘reactive’ single page applications (well my focus is anyway).


  1. Highly componentised
  2. JavaScript with HTML like syntax embedded in
  3. Single page application (often)
  4. View only .
  5. Blazing fast if on single page app – uses Virtual DOM to only update what it needs to on the page
  6. Back to stateful (if on single page app)

How excited am I to use it?

I feel pretty fortunate to have to opportunity to use this in a commercial setting. I’ve always liked JavaScript and it’s fascinating to see it build out a large scale application. I like Angular for the same reason. So I’m excited once again.


It’s not all gravy though. Downsides include

  1. It is a steep learning curve and fast moving so the curve keeps shifting
  2. It’s JavaScript which is great but it’s easy to write terrible JavaScript so terrible React
  3. You’ll need a decent architecture to go with it like Redux – not a disadvantage but you need to be aware of it
  4. It’s just the view so the rest is up to you to (re)invent.

Looking Back and Looking forward

I feel all misty eyed looking back and this is just one aspect of the development I’ve been involved in. There’s ORMs, mobile development, testability, ASP Core, the rise of Dev Ops and on and on and on. Headspinning but great.

What’s next – it’s just so hard to say. I reckon .Net Core will take off, JavaScript will be replaced or transform to something unrecognisable, everyone will decide they hate ORMs and rediscover stored procedures, machine learning will be big, driverless cars will start to fly and we will all go to live on Mars with Elon Musk. Or maybe someone will invent a web framework which combines the best of classic, web forms, mvc and react; perhaps like this ……

  • The simplicity of classic ASP
  • The rapid development capabilities of web forms
  • The testability of MVC
  • The blazing speed of React

Can someone invent that one please.

Useful Links
Classic ASP examples
WebForms page management life cycle
Microsoft site for MVC
Main page for react from FaceBook this time

Shorter syntax for Node.js module import

I’ve found myself writing a lot of import module statements during React development that I could have shortened. It’s a bit dispiriting when everything above the fold in your code is a boilerplate import. To give an example – this very simple React page

(this demo app is so bland I actually tarted up the image in photoshop – and it’s still bland)

Is constructed from this component

Even in this simple example, I’ve a bunch of imports from the same Alerts module. This could potentially go on and on and has done when I’m using something like React-Bootstrap. It’s not pretty. Happily this can all be shortened to one line thus

When I first saw this I found it baffling and unexplained – especially when just importing 1 object from a module e.g.

Suddenly there is curly brackets in the way. What’s all that about?

It’s all in the Destructure

It’s using ES6 object destructuring to do this magic. A simple example of object destructuring would be

The first object is automatically split into 2 variable when assigned – this is the destructuring

So our react import is the same as this in essence. Label.jsx is the component (object) we are importing

The export at the end is what is going to be destructured – we could simplify this further and omit the property names (with more ES6)

Anyway that’s not strictly relevant. Explaining onwards – the require squirts out the object and the destructuring assigns it to 3 variables which we can use in our page

This can be rewritten as an ES6 import statement which will transpile down into require with something like Babel if need be.

It’s this form in particular I often see in code samples and the like. So that’s explained then and a little bit of the grey fog has lifted. Lovely.

Useful Links
ES6 Destructuring – good detailed explanation
This is all underpinned by Node.js CommonJS module load pattern – that’s the require bit. More detail above.
The sample code isn’t much but as ever the code is on my GitHub site. It’s using webpack as the task runner which is different to the gulp runner I’ve been using. Probably better if I’m honest.



Only 92% Happy According to Cognitive Services

I’m particularly pleased with the photo of myself on this blog. I normally look a bit odd on photos but this one was taken about 2 days into a new job for an id card. I still had the new job glow. I was relaxed, tousled haired and the future lay ahead bright and clear. I look happy. So I thought I would upload it into Microsoft Cognitive Services Emotion API to get the confirmation that was indeed 100% happy.

I am shocked that even at my most happy I only achieve 92.8% happiness. My British reserve clearly means that I hold back 7% for that neutral stiff upper lip feeling. There are flickers of other emotions with contempt peeking out. Where does that come from ? It’s a new job. Surely contempt should only be registering when I’ve been there a month or two. I uploaded an uncropped image of myself a few months previously and I was registering about 3% fear . The only difference is that the very top of my head was visible that time. I’ve clearly got a very fearful haircut.

Is there a serious point to this? Probably not but it is my first foray into machine learning and as a professional software developer it certainly won’t be the last. I’m pretty fascinated about it. I hope I can start to register 100% happiness when I get into it more. At least 95% – come on!

Another Free JavaScript Book

My least viewed blog post is the one about a free JavaScript book. So building on that lack of success here is another post about another free JavaScript book. You don’t know JS: Up and Going by Kyle Simpson is currently retailing for zero pounds and zero pence (or zero dollars if you prefer) at Amazon kindle store and it is worth a read.

It’s a brief trailer for the other 5 pay for books in the series but does a good job of going over the basics and the not so basics. Mr Kyle makes the interesting, and probably correct, argument that it’s possible to write entire applications in JavaScript without knowing a lot of the language. It certainly accords with my own experience – there is a lot of dodgy JavaScript around and not so much well crafted stuff. So he’s issued a bit of a call to arms for developers to learn all the language and not just the ‘Good Parts’.

I’m not sure if I’m going to read all the books in the series but I’ve bought the ES6 one and that’s also very good but sadly not free. I guess the man’s got to be paid somehow.