Algorithm

3. Base64-encode the header and payload independently. This gives us the unsigned token.

4. Using the HMAC SHA256 algorithm, and a secret key value, generate the signature for the unsigned payload.

A token, therefore, will have three segments: a) header, b) payload, and c) signature. The first two are Base64-encoded JSON objects, and the third is the encoded signature of the first two segments. This can be seen in action when generating a token with the debugger at jwt.io:

For generating the third segment of the token – the signature – the process is different. In this case, we need to generate a hash digest of the header and payload, along with a 256-bit secret value, then encode that digest. The algorithm for this is given as:

Aside from calling the API to render the DataTable, this JavaScript function makes a request to the /Search/JsonResults controller action when a page load is triggered. The controller action, in turn, will fetch the subsequent x number of records from the source. Set the ‘serverside‘ attribute to ‘true‘ for this.

The (abbreviated) controller action for this originally looked something like:

Ordering results in DataTables should be easy, yes? Actually, no, it wasn’t, since the application here used a single DataTable instance to present tabled data for doctors, organisations, third-party providers, other personnel, sites, tests, etc. In this case, the data fields/columns are defined by the JSON response from the controller, and they’ll change according to the dataset set being selected by the user.

This was my initial code, simply to get a working LINQ query and to create a placeholder for a dynamic variable:

The above is a LINQ statement to sort the data (ascending) by Organisation Postcode – I picked that variable arbitraily from the JSON response. We use DataSet to create an in-memory representation of the data being fetched, so the DataAdapter would limit the read volume to the number of records being requested by DataTables.js. LINQ is used to query this in-memory data instead of the database itself.

What we need to do now is replace the ‘Organisation Postcode‘ with something that could dynamically represent any column name in the JSON response. The LINQ queries I ended up with were:

This line, in turn, creates a new instance of the following class:
public class Order
{
public int column { get; set; }
public string dir { get; set; }
}

Now, it might be the case that null values are returned for a column, which screws the ability to pick that column as a sorting criteria, so we use the following to populate the null fields with whatever is derived from DateTime.MinValue:is DBNull ? DateTime.MinValue

The above is a short-hand way of creating an if/then statement. If the value is null, set the value to DateTime.Min.

Note: Parsing JSON Response to Get Columns

There is another method in the SearchController:

