Get started using web API’s – Luas Forecasting API

My JavaScript excursions have taken a damper as of late. Without much digression, the next mini project I want to tackle is how to consume an api and present it on a page. I’ve been having a bit of internal conflict if I should conduct this on GitHub or codepen and came to the conclusion that i’ll do it on both – first attempt on GitHub and a cloned, improved version, on codepen.

For this tutorial, of sorts, will include the following:

  • Consume the public Luas API
  • Extract relevant information and display on a page

At this point it will only be for a specific location and inbound shuttles. At this stage the HTML & CSS have been setup, as well as the AJAX script to call the Luas Forecasting API.

The API only seemed to show tabular information and not much of explanation or examples are available, bar one on the data.gov.ie page for the aforementioned API. It seemed to be only displaying the current status, however, when it was retrieved, the response contained all the relevant information that is needed i.e. the stop name, inbound/outbound and luas arrival times.

Luas Forecasting API response message

Luas Forecasting API response message XML

The next step will be to parse the XML received and push the relevant info to the page. The code so far is available on GitHub. One issue is the GitHub page the AJAX call refuses to play nice. I’l have to look into that as well the next time around, stay tuned!

 

Javascript functions

JavaScript allows numerous ways in which functions can be created and invoked.

Named functions

These have a name associated with them

