oraclefrontovik

Sharing what I learn

Virtual Box

I use Virtual Box with Windows 10 as the Guest Operating System. It is a combination that works well and other than the usual Windows update dance, it doesn’t cause me any distractions. 

Visual Studio Code

All my Angular development have been built using Visual Studio Code which allows me to build, compile and run my projects without leaving the editor. I switched from Atom and I haven’t looked back. Using it is a joy and it allows me to focus on the task in hand. Superb Stuff. 

For Angular Development I am using the Gitlens, TSLint and Debugger for Chrome extensions

Chrome DevTools

I remember the relief I felt when a friend showed me Firebug for the first time. I was having a torrid time getting to the bottom of an opaque JavaScript problem. Fortunately Tools for the Web Developer have come a long way since then and I use the Chrome DevTools every time I work with Angular; from debugging my code to inspecting elements to see what Angular has welded on to them. The things you need most are shown whilst tools you use on lesser occasions are tucked neatly away with menus that make discoverability easy. 

I haven’t got any real experience of using the Firefox Developer Tools so if I am missing something useful please let me know in the comments.

Installed but not yet used: Chrome DevTools extension: Angular Augury

Angular Augury is an extension to Chrome that was recommended to me via the Udemy course I am taking. This extension is used for debugging and profiling your Angular Application. I haven’t had to use it yet so will revisit this post once I have some real world experience of using it.  

Err. That’s it. How does your development environment differ? What am I missing? 

I have spent many months this year learning Angular. More accurately I have wrestled with Angular, left to try React then decided that to get the most out of learning these frameworks I need to brush up on my vanilla JavaScript skills which I proceeded to do before finally returning to Angular. Phew!

I have used several resources to get up to speed with Angular and what I found useful and others that were not so are listed here. At the end of the post I ask for resources that have helped you learn Angular so if you don’t get that far please leave your recommendations in the comments

The good: Udemy Course

A friend recommended the Udemy course Angular – The Complete Guide by Maximilian Schwarzmüller. At the time of writing I am about half way through and it is the most enjoyable Angular resource I have found. Max is a friendly, enthusiastic teacher and the course is highly polished and easy to follow along building the sample applications and experimenting.

In addition to the discussions around language features there are lots of useful nuggets such as how to understand the opaque Angular errors that you are bound to see in your early days with the framework and the use of the browser add in Augury which is a very useful tool for debugging and profiling Angular applications.

The bad: ng-book

I have only purchased one book on Angular which was the eBook edition of the ng-book The print version was not available at the time. This is a large book running to 650+ pages. I didn’t enjoy it and only got as far as chapter 3 before giving up. Not sure why I didn’t enjoy it, perhaps I didn’t like the style or the fact that I prefer printed books? I lost patience by chapter three as the app wouldn’t work and I had no idea why. 


If you have a recommendation for an Angular book please do get in touch.   

The ugly: Official Docs

My adventures with Angular started with the Angular home page, I built the Tour of Heroes sample application and have wandered through the rest of the documentation look for other stuff to try out.

I have found the documentation to be dry and not a place that rewards you for spending much time there and so far I have had little reason to return. Problems that I encounter normally result in a Google search followed by a visit to the StackOverflow question.

Perhaps as my experience with the framework grows and I need to look things up I will be spending more time with the docs. If my opinion changes I will ensure that I update this post. 

Help needed

If you have Angular resources that you think may help me no matter how small please leave a comment. 

The problem

You need to sort this JavaScript array in numeric order:


var numbers = [2, 1, 11];

Arrays have a sort method, so lets try using that


var numbers = [2, 1, 11];

console.log(numbers.sort());

The output from running this in Chrome 67 is that the array is now sorted as:

[1, 11, 2]

Which is not what we want, the number 11 is in the wrong place.

The Reason

This result is produced because using the JavaScript sort() without a compare method array causes elements to be sorted by converting them to strings and comparing strings in Unicode code point order.

Apologies! That was a bit opaque so lets take that last paragraph apart. The sort method first converts the numbers to strings so we conceptually have

“2”, “1”, “11”

The  UTF-16 code for each of these are obtained and these are respectively

0032, 0031, 0031 0031

With both “1” and “11”  having a lower UTF-16 code than “2” it should now be slightly clearer why 11 appears before 2.

The Solution

The sort method compares two values to determine which should come first. These two values are usually referred to as a and b. The sort method can have an function, anonymous or named as a parameter. This function is a referred to as a compare function. The compare function allows you as the developer to define the rules for sorting.

The compare function should return a number. That number will be  used to determine which of a or b comes first.

<0

If the compare function returns less than zero a should be shown before b

0

If the compare function returns zero, the a and b should remain in the same order

>0

If the compare function returns greater than zero b should be shown before a