Set the variable ‘result‘ simply as the ‘[‘ character to begin with, to mark the beginning of an array.
In the next instruction, if the result is not ‘[‘, in other words, if there’s already something in the array, we append a comma to mark the end of the last element before executing the next instruction. If we’re not at the start of an empty array, ‘result‘ is appended with:{ "data": "{0}", column.logical_name }

The ‘column.logical_name‘ refers to a string coming from the database table that identifies it as a column name.
After the array has been populated, ‘]‘ is appended to ‘result‘, to mark the end of the array, and it is returned to the calling function as a JSON response.

Like this:

Normally Microsoft’s Map application on a Lumia device is perfect for travelling, but it turns out there isn’t an offline map available for Japan. After trying several alternatives, I figured that I could maybe create something better as a feature to my side project. I needed this to be compatible with the Edge browser, and for it to function effectively without a WiFi connection. Is this achievable using just HTML5, CSS and JavaScript? Yes, it is. Here are the results:

Creating the Offline Map Files
The first thing we need is data, in the form of map tiles, and the easiest way of getting this is by generating them using the Mobile Atlas Creator. This is straightforward to use – simply select the region to map and the zoom levels the application would display (e.g. all of them), and create the atlas .zip archive. The archive contains sets of numbered directories and files – I’ll explain why they’re structured that way and how they’re read by the application. For the data source, ‘OpenStreetMap Public Transport‘ gave the clearest tile images.

Leaflet.js API
There are multiple JavaScript APIs for rendering maps in the browser and showing the current GPS position. I went with Leaflet.js, as it’s lightweight, functional and reasonably well-documented.
This is roughly how Leaflet.js does the rendering: Leaflet.js will select the images to display according to the co-ordinates set in the code. The API will translate the co-ordinates into two five-digit numbers to select the file paths of the tiles to display. There is a third variable, which is the zoom level and layer – this determines the root directory that Leaflet.js will fetch the tiles from.

The three aforementioned factors are variables, z, x and y in the code. These correspond to the zoom level, latitude and longitude. All three are initially determined by the setview() parameters – the default zoom level and initial map frame displayed, but they’re changed by the JavaScript controls as the user scrolls and zooms in and out.

Geolocation
Leaflet.js includes a feature that makes use of the browser’s geolocation API. We include a button with this event trigger:onClick="javascript:getLocationLeaflet();"

Of course, there’s no map in the screenshot here, as there aren’t any tiles for that location.

Location Markers
Another feature essential to my application is the ability to mark important locations on the map and display information about them. In this example, the placemark locations and popup messages are hard-coded into the JavaScript, though it should be possible to load that information from a GeoJSON file without having to use something like Node.js (I’m still working on this).

Like this:

Web Storage is an HTML 5 feature that enables JavaScript to store and retrieve data in the browser application itself. There are two APIs for this: localStorage() and sessionStorage(). The former writes data to persistent storage, while the latter only stores session data. Both APIs provide setItem() and getItem() for writing and reading the data.

If the browser displays an alert when running the above code, you’ll know it’s working because the alert function has fetched the values from Web Storage.

If, on the other hand, the Developer Tools displays an ‘Uncaught DOM Exception’ error , the browser’s privacy configuration is preventing the JavaScript writing to Web Storage.

It is possible to view objects in Web Storage using the Developer Tools’ Storage Inspector.

An Example Application
If you remember my recent post, it was a currency converter application with the exchange rate hard-coded in multiple places in the JavaScript. Obviously this isn’t good coding practice. Here we can use Web Storage to store this value, and use the localStorage.getItem() function to provide the exchange rate as a JavaScript variable.
The following is a simple demonstration of an arithmetic operation on two variables in Web Storage:

Substituting the Hard-Coded Values in My Application
In the head element, I declared the following global variable:
var sliderMultiplier = parseInt(localStorage.getItem('currentRate));

Here I’m using parseInt() because objects are always stored as strings, and currentRate must be typed as an integer before our conversion functions can use it. Also, the interface should obviously display the currently-stored value whenever the page loads, so the following lines are included:

And also a form that enables the user to update the currentRate value in localStorage:

Now it’s a simple matter of replacing the hard-coded exchange rate with the sliderMultiplier variable.

Share this:

Like this:

The travel application I’ve been working on (really a set of locally-stored HTML, CSS and JavaScript files) requires a feature that enables quick currency conversions. It also needs to function independently of a working Internet connection.

The first pane has an H2 tag displaying what the exchange rate was when the application was last updated – this is hard-coded – and I’ve added a button that navigates the browser to the XE Currency Converter.

I figured a slider would be the quickest way of implementing a conversion feature in a UI, and it’s more efficient than trying to use a small touchscreen to type the values in. The user sees a price in Japanese currency, and moves the slider to get the approximate value in British pounds.
To make this, I used the onchange function to show the current selected slider value, and appended that to also show the value divided by 148.575 (or whatever the exchange rate happens to be).

Calculations with Values from Multiple Range Controls
Quickly it became evident that a user would find it difficult to get a precise enough conversion with a small slider representing such a large range. I needed to add a couple more sliders.

I spent several hours trying to craft some JavaScript that performs the conversion on the combined values from all three controls – who would have though this would be so tricky! HTML5 provides a workaround for this, with the ‘output‘ tag and the ‘oninput‘ form attribute.

The ‘oninput‘ attribute here contains JavaScript that performs the calculation:
form oninput="result.value=(parseInt(upperRange.value)+parseInt(centreRange.value)+parseInt(lowerRange.value))/(148.75)"

With an output just before the closing form tag:output name="result"

Next, for the application to be usable, it also needs to display the current state of each slider. Fortunately we can chain both ‘onchange’ and ‘oninput’ within the same input tag for each slider:
The range tags now have the following attributes:
input type="range" id="centreRange" min="0" max="10000" value="0" step="1000" onchange="centreValue('JPY: ' + this.value + ' | ' + 'GBP: '+ this.value/148.475)" oninput="midRange(value)" /

Each form element is also assigned an output tag:output for="centreRange" id="centreValue"

Precise Currency Conversion Form
The JavaScript for the next currency conversion pane I borrowed from ProgLogic.com, which uses simple multiplication functions. This is tied to a set of form controls – text boxes and a submit button.

When the button is pressed/clicked, the input fields are updated by poundConverter() and yenConverter() to whichever value multiplied by the exchange rate.

Showing and Hiding Conversion Tables
The other two panels I’ve added as conversion tables, in case the user simply needs a quick lookup to see roughly what the equivalent value is. This uses Bootstrap.css ‘table-striped‘ styling.

Categories

Profile

My name is Michael, and I’m a software developer specialising in clinical systems integration and messaging (API creation, SQL Server, Windows Server, secure comms, HL7/DICOM messaging, Service Broker, etc.), using a toolkit based primarily around .NET and SQL Server, though my natural habitat is the Linux/UNIX command line interface.
Before that, I studied computer security (a lot of networking, operating system internals and reverse engineering) at the University of South Wales, and somehow managed to earn a Masters’ degree. My rackmount kit includes an old Dell Proliant, an HP ProCurve Layer 3 switch, two Cisco 2600s and a couple of UNIX systems.
Apart from all that, I’m a martial artist (Aikido and Aiki-jutsu), a practising Catholic, a prolific author of half-completed software, and a volunteer social worker.