function nameOfFuction(){ // code goes here; }

Assigned functions

These are usually named or anonymous functions which are assigned to a variable

var someName = function someFunction() { // code; };
// invoking the function like so
someName();

In this case the function is considered a statement so needs to have a semicolon unlike a typical function declaration.

Anonymous functions

These are functions without a name and are most suited for assignment to other variables, in fact the previous function type would be far better using anonymous functions.

var someName = function someFunction() { // code; };
// invoking the function like so
someName();

Another way anonymous functions can be used is by having it as the return value of another function

function mainFunction(param1, param2){   // code   return function(){
      // code 
   };}d

In order to utilise this, the main function itself will NOT work as it will only return the function statement it contains within its body. It is returned in a structure known as a closure:

 // This will return anonymous function from the main function body
mainFunction(paramValue1, paramValue2);
( function() { //code } )

It can, however, be assigned to a variable and thus run like an assigned function

var functionRunner = mainFunction(paramValue1, paramValue2);
functionRunner();

or it will need to have a pair of parenthesis added to the end of the function call if it is to be invoked like a standalone function, which will not be returning a function.

mainFunction(paraValue1, paramValue2)();

What is happening is that  the returned anonymous function will get the ‘()’ and be invoked like a regular function call. This is known as immediate function invocation.

A brief intro to Node.js

This is a topic I’ve been meaning to approach for a while now. As it happens, one of my college courses – Web Applications – requires a project built using Node.js, so what better time to tackle this.

I had mentioned Node.js in a previous post, where I was talking about the various environments JavaScript can be run in. This post won’t go into the history or specifics of Node.js; the main exercise will examine the various items found in the sample code for creating a simple Node.js server – which will explore and detail node specific aspects as well as JavaScript patterns used. The code can be found on the About page on the Node.js site:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Play by play

The very first line of code, allows us to import the module ‘http’.

const http = require('http');

This is the implementation method that is specified in CommonJS, which is an ecosystem for JavaScript outside the browser. This is a synchronous system which allows importing of modules or files; since everything will be on the server side. This allows us to import the module http.

The next two lines set the IP address of the localhost (the machine you are currently on) and the port to listen to for incoming requests.

const hostname = '127.0.0.1';
const port = 3000;

Immediately following that, the createServer() method is called on the http instance we created on the first line. Which is then assigned to a constant called server.

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

This is passed a call back function with two parameters and uses an arrow function (read more about it here [1] [2]). This createServer() method will be invoked by an incoming event, in this case web requests. The req parameter will contain all the incoming request’s details. The res parameter will handle the response which will be sent out. In this case it’s setting its statusCode to 200, which signifies that the request was handled successfully. After which the response’s header information is set to indicate it’s content which in this case is plain text. And finally some plain text output is shown while closing the response – this will be displayed in the browser.

The final section of the code, referencing the server which points to the http.createServer() call, is set to listen on the port and host IP address set above.

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

The arrow function will display the message indicated while the server is running in the node.js environment giving us a visual that things are working.

There you go, this was just a quick run down to help try and elucidate, both for me and anyone reading this, what is happening within this simple node.js server code. Stay tuned for more practical topics on the matter.

Simple JavaScript Timer: Part III

The remaining requirements from the last session are:

  • Refactoring the two buttons to just one for starting/stopping the timer
  • Being able to capture snapshots of the timer countdown on a button press.
  • Clearing the snapshots and resetting the timer on another button press.

Refactoring the two buttons to a single one which would handle the starting and stopping of the timer proved to be tricky. For the single buttons Start and Stop a reference to the calling object itself was passed to the function and based on the innerHTML of that object, the button, the code would start or stop the timer.

Button innerHTML with JavaScript

JavaScript code to specify which button is being clicked

When only one button was present, there was nothing that could be used to identify what ‘state’ the timer, by extension the button, was in. Tried one or two ways to sort this but most of them resulted in the single button functioning once to start/stop the timer but after that it wouldn’t function at all.

What finally did it was the creation of a Boolean to keep tabs of whether the button was clicked. Simple but boy did it take some time getting to it. [see commit]

JavaScript button handler code

JavaScript button handler

With that out of the way the only thing left to do was to capture the counter values and show them beneath the actual counter and reset the captured values and timer count. This was simple enough and only required adding to the innerHTML of the display area and clearing them. [see commit]

One final item remaining was to enable key presses to activate the same functions as the button presses. These were:

  • ‘s’ to start and stop the timer
  • ‘t’ to record the times
  • ‘r’ reset the recorded times and timer

This presented some challenges as I wasn’t too sure how the code would be invoked from a separate script file. I thought it would have to go in the actual HTML document. But referring to the document element from the script file and adding an event listener to it did the trick.

Document event listener setup

Document event listener setup

From there it was just a simple callback function, part of which can be see above, with the event object passed to it from which the keypresses could be retrieved.

And there you have it, another successful simple  project completed. You can see it in action here https://donyd.github.io/Simple-Timer/

There was one final issue, this time with Github. You can see the code at various iterations of the work in progress, however the final Github page only shows the final results.

Catch up with the initial posts about this piece:

 

JavaScript callback functions

Another primer, this time on callback functions.  Call back functions are basically a function that is passed as an argument, or included wholly as in the case of anonymous functions, in another function’s call. It hails from, wait for it… functional programming.

One way of understanding how callbacks function *pardon the pun*, is based on one form of creating a function in JavaScript:

var someFunction = function functionName() {  // code goes here}

This is known as a function expression, whereby a function is declared and assigned to a variable. [1] Now, someFunction can be used to invoke functionName() just by calling it similarly to how a function would be called i.e. someFunction();

In a callback function pattern, in one scenario, a named function which has already been declared is passed as an argument in another function.

function gradeBoost(x){ // call back function
   return x += (x *= .15);
}

function bonusQuestion(receivedMarks, callback){ // uses callback function
  return callback(receivedMarks);
}

var finalMarks = bonusQuestion(45, gradeBoost));
console.log(finalMarks);

So, in the example above, gradeBoost is the callback function. In bonusQuestion, the second argument ‘callback’ is set to receive (be assigned) the callback function, gradeBoost, similar to the first code explanation block above this example.

Within the body of bonusQuestion, the assigned function is setup based on the parameter list of the gradeBoost callback function. The result being when bonusQuestion is called and passed in gradeBoost as the callback function argument, gradeBoost returns the result of the calculation to the bonusQuestion function call.

This is in essence how callbacks are cast and called. For some more applications of callback functions see the post on Asynchronous JavaScript.

Handy little methods for Xrm.Page calls in browser for Dynamics CRM

Based on the last post about retrieving Microsoft Dynamics CRM record based information from the console ‘Dynamics CRM – Access GUID from the browser console‘, I thought I write up some other useful bits that can be used to get information in a pinch.

Most of these have be run from the viewport where the record in question is open, unless otherwise stated.

Get an entity’s origin

frames[1].Xrm.Page.data.entity.getEntityName();

This is particularly handy when you want to know the logical name to work with programmatically. All this without having to open up the solution or form and plow through a few forms and several clicks.

Get logical name for controls in the controls collection

frames[1].Xrm.Page.getControl(0).getName();

The controls collection is a child of the ui object, which itself is a child of the Xrm.Page object. [See the visual layout on MSDN]. The index allows retrieval of control items as they occur on the form.

Get logical name for control based on display name

frames[1].Xrm.Page.getControl(0).setFocus();

Now there are no direct method calls, that I found or aware of, that could get you the logical name for a field based on its display name. Which is a big shame because that would be a very useful one.

Now this might be somewhat tedious based on what wants to be achieved, and most definitely based on the number of fields on the form, as the user will have to randomly call the setFocus() method on a guess of where the control might be in the index based on position i.e. if the field is placed in the middle of the list of fields, chances are the index will be roughly half of the length of the count of fields.

But once the focus reveals the field that the user is interested in, the previous method getName() can be used to retrieve the logical name using that same index.

Conclusion

These calls are part of the Xrm.Page model which can be referred to on the MSDN site. However, they can be utilized for quick little views at relevant information via the browser’s console.

JavaScript: Asynchronous Programming Primer

Some aspects of JavaScript are well known, or well loathed, mostly because it’s only partially understood. Some of these include that JavaScript is an interpreted language, which is not entirely true, which we’ll save for another day. Another is that JavaScript is a single threaded language, which is true but there are structures which allow more than a single thread to operate.

A city called asynchroni… city

Asynchronous programming allows multi-threading via Web API’s (such as event handlers) that handles processes and return tasks to the browser separately from the main thread.

The cycle follows that when a function or other code is encountered, it is placed on the Call Stack and the stack at this point is unavailable till this code is executed. The Call Stack is the data structure that handles function calls in the order that they were executed, i.e. first in, last out. This stack is the main thread that JavaScript runs on in browser. If, however, an asynchronous function is encountered, the code is deferred to a non Call Stack process to handle,

These other processes run the code, which are sent to it as callback functions, whose results are then queued in the Event Queue. This is eventually passed back to the Call Stack when it is empty. A common Web API that processes such asynchronous calls are Timers, these include:

setTimeout()

The setTimeout() method can be used to put a task on the event queue.  The method takes a callback function as the first argument and the amount of time to wait as the second argument. The time value is numeric in milliseconds. e.g. 500, 1000 which equates to half and one full second,

setInterval()

This is similar to the setTimetout() method however, the call back function will be called non-stop after each time value period lapses.

Stopping Timers

Each method above can be stopped using the related stopping methods:

  • clearTimeout()  // for setTimeout()
  • clearInterval()   // for setInterval()

When the respective timer events are created, it returns a numeric id which can be stored in a variable and then passed on to the methods indicated. This allows targeting a specific timer instance to be stopped.

Conclusion

Asynchronous programming allows processes, which would otherwise tie up the browser and make it unusable to another handler and return the results to the main thread. Thus allowing the application question to be efficient and responsive.

This is just a small primer on the asynchronous capabilities of JavaScript on the browser side. Stay tuned as more write ups will focus on this topic and related areas.

Simple JavaScript Timer: Part II

In the last part, of ‘Simple JavaScript Timer: Part I’, the asynchronous function was running as soon as the page was loaded. A few reasons why I assumed this was happening:

  • Since there were no synchronous calls, there was nothing on the call stack and therefore it just ran
  • Maybe some sort of mechanism was needed to prevent this from occurring

However, the real reason was that I’d invoked the setInterval() function and assigned it’s return to a variable (erroneously thinking I’d created a named function by assigning an anonymous function to a variable, which was contained within the setInterval()). So the asynchronous setInterval() was running when the script loaded and updated the innerHTML of the element it was attached to. [see commit]

This was sorted by enclosing the setInterval call within a function and then invoking that on the button’s onclick event. [see commit] The next item was to stop the timer once it was started. But that had its own issue in that the timer would not stop. Turned out that the id returned by the setInterval function was scoped to the first conditional branch and would not transfer over to the second conditional:

Asynchronous JavaScript: setInterval and clearInterval

Asynchronous JavaScript: setInterval & clearInterval

Placing the variable outside the conditionals, but still within the function body, resulted in the same thing. The variable had to be declared outside the function’s scope – read more about scope here – as declaring the variable without the var keyword still does not set its scope to global. The latest commit with all the issue fixes can be found in this commit [see commit].

So that still leaves the two outstanding requirements from the first post, as well as a new one (which is just to refactor the two buttons to just one for starting and stopping the timer):

  • Being able to capture snapshots of the timer countdown on a button press.
  • Clearing the snapshots and resetting the timer on another button press.

Those and the final wrap up can be seen in this post: Simple JavaScript Timer Part III
See the demo in action on the Github page here: https://donyd.github.io/Simple-Timer/

 

Simple JavaScript Timer: Part I

Ok following along the heels of the last mini project run down ‘Binary to Decimal Convertor‘ is a JavaScript Timer.

This project will borrow items and techniques learned from that excursion, one of which is how to showcase the various stages of the development process that shaped it. To that end, instead of codepen.io, github pages will be used. For the moment the source files can be found here: https://github.com/donyd/Simple-Timer and the commits will show the various stages involved as the project progresses.

Observances

  • So the same thing that tripped me up in the the Binary to Decimal Convertor happened here – I was trying to push a value into an HTML element instead of using the innerHTML property.
  • I’ve wired up a function timeElapsed to the onclick event of a button, however it seems to be running when the page is loaded.

So the next order of business is to correct the issue so the function is only triggered on the onclick event of the button it is attached to as well as the following:

  • Being able to capture snapshots of the timer countdown on a button press.
  • Clearing the snapshots and resetting the timer on another button press.