Shown below is an example of anonymous compare function:

function(a, b) {  

  return a - b; 

}

This function can then be passed to the sort() method as shown below. The calls to console.log are instrumentation that you can use to see what is going during each of the three times the compare function is invoked.

 

  var numbers = [2, 1, 11];
  console.log('Original order: ' + numbers);

  numbers.sort(function(a, b) {
   console.log(a + ' - ' + b + ' = ' + (a - b));
   return a - b;
  });   

  console.log('Expected order: ' + numbers);

Pasting this into the Chrome console window will produce the following output:

20180724_02 .JPG

Stepping through the output, first displayed is the array in it’s original order.

The next two lines shows the results of the compare function and in this invocation the parameters a and b have the values 2 and 1 respectively

2 – 1 = 1 means that the compare function returns a number greater than 0 so that 1(b) will be shown before 2 (a)

The next line shows that the and b values for the final invocation are now 2 and 11.      2 – 11 = -9 which means that the compare function this time return a number less than zero so that 2(a) will be displayed before 11(b)

The final line shows the results of the sort and now the numbers are sorted as expected.

Acknowledgements

Another plug for this wonderful book which was the inspiration for this page Javascript and JQuery book by Jon Duckett

 

20180712_1.JPG

Not pretty

Here’s what I learnt when building two To Do applications. One was built using pure JavaScript and the other used jQuery with a smidgen of JavaScript.

Each To Do list had to satisfy several basic functions. The user had to be able to add tasks, remove tasks, save tasks and be able to retrieve them. These To Do lists are far from production quality but what I have learnt by building them will help immeasurably in my next project and the one after that and so on.

Tools

Both examples were built using Visual Studio Code, jQuery 3.3.1 and Chrome 67. Any text editor can be used instead of Visual Studio Code but I have found it to be a joy to use and is now a firm favourite of mine.

Javascript

Practical experience of using Web Storage to save and retrieve tasks.

 

Understanding Immediately Invoked Function Expression or IIFE. Whilst there are other reasons to use an IFFE such stopping name collisions in this example I have used an IFFE to call a function that retrieves the saved tasks once the Document Object Model (DOM) has been loaded.

 

Although there is only 200 lines of JavaScript I have become familiar and thankful for Chrome Devtools. Pressing F12 has become second nature when I need to find out what is actually going on with my code. From seeing errors shown in the console to adding breakpoints via sources, I have found Chome Devtools so intuitive to use.

 

Creating and removing input items dynamically. The To Do list needed functionality whereby a user could add and remove tasks which translated to being able to create input elements and attach them to the parent. When removing an item, the code needed to find out which task had been selected for removal before removing it.

 

When refreshing my knowledge of JavaScript I was having trouble getting to grips with which selector I should use when selecting elements of the DOM. Experimenting with different JavaScript selectors such as querySelector, getElementById for single element node selection and getElementsByName for selecting more than one node gave me a greater understanding of working with the DOM and the difference between the code required to handle one node compared to when a node list is returned.

 

jQuery

