What I learnt from building ugly ToDo lists in JavaScript and JQuery

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.

What I learnt building an Airport Explorer with ASP.NET Core

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.

Hello WordPress.com

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.

 

Some recent podcast episodes

I have listened to these episodes multiple times now and have been able to extract more value and extra insights from them on every playback.

I hope you find them enjoyable as much as I have.

Akimbo: No such thing (as writers block)

Seth Godin’s podcast is superb, this episode on writers block is my favourite.  In it he argues convincingly that there is no such thing.

Developer on Fire: Episode 196 Rob Conery

Not sure how I found Dave Raels podcast, Developer on Fire but I am glad I did. In each episode Dave interviews famous and not so famous programmers. I have enjoyed rummaging through the archive listening to interviews with Gerald Weinberg, Ward Cunningham, Dave Thomas, the list goes on.

My favourite episode features Rob Conery. In this episode they talk about Rob’s book; The Imposters Handbook (a superb book!)  but it is the discussions on the Perception of danger and Getting over yourself that really make this episode special for me.

The Hello World Podcast: Episode 12 Scott Hanselman

As well as hosting one of my favourite podcast, Hanselminutes Scott is a fantastic guest. In this episode, Scott  talks about retaining some perspective even when your project is being chased by ninjas and the common trait his mentors share.

 

NDC 2018

IMG_0649-Copy

I try to attend a developers conference once a year and this year I attended NDC London 2018.  I was surprised that only two developers out of the many I had asked  before going knew of the NDC brand of conferences.  I discovered NDC thanks to Carl and Richard of .NET Rocks! Thanks gents, I owe you.

Just in cases you are not aware of what NDC is, here is a brief description courtesy of the NDC London site.

About NDC

Since its start-up in Oslo 2008, the Norwegian Developers Conference (NDC) quickly became one of Europe`s largest conferences for .NET & Agile development. Today NDC Conferences are 5-day events with 2 days of pre-conference workshops and 3 days of conference sessions.

NDC London

In December 2013 NDC did the first NDC London conference. The conference was a huge success and we are happy to announce that the 5th NDC London is set to happen the week of 15-19 January 2018.

I didn’t attend the pre-conference workshops so my NDC adventure started on Wednesday. First impressions of the conference and its venue, The Queen Elizabeth II Centre, Westminster were superb; upon arriving there were no queues to register another plus was that the cloak room was free which although a small touch was one I really appreciated.

Throughout the conference continuous high quality hot drinks and food was served. Starting with cakes and pastries and moving on to a variety of hot food.  I wouldn’t normally mention food at a conference but it was of a standard that I had not encountered at other conferences that I had to write a few lines about it.

IMG_0657-Copy

My reason for attending was to hear a number of people whose podcasts I listen to, books & blogs I have read or have helped me by providing answers on Stack Overflow speak. As a newbie to this conference I did not know what to expect from the talks but I was not disappointed and for me the conference experience went into the stratosphere from here on in.

The talks are scheduled to last one hour and as you will see from the agenda they are on a wide variety of subjects. The presenters did not disappoint. There was no death by PowerPoint, no about me slides, no err/errms or the dreaded “like”.  The presenters were passionate about their topics and were clearly enjoyed themselves engaging with their audiences. Some had a slight more conversational style whilst others used self deprecation and one in particular used the medium of song (thank you Jon Skeet that was unforgettable). One of the common traits that I noticed is that many of the presenters are building and experimenting with “stuff” all the time.

As is the norm after a talk\session the audience are invited to give feedback and NDC has probably the best I have so far encountered.  As you leave the room after a talk just throw a colour in the box. Brilliant.

IMG_0602-Copy

Here are the sessions I attended:

Wednesday

Keynote: What is programming anyway?
Felienne

Sondheim Seurat and Software: finding art in code
Jon Skeet

You build it, you run it (why developers should also be on call)
Chris O’Dell

I’m Pwned. You’re Pwned. We’re All Pwned.
Troy Hunt

Refactoring to Immutability
Kevlin Henney

Adventures in teaching the web
Jasmine Greenaway

C# 7.1, and 7.2: The releases you didn’t know you had
Bill Wagner

Thursday

Building a Raspberry Pi Kubernetes Cluster and running .NET Core
Alex Ellis & Scott Hanselman

An Opinionated Approach to ASP.NET Core
Scott Allen

Who Needs Dashboards?
Jessica White

Hack Your Career
Troy Hunt

HTTP: History & Performance
Ana Balica

Going Solo: A Blueprint for Working for Yourself
Rob Conery

NET Rocks Live with Jon Skeet and Bill Wagner – Two Nice C# People

Friday

The Modern Cloud
Scott Guthrie

Web Apps can’t really do *that*, can they?
Steve Sanderson

The Hello World Show Live with Scott Hanselman, Troy Hunt, Felienne, and Jon Skeet

Tips & Tricks with Azure
Scott Guthrie

Solving Diabetes with an Open Source Artificial Pancreas
Scott Hanselman

Why I’m Not Leaving .NET
Mark Rendle

Summary

NDC London 2018 was the best conference I have ever attended. I have returned from it motivated to do more; to experiment and try stuff that I hadn’t even thought about.

There were so many highlights for me but having my photo taken with Carl and Richard was the best. Seriously guys you rock!

IMG_0537-Copy
 

Boxing and Unboxing in C#

This post is an aide-memoire as I learn more about boxing and unboxing in C# and is based upon this part of the C# docs.

Boxing

Is the process of converting a value type (such as int or bool) to the type Object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it in the managed heap.

Boxing is implicit.

int i = 10; 
// this line boxes i
object o = i;

Although it is possible to perform the boxing explicitly it is not required.

int i = 10;
// explicit boxing
object o = (object)i;

Unboxing

Extracts the value type from the object.

Unboxing is explicit.

int i = 10; 
// boxes i
object o = i;
// unboxes the object to the int value type named j
int j = (int)o;

Performance

Both boxing and Unboxing are computationally expensive operations.

C# Utility to emulate the XPath 3 function path()

I recently needed to examine a number of XML files and print out the element names that contained text greater than X number of characters. In addition I also need to print the location of that element within the XML document.

i.e. given the following document


  
    Microsoft Visual C# Step by Step
  

…if I was interested in book titles that had more then 10 characters I would want to see:

/bookshop/book/title/
Microsoft Visual C# Step by Step

Whilst it is straightforward to return the text node, finding the XPATH location proved to be more challenging than I initially thought. The reason being is that whilst XPATH 3.0 introduced the path() function that returns the current XPATH location, the number of programming languages that I know (PL/SQL, Python and C#) do not implement XPATH 3.0 yet.

As a result I had to build my own utility. I chose to write this in C# as this is a language I have spent the past 18 months learning and I am now looking for real world problems I can solve using it.

The utility can be found on github. The “engine” of the utility is copied from this Stackoverflow answer: http://stackoverflow.com/a/241291/55640 provided by Jon Skeet.

Although far from feature complete I hope it will give someone facing a similar challenge a head start.

Let me know what you think.