Anders Tornblad, web developer

I'm all about the web

Monthly archive for February 2016

"Hello, World!" in Pascal

How to do "Hello, World!" in Pascal.

program HelloWorld; begin WriteLn('Hello, World!'); end.

Pascal was one of the first computer languages I learned, back in the late 1980s and early 1990s. The Borland Turbo Pascal compiler was really fast, and I once actually took a university course in Computer Science, where we wrote code in Pascal on Macintosh computers. This was in 1996. A few years later, I had the opportunity to try Delphi 8 (Octane), which among other things had an immensly superior "Intellisense" solution.

I think I need to add Pascal definitions to my code formatting script...

For more "Hello, World!" examples, go to the Hello World category.

Finding the right namespace

StackOverflow user graham added a reference to a third-party DLL called ServiceProvider.dll, but couldn't figure out which using directive to use to access the types made available in that DLL.

Most times, the DLL is named after the default namespace, which would suggest that a simple using ServiceProvider; should help, but that didn't work. When using closed-source SDKs that you purchase licenses for from some company, it is pretty common to find that their namespaces are named after the company itself. In this case, the root of the namespace hierarchy was Avaya, after the company.

Object Browser screenshotObject Browser When you double-click the reference in the Solution Explorer, the Object Browser opens up with the double-clicked referenced assembly pre-selected. All you have to do then is to expand the selected row to see all namespaces included in the dll file.

403s for the Naughty List

As I mentioned in Complete Blog Remake, Part 2, there are lots of evil bots out there. They are relentless in their automated search for known exploits, and a lot of those target WordPress installations and plugins. Most of these go through the normal HTTP protocol, trying to find URLs that are routed to some badly written, exploitable PHP code. In my logs, I find thousands of calls to /xmlrpc.php, /wp-admin/admin-ajax.php, /wp-content/uploads/locate.php and others where there are current or older versions that expose known SQL injection or script injection exploits.

Because of how my routing is built, all of these requests are interpreted as possible article titles and sent to the ArticleController's Single(string postname) method, which searches for an article with a weird name, doesn't find it, and responds with a 404 page. The request gets logged by Azure, and when there are many bots (or just one unusually intense one), Azure alerts me of having many client errors in a short time period.

In the beginning, I used these logs to double-check that I hadn't missed any incoming links, but because of the huge amount of bots out there, the requests that I'm really interested in gets drowned out by the low signal-to-noise ratio.

Building the naughty list

Some requests could be people or crawlers (Google, Yahoo, Baidu, ...) just doing their job, following links that may or may not lead somewhere, so I don't want to blindly and automatically block the IP address of everyone making mistakes in typing or following a misspelled link. But if there are a few bad requests from the same IP address (say eight in 24 hours), I will block them.

Other requests are just blatant attempts at finding exploits. I will block the IP address of those calls instantly. The Single method makes use of the PageNotFound method of the base class, so the result is really straightforward:

public ActionResult Single(string postname) { if (postname.StartsWith("xmlrpc.php") || postname.Contains("wp-admin") || postname.Contains("wp-content/plugins")) { return PageNotFound(403); } /* Edited out: Code that searches for the requested article */ if (article == null) { return PageNotFound(); } }

The PageNotFound method of the base class isn't too complicated either. It calls the ApplicationData class to handle the list of suspicious or blocked IP addresses:

public ActionResult PageNotFound(int statusCode = 404) { if (applicationData.SuspectUserAddress(Request.UserHostAddress, statusCode == 403)) { return new HttpStatusCodeResult(403); } else { /* Edited out: Code that gives a nice 404 page */ } }

And here is finally some of the code that keeps track of suspicious IP addresses:

internal bool SuspectUserAddress(string address, bool confidentSuspicion) { // Is this address already blocked? Just return true. if (BlockedAddresses.Contains(address)) return true; // If I'm not sure yet, check some more rules if (!confidentSuspicion) { // How many times has this address acted suspiciously already? int count = SuspiciousRequestAddresses.Count(sra => sra == address); if (count >= 5) { // Do a reverse DNS lookup. Is it NOT a known nice crawler? if (!IsNiceCrawler(address)) { // Then this suspicion is a confident one! confidentSuspicion = true; } } } // Are we sure now? if (confidentSuspicion) { // Remove from list of suspicious requests SuspiciousRequestAddresses.RemoveWhere(sra => sra == address); // Add to list of blocked addresses BlockedAddresses.Add(address); return true; } else { // We are not sure... That means this request should be stored as a suspicious one SuspiciousRequestAddresses.Add(address); return false; } } private bool IsNiceCrawler(string address) { var parsed = IPAddress.Parse(address); var hostInfo = Dns.GetHostEntry(parsed); // Something like ($)|($)|($)|($) string validationRegex = ConfigurationManager.AppSettings["NiceCrawlersRegex"]; // Check all of hostInfo's aliases for one that matches the regex bool isNice = hostInfo.Aliases.Any( alias => Regex.IsMatch(alias, validationRegex, RegexOptions.IgnoreCase) ); return isNice; }

After doing this, the amount of 404s went down by a lot, but the 403 errors started rising. I checked a few times to see that the blocked requests are really exploit attempts, and I feel comfortable with this solution.

Also, I changed my Azure alerts to separate the different 4xx responses. I still want those unhandled 404s to generate an alert so that I can fix broken links. This works really well for me.

Complete blog remake, part 1
Complete blog remake, part 2
403s for the Naughty List (this part)

"Hello, World!" in ZX Spectrum machine code

How to do "Hello, World!" in ZX Spectrum machine code.

CHANOPEN equ 5633 PRINT equ 8252 ld a, 2 ; 3E 02 call CHANOPEN ; CD 01 16 ld de, text ; 11 xx xx ld bc, textend-text ; 01 0E jp PRINT ; 3C 20 text defb 'Hello, World!' defb 13 textend equ $

This piece of code calls two functions in the original ZX Spectrum ROM. First it calls CHAN-OPEN which sets the current output channel to number 2 (normal screen output), and then it calls PRINT, which prints a string of characters to the selected channel. To print this on a ZX Printer, simply select channel 3 instead.

I think I need to add Z80 assembler definitions to my code formatting script...

For more "Hello, World!" examples, go to the Hello World category.

"Hello, World!" in HTML

How to do "Hello, World!" in HTML5.

<!doctype html> <title>Hello, World!</title> <p>Hello, World!

Most of the structure of an HTML document, including the html, head and body elements, can be left out without invalidating the document. Also, most block-level elements are self-closing. For instance, the segment <p>Hello<div>World is perfectly equivalent to <p>Hello</p><div>World</div>, which sometimes can be unintuitive, especially in combination with CSS or the querySelector function.

For more "Hello, World!" examples, go to the Hello World category.

"Hello, World!" in JavaScript

How to do "Hello, World!" in JavaScript.

'use strict'; console.log('Hello, World!')

JavaScript has really matured over the last years. Though it started out as a browser-only language, giving grey hairs to web developers everywhere, it is now a competent language in its own right. Combined with initiatives such as node.js, it performs on par with all other system languages. The code above works in your browser (printing to the developer console) as well as in node.js (printing to your terminal output). And yes, you should always go for strict mode.

For more "Hello, World!" examples, go to the Hello World category.

A simple hamburger button

There are lots of tutorials, pens and fiddles out there describing how to create the perfect hamburger button, as well as a few bloggers telling us to stop using it. Me, I kind of like it, actually. It has become a household item – most people know what it is and what it should do. Also, it has been around for almost 40 years. Check out this history of widgets until 1990

A simple layout

I like trying to keep things as simple as possible, so instead of going all in with SVG, JavaScript, animations and complicated transitions, the HTML markup for my hamburger button is simple:

<button class="hamburger"> <hr> <hr> <hr> </button>

The CSS is almost as simple:

button.hamburger { display: flex; flex-direction: column; justify-content: space-around; align-items: stretch; width: 6vw; height: 6vw; box-sizing: border-box; padding: 1vw; border-raius: 0.8vw; background: #195024; cursor: pointer; } button.hamburger hr { display: block; border: 0; height: 0.5vw; background: white; }

Always some browser issue

This worked like a charm until I tested in Firefox. Even though the button element has justify-content: space-around, the hr elements get lumped together in the middle. Even IE got it right. But just for Firefox, I had to add this to my CSS:

button.hamburger hr + hr { margin-top: 0.5vw; }

"Hello, World!" in PHP

How to do "Hello, World!" in PHP.

<?php echo 'Hello, World!'; ?>

Even though PHP is mostly used for adding server-side functionality to web pages, PHP is actually a self-containing language that can be run on a lot of different platforms, both in a web server and completely stand-alone. When PHP is run inside a web server, the echo function renders output to the response of an HTTP request. When PHP is run from the command line, it prints to the console.

For more "Hello, World!" examples, go to the Hello World category.

"Hello, World!" in Java

How to do "Hello, World!" in Java.

public class Program { public static void main(String[] args) { System.out.println("Hello, World!"); } }

I have never really gotten into the Java world. I wrote some Java code in Notepad back in the 1990s and liked the language, but then I had the misfortune of having to use Eclipse at work a few times, and hated the whole experience, from installation to debugging.

For more "Hello, World!" examples, go to the Hello World category.

"Hello, World!" in C#

How to do "Hello, World!" in C#.

class Program { static void Main() { System.Console.WriteLine("Hello, World!"); } }

For writing desktop and server applications, C# has been my language of choice for over ten years now, both for work and for side projects. I really like PHP too, but I don't think it can measure up to the maturity of C#, even though PHP7 looks really nice. The size of the .NET Framework and all the Open Source NuGet packages available really help focusing on what to do, instead of how to do it.

For more "Hello, World!" examples, go to the Hello World category.

"Hello, World!" in C++

How to do "Hello, World!" in C++.

#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }

About ten years after the birth of the C language, object oriented paradigms were added to form the C++ language. The latest version of the C++ standard is often called C++14.

For more "Hello, World!" examples, go to the Hello World category.

"Hello, World!" in C

How to do "Hello, World!" in C.

#include <stdio.h> int main() { puts("Hello, World!"); return 0; }

The C language is father and grandfather of a whole range of modern languages, like C++, PHP, C#, Java, Objective C, Swift, JavaScript and others. Development of the language is continuing, and the latest version, from December of 2011, is usually called C11. C is still in heavy use, mostly for embedded systems, realtime applications and operating systems on small devices.

For more "Hello, World!" examples, go to the Hello World category.

JavaScript countdown using localStorage

New StackOverflow user Pankaj Badera asked how to create a simple JavaScript timer that would survive reboots of the user's computer.

For the specific question, this is not a good idea, because it seems as if the problem needs to deal with some sort of timing rules (school assignment deadlines, maybe?), in which case a server-side solution is a must. However, the technical aspects is pretty intriguing. As it turns out, I have already faced this problem before, when building Tajmkiper, which handles all of its timing client-side.

In principal, you can start any type of countdown, or "countup", allowing the counter to continue between browser and computer restarts, by simply recording the current time for when an event starts, and then continuously checking the difference between that saved value and the current time of a later event.

In Tajmkiper, this is done for many projects at the same time, but the principle is the same. In the case of this StackOverflow question, there is only one timer. Also, Tajmkiper is meant to be a tool for the user, and not for keeping track of (from the browser's perspective) externally checked rules like deadlines, so a solution involving local storage is fine.

My answer looks like this:

(function() { var started = localStorage['started']; if (started) { // This is not the first time the user opens this file // How long has it been? var diff = - started; if (diff >= 1000 * 60 * 60 * 24 * 7) { // At least one week has passed. Do something here. } else { // Less than a week has passed. Do something else here. } } else { // This is the first time the user opens this file localStorage['started'] =; // Do something else here to welcome the user... } })();

For my project time clock, this happens every time you select a different project. I combine this with keeping track of how much time has been clocked total.

Formatting a truncated float in JavaScript

StackOverflow user nips asked how to format a floating point number in JavaScript, truncating the value instead of rounding it.

According to the question, this was the desired result:

  • The value 12.999 must be displayed as 12.99
  • The value 14 must be displayed as 14.00

The page gives a thorough example of how to perform decimal rounding correctly, avoiding any rounding errors in the process. For this question, however, a simple multiplication-division pair is surely good enough:

// Step by step var multiplied = value * 100; var truncated = Math.floor(multiplied); var divided = truncated * 0.01; var output = divided.toFixed(2); // One-liner version var output = (Math.floor(value * 100) * 0.01).toFixed(2);

The above code performs the following steps, in order:

  • Value is multiplied by 100
    12.999 => 1299.9
    14 => 1400
  • Value is truncated using the Math.floor function
    1299.9 => 1299
    1400 => 1400
  • Value is multiplied by 0.01
    1299 => 12.99
    1400 => 14
  • Value is formatted for printing using two decimal places using the Number.prototype.toFixed function
    12.99 => "12.99"
    14 => "14.00"

Most languages do have functions called round, ceil, floor or similar ones, but almost all of them round to the nearest integer, so the multiply-round-divide chain (or divide-round-multiply for rounding to tens, hundreds, thousands...) is a good pattern to know.

In JavaScript there is no float datatype like in a lot of other languages, but the Number object is used for both integers and floating point numbers. Internally, numbers are just 64 bit floating point numbers (source:, conforming to the IEEE 754 standard. So when dealing with numbers in JavaScript, you always need to take floating point precision into consideration!

Complete blog remake, part 2

This is the second part of a series of articles about my complete blog remake. If you haven't read the first part, here it is: Complete blog remake, part 1

Last week I wrote about completely remaking my blog, leaving WordPress, PHP, MySQL and Loopia behind. One of my main concerns was to keep all urls intact, since I know that some of my old articles have a lot of incoming links. The whole url scheme reverse-engineering was the focus of the first part of this article series.

The ghost of WordPress unpatched

After taking a leap of faith and actually publishing the first version of my reverse-engineered blog engine (along with all of the articles) to Azure, I kept a vigil eye on the access logs. I wanted to make sure that I hadn't missed any incoming links. I discovered two cases of misspelled addresses and the non-existing robots.txt and favicon.ico, that I could fix quickly, but most of all there were hundreds of of 404's for the WordPress administration panel, WordPress-specific AJAX url's, some requests for /xmlrpc.php, and a lot of requests for (which I found out after some searching) known security flaws in older WordPress versions.

Virtually every evil bot net out there is trying to exploit our blogs, hoping to find an unpatched WordPress installation. This is one of the reasons I wanted to leave WordPress behind. It is also the reason I have chosen to not have an administration web interface for my blog. Instead I am actually using Visual Studio, not just for coding, running unit tests, debugging, testing and publishing to Azure, but also for writing my articles and publishing them.

Putting T4 text templates to work

My article data files are really simple text files, each containing a title, a category, some labels and the markup of the article itself. I wrote a simple T4 template for converting this to an XML file. When I have written an article, I simply run the TextTemplatingFileGenerator tool and then click Publish to send the new article to Azure. Then I just wait for the scheduled task (runs once per hour) to pick up the new article and make it visible.

My favorite IDE, by far, is Visual Studio, and my favorite language is without doubt C#. I have blogged a lot about JavaScript and PHP too, but I have to admit that C# is my number one. Being able to actually use Visual Studio as my main tool for blogging (both when writing the Blog engine code, and when writing articles) feels really great.

So far, everything that I have done fits well within the Free tier of my Azure subscription. So not only have I a blogging tool that suits me better, I have also reduced my web hosting cost with 100 %. There is still more to write about, like having ASP.NET MVC Areas that map to my subdomains, like, and I leave that for the next part of this series.

Complete blog remake, part 1
Complete blog remake, part 2 (this part)
403s for the Naughty List

Keep NumLock on permanently

One of the remnants of early PC computers is the Num Lock key. For most people, like me, it is just a nuisance. I mostly use my laptop with a dock connected to a standard 102 key keyboard, so when I use the numpad, I want numbers to appear – I don't want the cursor to move semi-randomly across my document. When I sometimes hit the Num Lock key by accident, I'm always in for a few seconds of feeling annoyed.

I'm not the only one thinking this. A quick search for keep num lock key on permanently windows 10 gives hundreds of results, but most answers focus on making it turn on at reboot. I could only find one good answer to the actual question.

If you have the same problem, try importing this in Regedit (run as administrator):

Windows Registry Editor Version 5.00 [HKEY_USERS\.DEFAULT\Control Panel\Keyboard] "InitialKeyboardIndicators"="2147483650" [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,00,00,45,00,00,00,00,00

This will fix two things:

  • The first setting makes Num Lock turned on by default at reboot
  • The second setting disables the Num Lock key (key code 45) completely so that its signals don't reach the operating system correctly


Use this tip on your own risk. Don't forget to backup your registry before doing this. Changing things in RegEdit is always risky and in no event will I be liable for any loss or damage arising from the use of this information.

Revisiting CssFlip

When I first started experimenting with modern Web APIs, 3D transforms was still an experimental feature. Browser support was limited and shaky, and required vendor prefixes. These days support is much better, but there are still a lot of quirks when it comes to browser implementation.

Back in 2011, I wrote a demo called CSS Page Flip, using a combination of CSS and some JavaScript to let a user flip through pages in a book. The transitions are declared in CSS and are triggered by JavaScript. Pages on the left have their transform-origin set to their right edge, which is aligned to the horizontal center of the screen, while pages on the right have their transform-origin set to their left edge. By applying backface-visibility: hidden, I can then rotate pages along the Y axis for a pretty simple effect.

#book { perspective: 2000px; transform-style: preserve-3d; } .page { width: 50%; height: 100%; position: absolute; top: 0px; left: 0px; margin-left: 50%; overflow: hidden; transform-style: flat; backface-visibility: hidden; transition: none; transform: none; } .page:first-child { margin-left: 0px; transform-origin: right center; } .page:last-child { transform-origin: left center; } .currentFold.forward > .page:last-child { transform: rotateY(0deg); } .nextFold.forward > .page:first-child { transform: rotateY(179.9deg); } .currentFold.backward > .page:first-child { transform: rotateY(0deg); } .nextFold.backward > .page:last-child { transform: rotateY(-179.9deg); } .folding .page { transition: all 1s ease-in-out; } .folding > .currentFold.forward > .page:last-child { transform: rotateY(-179.9deg); } .folding > .nextFold.forward > .page:first-child { transform: translateZ(1px) rotateY(0deg); } .folding > .currentFold.backward > .page:first-child { transform: rotateY(179.9deg); } .folding > .nextFold.backward > .page:last-child { transform: translateZ(1px) rotateY(0deg); }

It took a lot of fiddling to find good values for rotateY(). Almost every new version of Webkit broke my experiment, but I eventually settled on a combination of 0deg, -180deg and 180deg.

CSS Flip in EdgeEdge behaving badly A couple of years later, the major browsers started supporting 3D transforms, even without vendor prefixes. Unfortunately all of them have different ideas about how to transition from 180deg or -180deg to 0deg. Finally I thought of forcing the browsers to do what I want by having -179.9deg and 179.9deg. This works fine now, unless for (of course) IE and Edge. IE doesn't even support 3D transforms correctly without prefix, and for some reason Edge treats the transformation matrix differently than the other browsers, completely breaking part of the animation.

Apart from the page flipping, the demo also has an automatic page layout mechanism that reflows the chapters and the text blocks when needed. In the original demo, the contents of the book was actually a detailed description of how the demo was made, but unfortunately the original content was lost at some point. Now it is my personal story instead. Enjoy!

During the next week or two, I will make an effort to bring the solution forward into the 2016 state of mainstream browsers, including the following:

  • Fix scroll wheel flipping in Firefox
  • Handle chapter navigation using history.pushState()
  • Add some interactive stuff on some of the pages
  • Some effort of fixing the weird behavior in Microsoft Edge
  • Minimal effort of making it work in Microsoft IE

When that is done, I will open-source the whole thing on GitHub.