Use of the jQuery ready method. All the code used by index.js is contained within the jQuery’s ready method, the shorthand version of which is shown below
$(function() { 

   all code goes between the opening and closing brackets

}
Doing this ensures that the DOM has tree has been constructed by the browser.

 

Similar to the JavaScript version I learnt how to create and remove items dynamically and attaching or detaching them from the parent as necessary.

 

When working with items using the id attribute requires use of the # symbol followed by the unique name.  e.g. to select the following element:
0 tasks
The following jQuery expression is used
$('#Count').text($countOfItems);
Refactoring. As I was building this second ToDo list I could see ways to improve and do things better with less code. In addition whilst working on this version I discovered a bug with that would have also affected the JavaScript version as well so I was able to go back and fix it in both.

 

I really enjoyed working with jQuery and love the simplicity of selecting items and then chaining of actions to do interesting work with the selection but there were times that I thought pure JavaScript was a better fit. Within index.js you can see the function getLocalStorageAsArray() does not use jQuery.
Use of .each(). jQuery allows you to update all of the elements selected without the need for a loop. However there were times when I needed to perform some actions on each element found by a selection which meant use of the .each() method which allows you to recreate a loop in scenarios when it is required. This required a slight shift in thinking because it is too easy to think a loop is required (coming from another language) when a jQuery selection is all that is really needed.

 

A pleasant side effect of  working with .each() was that I needed to find out which iterator my .each() was currently processing and during my hunt for an answered discovered that the jQuery official documentation is really good and it succinctly pointed me to using using the index argument.

 

The number of lines of code when using jQuery versus pure JavaScript reduced the lines of code by about 50 lines (I’m in no doubt a more experienced developer could reduce both versions down even further.) I am not going to read too much into that because it is like comparing apples with oranges but for me it was an interesting observation.

 

Summary

I have surprised myself with how much I have learnt building these and how much fun I had doing so.

Acknowledgements

Javascript and JQuery book by Jon Duckett This is the best book I have read on JavaScript and JQuery and I have no hesitation in recommending this to you.

20180712_01.png

Limoges Airport details courtesy of Airport Explorer

Thanks to Scott Hanselman’s tweet. I went off and had an enjoyable couple of hours building Jerrie Pelser’s Airport Explorer and learnt a lot more than I was expecting.

20180712_02.JPG

Firstly the app is a single page ASP.NET Razor application, something I didn’t even know existed but now will be my first choice to use when developing an upcoming ToDo list requirement. I used the Mapbox and Google places API’s for the first time.

The Google API was particularly interesting because it has moved on since Jerrie’s book which meant that one particular line of code would not compile:

  if (photosResponse.PhotoBuffer != null)
            {
                airportDetail.Photo = Convert.ToBase64String(photosResponse.PhotoBuffer);
                airportDetail.PhotoCredit = photoCredit;
            }

The Google API I was using was version 3.6.1 which meant that the project would not compile with the reference to PhotoBuffer (shown in bold above) Reviewing Jerrie’s completed example on GitHub and I saw that the Google API used was version 3.2.10. So I learnt to install a particular version using the Package Manager Console

install-package googleapi -version 3.2.10

In addition my debugging skills were exercised when bad data kept my page from loading. It took a little while but I traced the problem to this line of code

 using (var reader = new CsvReader(sr, configuration))

and I had forgotten to add the entry in bold which handled the bad data!

I used GitKraken for the first time to manage my Git interactions and learnt how to undo a commit after remembering that I had left my API credentials in the source code!

My version of the Airport Explorer can be found here.

After several fruitless attempts to contact my previous web host in order to add HTTPS to this site I gave up and moved this blog to WordPress. Additionally I was getting increasingly bored with the management of a self hosted WordPress site with challenges such as deciding which versions of WordPress the hosting company would accept, which of the several plugins I used should be updated. A lot of noise confronted me each time I logged on when all I just want to put something up that I had learnt. So I have outsourced all of those distractions to WordPress.com.

The migration from self hosting wasn’t as painful as I thought and took about a day. Albeit this was going from one version of WordPress to another. The export functionality creates an XML file that contains posts, pages, comments, categories, and tags only. Importantly the export does not export images. This needs to be done manually. I used downML which downloaded all the images in a WordPress media library into one zip file.

Upon uploading the images to WordPress.com they had a different URL which meant when I imported my posts from the old site, none of the images referenced by the posts could be found. Faced with two options; amending the export script to change the URL for the images in each post or manually add the images. I chose the later simply because by the time I had developed the regex to find and then replace the URL’s, then tested and then fixed and retested and so on I could have made far quicker progress using the manual approach. If my back catalogue of posts had been greater I think I would have taken the programmatic route. Although not the most fun job in the world it is now done and I am pleased with the results. If you noticed any bugs whereby a post is missing an image please get in touch.

 

Lighthouse is a useful tool that is unfortunately tucked away within depths of the Chrome browser devtools. It performs an audit of a URL that you supply and provides a report based on scoring across five categories; Performance, Progressive Web App (PWA), Accessibility, Best Practices and Search Engine Optimisation (SEO).

The easiest method of taking it for a spin is to start Chrome, go to a page of interest, press F12 then the >> button and choose Audits

20180618_1.png

which that will bring up the Lighthouse home page.

20180618_2.png

Pressing “Perform an audit” will present you with options to include or exclude one of the five categories.

20180618_3.png

You invoke Lighthouse by selecting “Run audit”.  After an interval the report will be displayed. The Lighthouse report for google.co.uk is shown below.

20180618_4.png

The top bar gives information about the URL used and the emulation options used. Immediately underneath are the five categories with a score between 0 and 100, where 0 is the lowest possible score. This page explains the Lighthouse v3 Scoring Guide.

Selecting a category will take you to the relevant section of the report.

20180618_5.png

It is also possible to invoke Lighthouse using the Node command line tool. First install it using the Node Package Manager. I have used the -g option to install it as a global module.

npm install -g lighthouse

Once installed you can then use a command such as the following to run Lighthouse. The view option automatically opens Chrome and displays the HTML report.

lighthouse https://www.google.co.uk --view

If you prefer the output in JSON the following will create a file in the directory the command was run from

lighthouse https://www.google.co.uk --output=json --output-path=./google.json

Acknowledgements

Lighthouse home page

The Building Web Applications for the next Billion Users with Ire Aderinokun episode of Hanselminutes first made me aware of Lighthouse.